answer stringlengths 17 10.2M |
|---|
package edu.rpi.cs.yacs.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Period {
@SerializedName("type")
@Expose
private String type;
@SerializedName("day")
@Expose
private Integer day;
@SerializedName("start")
@Expose
private Integer start;
@SerializedName("end")
@Expose
private Integer end;
/**
*
* @return
* The type
*/
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The day
*/
public Integer getDay() {
return day;
}
/**
*
* @param day
* The day
*/
public void setDay(Integer day) {
this.day = day;
}
/**
*
* @return
* The start
*/
public Integer getStart() {
return start;
}
/**
*
* @param start
* The start
*/
public void setStart(Integer start) {
this.start = start;
}
/**
*
* @return
* The end
*/
public Integer getEnd() {
return end;
}
/**
*
* @param end
* The end
*/
public void setEnd(Integer end) {
this.end = end;
}
} |
package net.sf.taverna.t2.workbench.ui.servicepanel.tree;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
import net.sf.taverna.t2.workbench.icons.WorkbenchIcons;
import net.sf.taverna.t2.workbench.ui.servicepanel.ServicePanel;
import net.sf.taverna.t2.lang.ui.ShadedLabel;
@SuppressWarnings("serial")
public class TreePanel extends JPanel {
private static int MAX_EXPANSION = 100;
private static final int SEARCH_WIDTH = 15;
protected Set<TreePath> expandedPaths = new HashSet<TreePath>();
protected FilterTreeModel filterTreeModel;
protected JTextField searchField = new JTextField(SEARCH_WIDTH);
protected JTree tree = new JTree();
protected JScrollPane treeScrollPane;
public TreePanel(FilterTreeModel treeModel) {
filterTreeModel = treeModel;
initialize();
}
public void expandTreePaths() throws InterruptedException,
InvocationTargetException {
// Filter appliedFilter = filterTreeModel.getCurrentFilter();
// if (appliedFilter == null) {
for (int i = 0; (i < tree.getRowCount()) && (i < MAX_EXPANSION); i++) {
tree.expandRow(i);
}
// } else {
// boolean rowsFinished = false;
// for (int i = 0; (!appliedFilter.isSuperseded()) && (!rowsFinished)
// && (i < MAX_EXPANSION); i++) {
// TreePath tp = tree.getPathForRow(i);
// if (tp == null) {
// rowsFinished = true;
// } else {
// if (!appliedFilter.pass((DefaultMutableTreeNode) tp
// .getLastPathComponent())) {
// tree.expandRow(i);
}
protected void initialize() {
setLayout(new BorderLayout());
treeScrollPane = new JScrollPane(tree);
tree.setModel(filterTreeModel);
tree.addTreeWillExpandListener(new TreeExpandListener());
tree.setCellRenderer(createCellRenderer());
tree.setSelectionModel(new FilterTreeSelectionModel());
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel filterLabel = new JLabel("Filter: ");
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.0;
c.anchor = GridBagConstraints.LINE_START;
topPanel.add(filterLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
topPanel.add(searchField, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 2;
c.gridy = 0;
c.weightx = 0.0;
topPanel.add(new JButton(new ClearAction()), c);
c.gridx = 3;
c.weightx = 0.2;
topPanel.add(new JPanel(), c);
JPanel topExtraPanel = new JPanel();
topExtraPanel.setLayout(new BorderLayout());
topExtraPanel.add(topPanel, BorderLayout.NORTH);
Component extraComponent = createExtraComponent();
if (extraComponent != null) {
JPanel extraPanel = new JPanel();
extraPanel.setLayout(new BorderLayout());
extraPanel.add(extraComponent, BorderLayout.WEST);
topExtraPanel.add(extraPanel, BorderLayout.CENTER);
}
add(topExtraPanel, BorderLayout.NORTH);
add(treeScrollPane, BorderLayout.CENTER);
searchField.addKeyListener(new SearchFieldKeyAdapter());
}
protected Component createExtraComponent() {
return null;
}
protected TreeCellRenderer createCellRenderer() {
return new FilterTreeCellRenderer();
}
public synchronized void runFilter() throws InterruptedException,
InvocationTargetException {
String text = searchField.getText();
if (text.length() == 0) {
setFilter(null);
for (TreePath tp : expandedPaths) {
tree.expandPath(tp);
}
} else {
setFilter(createFilter(text));
expandTreePaths();
}
}
public Filter createFilter(String text) {
return new MyFilter(text);
}
public void setFilter(Filter filter) {
if (tree.getCellRenderer() instanceof FilterTreeCellRenderer) {
((FilterTreeCellRenderer)tree.getCellRenderer()).setFilter(filter);
}
filterTreeModel.setFilter(filter);
}
protected class ClearAction extends AbstractAction {
private ClearAction() {
super("Clear");
}
public void actionPerformed(ActionEvent e) {
searchField.setText("");
try {
runFilter();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
protected class ExpandRowRunnable implements Runnable {
int rowNumber;
public ExpandRowRunnable(int rowNumber) {
this.rowNumber = rowNumber;
}
public void run() {
tree.expandRow(rowNumber);
}
}
protected class RunFilter implements Runnable {
public void run() {
Filter oldFilter = filterTreeModel.getCurrentFilter();
if (oldFilter != null) {
oldFilter.setSuperseded(true);
}
try {
runFilter();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected class SearchFieldKeyAdapter extends KeyAdapter {
private final Runnable runFilterRunnable;
Timer timer = new Timer();
private SearchFieldKeyAdapter() {
this.runFilterRunnable = new RunFilter();
}
public void keyReleased(KeyEvent e) {
timer.cancel();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
SwingUtilities.invokeLater(runFilterRunnable);
}
}, 500);
}
}
protected class TreeExpandListener implements TreeWillExpandListener {
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
if (searchField.getText().length() == 0) {
expandedPaths.remove(event.getPath());
}
}
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
if (searchField.getText().length() == 0) {
expandedPaths.add(event.getPath());
}
}
}
} |
package wcdi.wcdiplayer;
import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.TextView;
import java.io.File;
import wcdi.wcdiplayer.widget.AlbumArrayAdapter;
public class AlbumFragment extends Fragment implements AbsListView.OnItemClickListener {
public static AlbumFragment newInstance(File file) {
AlbumFragment fragment = new AlbumFragment();
Bundle args = new Bundle();
args.putString("path", file.toString());
fragment.setArguments(args);
return fragment;
}
private AbsListView mListView;
private AlbumArrayAdapter mAdapter;
public AlbumFragment() {
}
private File path;
@Override
public void setArguments(Bundle args) {
path = new File(args.getString("path"));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
mAdapter = new AlbumArrayAdapter(getActivity(), R.layout.album_list_item);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_album, container, false);
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
if (mListView.getCount() == 0) {
try {
mAdapter.addAll(path.listFiles());
} catch (NullPointerException e) {
System.out.println(e.getMessage().toString());
}
}
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView directoryName = (TextView) view.findViewById(R.id.directoryName);
path = new File(directoryName.getText().toString());
if (path.isDirectory()) {
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, AlbumFragment.newInstance(path))
.addToBackStack(null)
.commit();
} else {
// ListActivityPlayingServiceList
// List<String> stringList = null;
// for (File f : path.getParentFile().listFiles()) {
// stringList.add(f.toString());
getFragmentManager()
.beginTransaction()
// .replace(R.id.fragment, PlayingFragment.newInstance(stringList, null))
.replace(R.id.fragment, PlayingFragment.newInstance(path.getParentFile(), null))
.addToBackStack(null)
.commit();
}
}
} |
package com.devansh.thrift;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TField;
import org.apache.thrift.protocol.TMessageType;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.protocol.TList;
import org.apache.thrift.protocol.TMap;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSet;
import org.apache.thrift.protocol.TStruct;
import org.apache.thrift.transport.TTransport;
import org.json.JSONArray;
import java.nio.ByteBuffer;
import java.util.LinkedList;
public class HumanReadableJsonProtocol extends TProtocol {
private static final String METHOD_KEY = "method";
private static final String SERVICES_KEY = "services";
private static final String NAME_KEY = "name";
private static final String ARGUMENTS_KEY = "arguments";
private static final String RESULT_KEY = "result";
private static final String SUCCESS_KEY = "success";
private static final String EXCEPTIONS_KEY = "exceptions";
private static final String EXCEPTION_KEY = "exception";
private static final String FUNCTIONS_KEY = "functions";
private static final String KEY_KEY = "key";
private static final String ONEWAY_KEY = "oneway";
private static final String FIELDS_KEY = "fields";
private static final String STRUCTS_KEY = "structs";
private static final String MESSAGE_KEY = "message";
private static final String CLASS_KEY = "class";
private static final String TYPE_ID_KEY = "typeId";
private static final String TYPE_KEY = "type";
private static final String KEY_TYPE_ID_KEY = "keyTypeId";
private static final String KEY_TYPE_KEY = "keyType";
private static final String VALUE_TYPE_ID_KEY = "valueTypeId";
private static final String VALUE_TYPE_KEY = "valueType";
private static final String ELEM_TYPE_ID_KEY = "elemTypeId";
private static final String ELEM_TYPE_KEY = "elemType"
private static final String RETURN_TYPE_ID_KEY = "returnTypeId";
private static final String RETURN_TYPE_KEY = "returnType";
private JSONArray metadata;
private String service;
private LinkedList<Object> params;
private TSimpleJSONProtocol oprot;
public HumanReadableJsonProtocol(TTransport transport, JSONArray metadata, String service) {
super(transport);
this.metadata = metadata;
this.service = service;
this.params = new LinkedList<>();
oprot = new TSimpleJSONProtocol(transport);
}
@Override
public void writeMessageBegin(TMessage tMessage) throws TException {
oprot.writeStructBegin(null);
oprot.writeString(METHOD_KEY);
oprot.writeString(tMessage.name);
switch (tMessage.type) {
case TMessageType.CALL:
oprot.writeString(ARGUMENTS_KEY);
break;
case TMessageType.REPLY:
oprot.writeString(RESULT_KEY);
break;
case TMessageType.EXCEPTION:
oprot.writeString(EXCEPTION_KEY);
break;
}
}
@Override
public void writeMessageEnd() throws TException {
oprot.writeStructEnd();
}
@Override
public void writeStructBegin(TStruct tStruct) throws TException {
oprot.writeStructBegin(tStruct);
}
@Override
public void writeStructEnd() throws TException {
oprot.writeStructEnd();
}
@Override
public void writeFieldBegin(TField tField) throws TException {
oprot.writeString(tField.name);
}
@Override
public void writeFieldEnd() throws TException {
// No-op
}
@Override
public void writeFieldStop() throws TException {
// No-op
}
@Override
public void writeMapBegin(TMap tMap) throws TException {
oprot.writeStructBegin(null);
}
@Override
public void writeMapEnd() throws TException {
oprot.writeStructEnd();
}
@Override
public void writeListBegin(TList tList) throws TException {
oprot.writeListBegin(tList);
}
@Override
public void writeListEnd() throws TException {
oprot.writeListEnd();
}
@Override
public void writeSetBegin(TSet tSet) throws TException {
oprot.writeSetBegin(tSet);
}
@Override
public void writeSetEnd() throws TException {
oprot.writeStructEnd();
}
@Override
public void writeBool(boolean b) throws TException {
oprot.writeBool(b);
}
@Override
public void writeByte(byte b) throws TException {
oprot.writeByte(b);
}
@Override
public void writeI16(short i) throws TException {
oprot.writeI16(i);
}
@Override
public void writeI32(int i) throws TException {
oprot.writeI32(i);
}
@Override
public void writeI64(long l) throws TException {
oprot.writeI64(l);
}
@Override
public void writeDouble(double v) throws TException {
oprot.writeDouble(v);
}
@Override
public void writeString(String s) throws TException {
oprot.writeString(s);
}
@Override
public void writeBinary(ByteBuffer byteBuffer) throws TException {
oprot.writeBinary(byteBuffer);
}
@Override
public TMessage readMessageBegin() throws TException {
return null;
}
@Override
public void readMessageEnd() throws TException {
}
@Override
public TStruct readStructBegin() throws TException {
return null;
}
@Override
public void readStructEnd() throws TException {
}
@Override
public TField readFieldBegin() throws TException {
return null;
}
@Override
public void readFieldEnd() throws TException {
}
@Override
public TMap readMapBegin() throws TException {
return null;
}
@Override
public void readMapEnd() throws TException {
}
@Override
public TList readListBegin() throws TException {
return null;
}
@Override
public void readListEnd() throws TException {
}
@Override
public TSet readSetBegin() throws TException {
return null;
}
@Override
public void readSetEnd() throws TException {
}
@Override
public boolean readBool() throws TException {
return false;
}
@Override
public byte readByte() throws TException {
return 0;
}
@Override
public short readI16() throws TException {
return 0;
}
@Override
public int readI32() throws TException {
return 0;
}
@Override
public long readI64() throws TException {
return 0;
}
@Override
public double readDouble() throws TException {
return 0;
}
@Override
public String readString() throws TException {
return null;
}
@Override
public ByteBuffer readBinary() throws TException {
return null;
}
} |
package facespace;
import java.sql.*; //import the file containing definitions for the parts
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.*;
/**
*
* @author Kyle Monto (kwm19@pitt.edu) | Joe Meszar (jwm54@pitt.edu)
*/
public class DatabaseConnection {
private static Connection connection; //used to hold the jdbc connection to the DB
private Statement statement; //used to create an instance of the connection
private PreparedStatement prepStatement; //used to create a prepared statement, that will be later reused
private ResultSet resultSet; //used to hold the result of your query (if one exists)
private String query; //this will hold the query we are using
public DatabaseConnection() throws SQLException {
//to run in netbeans need to add ojbdc6.jar to project libraries
String username = "";
String password = "";
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get the username and password
System.out.print("Please enter DB username: ");
username = keyIn.nextLine().toLowerCase();
System.out.print("Please enter DB password: ");
password = keyIn.nextLine();
try {
// Register the oracle driver.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//This is the location of the database.
String url = "jdbc:oracle:thin:@class3.cs.pitt.edu:1521:dbclass"; // school db
//String url = "jdbc:oracle:thin:@localhost:1521:xe"; // localhost db (debug)
//create the database connection
connection = DriverManager.getConnection(url, username, password);
} catch (Exception Ex) {
System.out.println("\nError connecting to database. Machine Error: " + Ex.toString());
System.exit(0); // immediately exit
} finally {
}
}
/**
* Closes the database connection.
*/
public void closeConnection() {
try {
connection.close();
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
}
/**
* Adds a new user to a group in the database system.
*/
public void addToGroup() {
try {
//initialize input variables
String userEmail = null;
String groupName = null;
int userID = 0;
int groupID = 0;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//make sure user exists
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// get the groupName and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter a group name: ");
groupName = keyIn.nextLine().trim().toUpperCase();
} while (groupName == null || groupName.equalsIgnoreCase(""));
//make sure group exists
//query to make sure user exists and get their ID
query = "SELECT ID FROM GROUPS WHERE UPPER(NAME) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, groupName);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No Group Found");
} else {
groupID = resultSet.getInt(1);
}
// show the user input
System.out.println(String.format("User ID: {%d} Group ID: {%d}", userID, groupID));
//Insert query statement
query = "INSERT INTO GROUPMEMBERS (GROUPID, USERID, DATEJOINED) VALUES (?, ?, current_timestamp)";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, groupID);
prepStatement.setInt(2, userID);
prepStatement.executeUpdate();
// get the updated data
query = "SELECT G.NAME, U.FNAME, U.LNAME, U.EMAIL, GM.DATEJOINED FROM GROUPS G "
+ "LEFT JOIN GROUPMEMBERS GM ON GM.GROUPID = G.ID "
+ "LEFT JOIN USERS U ON U.ID = GM.USERID "
+ "WHERE GM.GROUPID=? AND GM.USERID=?";
prepStatement = connection.prepareStatement(query); //create a new instance
prepStatement.setInt(1, groupID);
prepStatement.setInt(2, userID);
resultSet = prepStatement.executeQuery();
// display the new list of users
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [GROUPNAME],[FNAME],[LNAME],[EMAIL],[DATEJOINED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (SQLException e) {
int errorCode = e.getErrorCode();
switch (errorCode) {
case 20000:
System.out.println("Group Membership limit is already met");
break;
default:
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
break;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else if (e.getMessage().equals("No Group Found")) {
System.out.println("The group name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Adds a new group to the database system.
*/
public void createGroup() {
try {
//initialize input variables
String groupName = null;
String description = null;
String limitS = null;
int limitI = 0;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get the firstName and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter a group name: ");
groupName = keyIn.nextLine().trim().toUpperCase();
} while (groupName == null || groupName.equalsIgnoreCase(""));
// get the lastName and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter a description for the group: ");
description = keyIn.nextLine().trim();
} while (description == null || description.equalsIgnoreCase(""));
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter a membership limit: ");
limitS = keyIn.nextLine().trim();
} while (limitS == null || limitS.equalsIgnoreCase("") || !Pattern.matches("\\d+", limitS));
limitI = Integer.parseInt(limitS);
if (limitI <= 0) {
throw new Exception("Group membership limit must be greater than 0");
}
// show the user input
System.out.println(String.format("Group Name: {%s} description: {%s} limit: {%s}", groupName, description, limitS));
//Insert query statement
query = "INSERT INTO GROUPS (NAME, DESCRIPTION, LIMIT, DATECREATED) VALUES (?, ?, ?, current_timestamp)";
//Create the prepared statement
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, groupName);
prepStatement.setString(2, description);
prepStatement.setInt(3, limitI);
prepStatement.executeUpdate();
// get the new list of users
statement = connection.createStatement(); //create an instance
query = "Select * FROM groups";
resultSet = statement.executeQuery(query);
// display the new list of users
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [NAME],[DESCRIPTION],[LIMIT],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Adds a new user to the database system.
*/
public void createUser() {
try {
//initialize input variables
String firstName = null;
String lastName = null;
String email = null;
String dateOfBirth = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get the firstName and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter a first name: ");
firstName = keyIn.nextLine().trim().toUpperCase();
} while (firstName == null || firstName.equalsIgnoreCase(""));
// get the lastName and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter a last name: ");
lastName = keyIn.nextLine().trim().toUpperCase();
} while (lastName == null || lastName.equalsIgnoreCase(""));
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter a valid email address: ");
email = keyIn.nextLine().trim().toLowerCase();
} while (email == null || email.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", email));
// get the date of birth (DOB) and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Enter a valid date of birth (DD-MON-YYYY): ");
dateOfBirth = keyIn.nextLine().trim().toUpperCase();
} while (dateOfBirth == null || dateOfBirth.equalsIgnoreCase("") || !Pattern.matches("[0123]{1}\\d{1}-\\w{3}-\\d{4}", dateOfBirth));
// show the user input
System.out.println(String.format("\nFirst Name: {%s} LastName: {%s} Email: {%s} DOB: {%s}", firstName, lastName, email, dateOfBirth));
// Create the query and insert
query = "INSERT INTO USERS(FNAME, LNAME, EMAIL, DOB, LASTLOGIN, DATECREATED) VALUES (?, ?, ?, TO_DATE(?,'DD-MON-YYYY'), NULL, current_timestamp)";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, firstName);
prepStatement.setString(2, lastName);
prepStatement.setString(3, email);
prepStatement.setString(4, dateOfBirth);
prepStatement.executeUpdate();
// get the new list of users
statement = connection.createStatement(); //create an instance
query = "Select * FROM USERS";
resultSet = statement.executeQuery(query);
// display the new list of users
System.out.println("\nQuery success, data is...\n"
+ "[RECORD#] [ID],[FNAME],[LNAME],[EMAIL],[BIRTHDATE],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5) + ", "
+ resultSet.getString(7));
counter++;
}
System.out.println("\nSUCCESS!");
} catch (SQLException e) {
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Displays all of that user's pending, and established, friendships.
*/
public void displayFriends() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d}", userID));
//query to display friends
query = "SELECT U.FNAME AS FIRSTNAME,\n"
+ "U.LNAME AS LASTNAME,\n"
+ "U.EMAIL AS EMAILADDRESS,\n"
+ "F.APPROVED AS APPROVED,\n"
+ "F.DATEAPPROVED AS DATEAPPROVED\n"
+ "FROM FRIENDSHIPS F, USERS U\n"
+ "WHERE F.FRIENDID = U.ID\n"
+ "AND F.USERID = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
resultSet = prepStatement.executeQuery();
System.out.println("\nQuery success, data is...\n"
+ "[RECORD#] [FNAME],[LNAME],[EMAIL],[APPROVED?],[DATEAPPROVED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (SQLException e) {
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Given a user, look up all of the messages sent to that user (either
* directly or via a group that they belong to).
*/
public void displayMessages() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d}", userID));
//query to display friends
query = "SELECT U.FNAME AS FIRSTNAME,\n"
+ " U.LNAME AS LASTNAME,\n"
+ " M.SUBJECT AS SUBJECT,\n"
+ " M.BODY AS BODY,\n"
+ " M.DATECREATED AS DATE_RECEIVED\n"
+ "FROM MESSAGES M, USERS U\n"
+ "WHERE RECIPIENTID = ? \n"
+ "AND U.ID = M.SENDERID\n"
+ "ORDER BY DATE_RECEIVED";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
resultSet = prepStatement.executeQuery();
System.out.println("\nMessages for the users are...\n"
+ "[RECORD#] [FNAME],[LNAME],[SUBJECT],[BODY],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (SQLException e) {
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Given a user, look up all of the messages sent to that user (either
* directly or via a group that they belong to).
*/
public void displayNewMessages() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
Timestamp lastLogin = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d}", userID));
query = "SELECT LASTLOGIN FROM USERS WHERE ID = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
resultSet = prepStatement.executeQuery();
//check result set to see whether last log in is null
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
lastLogin = resultSet.getTimestamp(1);
}
if (lastLogin == null) {
//query if last login is null, just display all messages
System.out.println("No previous login, displaying all messages");
query = "SELECT U.FNAME AS FIRSTNAME,\n"
+ " U.LNAME AS LASTNAME,\n"
+ " U.EMAIL AS EMAILADDRESS,\n"
+ " M.SUBJECT AS SUBJECT,\n"
+ " M.BODY AS BODY,\n"
+ " M.DATECREATED AS DATE_RECEIVED\n"
+ "FROM MESSAGES M, USERS U\n"
+ "WHERE RECIPIENTID = ? \n"
+ "AND U.ID = M.SENDERID\n"
+ "ORDER BY DATE_RECEIVED";
} else {
//query if last login is not null, and will display all message
//after the time of last login
query = "SELECT U.FNAME AS FIRSTNAME,\n"
+ " U.LNAME AS LASTNAME,\n"
+ " U.EMAIL AS EMAILADDRESS,\n"
+ " M.SUBJECT AS SUBJECT,\n"
+ " M.BODY AS BODY,\n"
+ " M.DATECREATED AS DATE_RECEIVED\n"
+ "FROM MESSAGES M, USERS U\n"
+ "WHERE RECIPIENTID = ? \n"
+ "AND U.ID = M.SENDERID\n"
+ "AND M.DATECREATED > ?\n"
+ "ORDER BY DATE_RECEIVED";
}
prepStatement = connection.prepareStatement(query);
if (lastLogin == null) {
//query if last login is null, just display all messages
prepStatement.setInt(1, userID);
} else {
//query if last login is not null, and will display all message
//after the time of last login
prepStatement.setInt(1, userID);
prepStatement.setTimestamp(2, lastLogin);
}
resultSet = prepStatement.executeQuery();
System.out.println("\nMessages for the users are...\n"
+ "[RECORD#] [FNAME],[LNAME],[EMAIL],[SUBJECT],[BODY],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5) + ", "
+ resultSet.getString(6));
counter++;
}
} catch (SQLException ex) {
System.out.println(String.format("\n!! SQL Error: %s", ex.getMessage()));
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Remove a user and all of their information from the system.
*/
public void dropUser() {
try {
// intialize input variables for user
String userEmail = null;
int userID = 0;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
// build a sql query to get the user's ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user,
// otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// use this ID to delete the user, which will fire a
// trigger and remove all of their data
query = "DELETE FROM USERS WHERE ID=?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
resultSet = prepStatement.executeQuery();
System.out.println("\nSUCCESS!");
} catch (SQLException e) {
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) { statement.close(); }
if (prepStatement != null) { prepStatement.close(); }
if (resultSet != null) { resultSet.close(); }
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Creates an established friendship from one user to another inside the database.
*/
public void establishFriendship() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
int friendID = 0;
String friendEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
/**
* GET THE BEFRIENDING USER'S EMAIL
*
*/
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the friend's email address: ");
friendEmail = keyIn.nextLine().trim().toLowerCase();
} while (friendEmail == null || friendEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", friendEmail));
if (friendEmail.equals(userEmail)) {
throw new Exception("You cannot friend yourself!");
}
//query to make sure friend exists and get their ID
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, friendEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
friendID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("\nID of user: {%d} ID of friend: {%d}", userID, friendID));
/**
* GET THE STATUS OF THIS FRIENDSHIP (IF EXISTS), AND EITHER
*
* 1) CREATE A NEW PENDING FRIENDSHIP 2) CREATE AN APPROVED
* FRIENDSHIP 3) TELL THE USER THAT A FRIENDSHIP ALREADY EXISTS
*
*/
//Select the current status of a friendship between the 2 users
query = "SELECT * FROM FRIENDSHIPS WHERE USERID = ? AND FRIENDID = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.setInt(2, friendID);
resultSet = prepStatement.executeQuery();
//normally insert userid, friendid, then friendid, userid
boolean oppositeDirection = false;
//if resultSet has a next then there is a friendship present
if (resultSet.next()) {
//if the result is 0 then its pending
int status = resultSet.getInt(3);
if (status == 0) {
System.out.println("Friendship is pending");
//carry out from the opposite direction
oppositeDirection = true;
} else if (status == 1) { //otherwise its already established
System.out.println("Friendship is already established");
//quit operation
return;
}
}
query = "INSERT INTO FRIENDSHIPS (USERID, FRIENDID) VALUES (?, ?)";
String countQuery = "SELECT COUNT(*) FROM FRIENDSHIPS WHERE USERID = ? AND FRIENDID = ?";
if (oppositeDirection == false) {
//insert in both directions
//Create the prepared statement
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.setInt(2, friendID);
prepStatement.executeUpdate();
prepStatement = connection.prepareStatement(countQuery);
prepStatement.setInt(1, friendID);
prepStatement.setInt(2, userID);
resultSet = prepStatement.executeQuery();
if (resultSet.next()) {
if (resultSet.getInt(1) == 0) {
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, friendID);
prepStatement.setInt(2, userID);
prepStatement.executeUpdate();
}
}
} else {
//insert in only the opposite direction of the
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, friendID);
prepStatement.setInt(2, userID);
prepStatement.executeUpdate();
}
//just a query to show that the row was inserted
query = "SELECT U.FNAME, U.LNAME, U.EMAIL, F.APPROVED, F.DATEAPPROVED\n"
+ "FROM FRIENDSHIPS F, USERS U\n"
+ "WHERE ((F.USERID = ? AND F.FRIENDID = ?)\n"
+ "OR (F.USERID = ? AND F.FRIENDID = ?))\n"
+ "AND F.USERID = U.ID";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.setInt(2, friendID);
prepStatement.setInt(3, userID);
prepStatement.setInt(4, friendID);
resultSet = prepStatement.executeQuery();
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [FNAME],[LNAME],[EMAIL],[APPROVED?],[DATEAPPROVED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (SQLException e) {
int errorCode = e.getErrorCode();
switch (errorCode) {
case 20001:
System.out.println("Friendship already pending");
break;
case 20002:
System.out.println("Friendship already established");
break;
default:
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
break;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Creates a pending friendship from one user to another inside the
* database.
*/
public void initiateFriendship() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
int friendID = 0;
String friendEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
/**
* GET THE EMAIL OF THE USER INITIATING A FRIENDSHIP
*
*/
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
// query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
// check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("The email entered does not exist");
} else {
userID = resultSet.getInt(1);
}
/**
* GET THE EMAIL OF THE USER TO FRIEND
*
*/
// get the email of the friend and normalize (lowercase with no leading/trailing spaces)
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the email address of the person to friend: ");
friendEmail = keyIn.nextLine().trim().toLowerCase();
} while (friendEmail == null || friendEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", friendEmail));
if (friendEmail.equals(userEmail)) {
throw new Exception("You cannot friend yourself!");
}
// query to make sure friend exists and get their ID
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, friendEmail);
resultSet = prepStatement.executeQuery();
// check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("The friend name entered does not exist");
} else {
friendID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d} ID of friend: {%d}", userID, friendID));
/**
* USE THE USER_ID AND FRIEND_ID TO CREATE A "FRIENDSHIP". THIS
* DEPENDS ON THE TRIGGER THAT WAS BUILT, WHICH WILL DO ONE OF TWO
* THINGS:
*
* 1) Create a "Pending Friendship" 2) Create a "Friendship"
*
*/
// insert statement for establishing pending friendship
query = "INSERT INTO FRIENDSHIPS (USERID, FRIENDID) VALUES (?, ?)";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.setInt(2, friendID);
prepStatement.executeUpdate();
/**
* GRAB THE INSERTED ROW FROM THE DB AND DISPLAY TO USER.
*
*/
// query to show that the row was inserted
query = "SELECT U.FNAME, U.LNAME, U.EMAIL, F.APPROVED, F.DATEAPPROVED\n"
+ "FROM FRIENDSHIPS F, USERS U\n"
+ "WHERE ((F.USERID = ? AND F.FRIENDID = ?)\n"
+ "OR (F.USERID = ? AND F.FRIENDID = ?))\n"
+ "AND F.USERID = U.ID";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.setInt(2, friendID);
prepStatement.setInt(3, userID);
prepStatement.setInt(4, friendID);
resultSet = prepStatement.executeQuery();
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [FNAME],[LNAME],[EMAIL],[APPROVED?],[DATEAPPROVED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (SQLException e) {
int errorCode = e.getErrorCode();
switch (errorCode) {
case 20001:
System.out.println("Friendship already pending");
break;
case 20002:
System.out.println("Friendship already established");
break;
default:
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
break;
}
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Lists all the groups in the database
*/
public void listAllGroups() {
try {
query = "SELECT NAME, DESCRIPTION, LIMIT, DATECREATED FROM GROUPS";
prepStatement = connection.prepareStatement(query);
resultSet = prepStatement.executeQuery();
System.out.println("\n[RECORD#] [NAME],[DESCRIPTION],[LIMIT],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter++ + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4));
}
} catch (SQLException ex) {
System.out.println(String.format("\n!! SQL Error: %s", ex.getMessage()));
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Lists all the users in the database
*/
public void listAllUsers() {
try {
query = "SELECT FNAME, LNAME, EMAIL, DOB, LASTLOGIN, DATECREATED FROM USERS";
prepStatement = connection.prepareStatement(query);
resultSet = prepStatement.executeQuery();
System.out.println("[RECORD#] [FNAME],[LNAME],[EMAIL],[DOB],[LASTLOGIN],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter++ + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5) + ", "
+ resultSet.getString(6));
}
} catch (SQLException ex) {
System.out.println(String.format("\n!! SQL Error: %s", ex.getMessage()));
} catch (Exception e) {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Logs in the user by updating their last login to the current timestamp.
*/
public void logInUser() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String userEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
userID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d}", userID));
//Insert statement for establishing pending friendship
query = "UPDATE USERS \n"
+ "SET LASTLOGIN = CURRENT_TIMESTAMP\n"
+ "WHERE ID = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
prepStatement.executeUpdate();
//just a query to show that the row was inserted
query = "select id, fname, lname, email, lastlogin\n"
+ "from users\n"
+ "where id = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, userID);
resultSet = prepStatement.executeQuery();
System.out.println("\nAfter successful update, data is...\n"
+ "[RECORD#] [ID],[FNAME],[LNAME],[EMAIL],[LASTLOGIN]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5));
counter++;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Searches firstname, lastname, and email as applicable search fields.
* breaks up search string by using regular regular expression on
* whitespace. runs queries for each of the search terms.
*/
public void searchForUser() {
try {
//initialize input variables for User and Friend info
int userID = 0;
String searchString = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get the search terms (uppercase with no leading/trailing spaces)
// and separate each term with comma (,)
do {
System.out.print("Please enter string you would like to search (break up terms with spaces): ");
searchString = keyIn.nextLine().trim().toUpperCase();
} while (searchString == null || searchString.equalsIgnoreCase(""));
String[] searchItems = searchString.split("\\s+");
System.out.println("searchItems length = " + searchItems.length);
//query that looks at firstname, lastname, and email as applicable search fields
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("SELECT ID, FNAME, LNAME, EMAIL FROM USERS WHERE ");
for (int x = 0; x < searchItems.length; x++) {
if (x == 0) {
queryBuilder.append("(");
} else {
queryBuilder.append("OR (");
}
queryBuilder.append("FNAME LIKE '%").append(searchItems[x]).append("%'");
queryBuilder.append(" OR LNAME LIKE '%").append(searchItems[x]).append("%'");
queryBuilder.append(" OR UPPER(EMAIL) LIKE '%").append(searchItems[x]).append("%'");
queryBuilder.append(") ");
}
prepStatement = connection.prepareStatement(queryBuilder.toString());
resultSet = prepStatement.executeQuery();
System.out.println("\nSearch results looking for matching Firstname, Lastname, OR Email...\n"
+ "[RECORD#] [ID],[FNAME],[LNAME],[EMAIL]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4));
counter++;
}
} catch (SQLException ex) {
System.out.println(String.format("\n!! SQL Error: %s", ex.getMessage()));
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Send a message to an entire group of users.
*/
public void sendMessageToGroup() {
try {
//initialize input variables for User and Friend info
int senderID = 0;
String userEmail = null;
int groupID = 0;
String groupName = null;
int recipID = 0;
String messageSubject = null;
String messageBody = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
senderID = resultSet.getInt(1);
}
// get the first name of the friend and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter recipient group name: ");
groupName = keyIn.nextLine().trim().toUpperCase();
} while (groupName == null || groupName.equalsIgnoreCase(""));
//make sure group exists
//query to make sure user exists and get their ID
query = "SELECT ID FROM GROUPS WHERE UPPER(NAME) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, groupName);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No Group Found");
} else {
groupID = resultSet.getInt(1);
}
// get the subject of the message
do {
System.out.print("Please enter your message subject: ");
messageSubject = keyIn.nextLine().trim();
} while (messageSubject == null || messageSubject.equalsIgnoreCase(""));
// get the body of the message
do {
System.out.print("Please enter your message body: ");
messageBody = keyIn.nextLine().trim();
} while (messageBody == null || messageBody.equalsIgnoreCase(""));
//query to get the users that are a part of the group
query = "SELECT USERID FROM GROUPMEMBERS WHERE GROUPID = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, groupID);
resultSet = prepStatement.executeQuery();
//Insert statement for establishing pending friendship
query = "INSERT INTO MESSAGES (SENDERID, SUBJECT, BODY, RECIPIENTID, GROUPID, DATECREATED) VALUES (?, ?, ?, ?, ?, current_timestamp)";
//Create the prepared statement
//I tried to do a batch update, but had conflicts with
//the trigger on the messages table when executing the batch of
//updates, because the trigger is a before insert, in order to
//determine the id for the message
//going to do a batch update so turn autocommit off
//connection.setAutoCommit(false);
prepStatement = connection.prepareStatement(query);
boolean groupHasMember = false;
while (resultSet.next()) {
prepStatement.setInt(1, senderID);
prepStatement.setString(2, messageSubject);
prepStatement.setString(3, messageBody);
prepStatement.setInt(4, resultSet.getInt(1));
prepStatement.setInt(5, groupID);
prepStatement.executeUpdate();
groupHasMember = true;
}
//execute the insert
if (groupHasMember) {
// prepStatement.executeQuery();
//prepStatement.executeBatch();
//connection.commit();
//connection.setAutoCommit(true);
} else {
System.out.println("The group you entered has no members");
return;
}
//just a query to show that the row was inserted
query = "SELECT M.ID, G.NAME, U.FNAME, U.LNAME, M.SUBJECT, M.BODY, RU.FNAME, RU.LNAME, M.DATECREATED FROM MESSAGES M "
+ "LEFT JOIN USERS U ON U.ID = M.SENDERID "
+ "LEFT JOIN USERS RU ON RU.ID = M.RECIPIENTID "
+ "LEFT JOIN GROUPS G ON G.ID = M.GROUPID "
+ "WHERE M.SENDERID=?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, senderID);
resultSet = prepStatement.executeQuery();
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [ID],[GROUP],[SENDERFNAME],[SENDERLNAME],[SUBJECT],[BODY],[RECFNAME],[RECLNAME],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5) + ", "
+ resultSet.getString(6) + ", "
+ resultSet.getString(7) + ", "
+ resultSet.getString(8) + ", "
+ resultSet.getString(9));
counter++;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else if (e.getMessage().equals("No Group Found")) {
System.out.println("The group name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Send a message to an individual user.
*/
public void sendMessageToUser() {
try {
//initialize input variables for User and Friend info
int senderID = 0;
String userEmail = null;
int recipID = 0;
String recipEmail = null;
String messageSubject = null;
String messageBody = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the sender's email address: ");
userEmail = keyIn.nextLine().trim().toLowerCase();
} while (userEmail == null || userEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", userEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, userEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
senderID = resultSet.getInt(1);
}
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the recipient's email address: ");
recipEmail = keyIn.nextLine().trim().toLowerCase();
} while (recipEmail == null || recipEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", recipEmail));
//query to make sure friend exists and get their ID
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, recipEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
recipID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of sender: {%d} ID of recipient: {%d}", senderID, recipID));
// get the subject of the message
do {
System.out.print("Please enter your message subject: ");
messageSubject = keyIn.nextLine().trim();
} while (messageSubject == null || messageSubject.equalsIgnoreCase(""));
// get the body of the message
do {
System.out.print("Please enter your message body: ");
messageBody = keyIn.nextLine().trim();
} while (messageBody == null || messageBody.equalsIgnoreCase(""));
//Insert statement for establishing pending friendship
query = "INSERT INTO MESSAGES (SENDERID, SUBJECT, BODY, RECIPIENTID, DATECREATED) VALUES (?, ?, ?, ?, current_timestamp)";
//Create the prepared statement
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, senderID);
prepStatement.setString(2, messageSubject);
prepStatement.setString(3, messageBody);
prepStatement.setInt(4, recipID);
prepStatement.executeUpdate();
//just a query to show that the row was inserted
query = "SELECT M.ID, U.FNAME, U.LNAME, M.SUBJECT, M.BODY, RU.FNAME, RU.LNAME, M.DATECREATED FROM MESSAGES M "
+ "LEFT JOIN USERS U ON U.ID=M.SENDERID "
+ "LEFT JOIN USERS RU ON RU.ID=M.RECIPIENTID "
+ "WHERE M.SENDERID=? AND M.RECIPIENTID=?";
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, senderID);
prepStatement.setInt(2, recipID);
resultSet = prepStatement.executeQuery();
System.out.println("\nAfter successful insert, data is...\n"
+ "[RECORD#] [ID],[SENDERFNAME],[SENDERLNAME],[SUBJECT],[BODY],[RECIPFNAME],[RECIPLNAME],[DATECREATED]");
int counter = 1;
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4) + ", "
+ resultSet.getString(5) + ", "
+ resultSet.getString(6) + ", "
+ resultSet.getString(7) + ", "
+ resultSet.getString(8));
counter++;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Given two users (userA and userB), find a path, if one exists, between
* the userA and the userB with at most 3 hop between them. A hop is defined
* as a friendship between any two users.
*/
public void threeDegrees() {
try {
//initialize input variables for User and Friend info
int startID = 0;
String startEmail = null;
int endID = 0;
String endEmail = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
startEmail = keyIn.nextLine().trim().toLowerCase();
} while (startEmail == null || startEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", startEmail));
//query to make sure user exists and get their ID
query = "SELECT ID FROM USERS WHERE LOWER(EMAIL) = ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, startEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
startID = resultSet.getInt(1);
}
// get a valid email and normalize (lowercase with no leading/trailing spaces)
do {
System.out.print("Please enter the user's email address: ");
endEmail = keyIn.nextLine().trim().toLowerCase();
} while (endEmail == null || endEmail.equalsIgnoreCase("") || !Pattern.matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$", endEmail));
//query to make sure friend exists and get their ID
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, endEmail);
resultSet = prepStatement.executeQuery();
//check if result set is empty and alert user, otherwise get the ID of the user
if (!resultSet.next()) {
throw new Exception("No User Found");
} else {
endID = resultSet.getInt(1);
}
// show user input (in form of ID's)
System.out.println(String.format("ID of user: {%d} ID of friend: {%d}", startID, endID));
//Select statement for establishing pending friendship
query = "SELECT FRIENDID FROM\n"
+ "FRIENDSHIPS \n"
+ "WHERE USERID = ?\n"
+ "AND APPROVED = 1\n"
+ "ORDER BY FRIENDID";
String countQuery = "SELECT COUNT(FRIENDID) FROM\n"
+ "FRIENDSHIPS \n"
+ "WHERE USERID = ?\n"
+ "AND APPROVED = 1\n"
+ "ORDER BY FRIENDID";
//get the number of rows returned
prepStatement = connection.prepareStatement(countQuery);
prepStatement.setInt(1, startID);
resultSet = prepStatement.executeQuery();
int numRows = 0;
while (resultSet.next()) {
numRows = resultSet.getInt(1);
}
//Create the prepared statement
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, startID);
resultSet = prepStatement.executeQuery();
LinkedList connections = new LinkedList();
LinkedList currentPath = new LinkedList();
Hashtable<Integer, LinkedList> currentFriendships = new Hashtable<Integer, LinkedList>();
currentPath.add(startID);
int curConnection = 0;
int degrees = 1;
int count = 0;
Integer currentID = new Integer(startID);
Integer lastID = null;
currentFriendships.put(startID, new LinkedList());
boolean success = false;
while (true) {
if (degrees <= 3) {
if (resultSet.next()) {
if (resultSet.getInt(1) == endID) {
currentPath.add(resultSet.getInt(1));
success = true;
break;
//completely found
}
if (!currentPath.contains(resultSet.getInt(1))) {
LinkedList l = currentFriendships.get(currentID);
l.add(resultSet.getInt(1));
currentFriendships.put(currentID, l);
}
count++;
}
}
//if you are on the last row, remove the last user that did not
//work, grab a new userID and get all of their friends
if (count == numRows || (degrees > 3 && !currentFriendships.isEmpty())) {
LinkedList l = currentFriendships.get(currentID);
int nextSearch = 0;
if (!l.isEmpty()) {
nextSearch = (Integer) l.removeFirst();
} else if (lastID != null) {
degrees
currentPath.remove(currentID);
currentFriendships.remove(currentID);
currentID = lastID;
l = currentFriendships.get(currentID);
if (l.isEmpty()) {
currentFriendships.remove(currentID);
currentPath.remove(currentID);
degrees
currentID = (Integer) currentPath.getLast();
l = currentFriendships.get(currentID);
if (l.isEmpty()) {
currentFriendships.remove(currentID);
currentPath.remove(currentID);
degrees
currentID = (Integer) currentPath.getLast();
l = currentFriendships.get(currentID);
if (l.isEmpty()){
success = false;
break;
} else {
nextSearch = (Integer) l.removeFirst();
}
} else {
nextSearch = (Integer) l.removeFirst();
}
} else {
nextSearch = (Integer) l.removeFirst();
}
} else {
success = false;
break;
}
//get the number of rows for this user
prepStatement = connection.prepareStatement(countQuery);
prepStatement.setInt(1, nextSearch);
resultSet = prepStatement.executeQuery();
while (resultSet.next()) {
numRows = resultSet.getInt(1);
}
count = 0;
//get the list of friendIDs for the next user
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, nextSearch);
resultSet = prepStatement.executeQuery();
currentPath.add(nextSearch);
lastID = currentID;
currentID = new Integer(nextSearch);
currentFriendships.put(currentID, new LinkedList());
degrees++;
} else if (count == numRows && currentFriendships.isEmpty()) {
success = false;
break;
//no dice
}
if (degrees > 3 && currentFriendships.isEmpty()) {
success = false;
break;
//too many degrees
}
}
if (success) {
query = "select FNAME, LNAME from users WHERE ID = ?";
System.out.println("\nPath for three degrees is ... ");
for (int i = 0; i < currentPath.size(); i++) {
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, (Integer) currentPath.get(i));
resultSet = prepStatement.executeQuery();
while(resultSet.next()){
System.out.print(resultSet.getString(1) + " "
+ resultSet.getString(2) + " -> ");
}
}
} else {
System.out.println("No successful 3 degree matching could be made");
}
} catch (SQLException e) {
int errorCode = e.getErrorCode();
switch (errorCode) {
case 20001:
System.out.println("\nFriendship already pending");
break;
case 20002:
System.out.println("\nFriendship already established");
break;
default:
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
break;
}
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("The user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(String.format("!! Cannot close object. Error: %s", e.getMessage()));
}
}
}
/**
* Display the top K who have sent or received the highest number of
* messages during for the past X months. X and K should be input parameters
* to this function.
*
* The current query treats all messages equally (aka no special
* consideration for group messages), so if a user sends 1 message to a
* group of 10 people, that would count as them sending 10 messages.
*/
public void topMessagers() {
try {
//initialize input variables for User and Friend info
int numMonths = 0;
int numResults = 0;
String numberOfMonths = null;
String numberOfResults = null;
// create a scanner to get user input
Scanner keyIn = new Scanner(System.in);
// get the amount of months
do {
System.out.print("Please enter the number of months: ");
numberOfMonths = keyIn.nextLine().trim();
} while (numberOfMonths == null || numberOfMonths.equalsIgnoreCase("") || !Pattern.matches("\\d+", numberOfMonths));
numMonths = Integer.parseInt(numberOfMonths);
//get the lastName of User and normalize (uppercase with no leading/trailing spaces)
do {
System.out.print("Please enter the number of results you would like to see: ");
numberOfResults = keyIn.nextLine().trim().toUpperCase();
} while (numberOfResults == null || numberOfResults.equalsIgnoreCase("") || !Pattern.matches("\\d+", numberOfResults));
numResults = Integer.parseInt(numberOfResults);
//query to make sure user exists and get their ID
query = "SELECT M.MESSAGE_COUNT, U.FNAME, U.LNAME, U.EMAIL FROM\n"
+ "(SELECT S.USERID AS USER_ID, S.TOTAL_SENT + R.TOTAL_RECEIVED AS MESSAGE_COUNT \n"
+ "FROM \n"
+ "(\n"
+ "SELECT SENDERID AS USERID, COUNT(*) AS TOTAL_SENT\n"
+ "FROM MESSAGES \n"
+ "WHERE DATECREATED > CURRENT_TIMESTAMP - NUMTOYMINTERVAL(?, 'MONTH')\n"
+ "GROUP BY SENDERID\n"
+ "ORDER BY SENDERID\n"
+ ") S, \n"
+ "(\n"
+ "SELECT RECIPIENTID AS USERID, COUNT(*) AS TOTAL_RECEIVED\n"
+ "FROM MESSAGES \n"
+ "WHERE DATECREATED > CURRENT_TIMESTAMP - NUMTOYMINTERVAL(?, 'MONTH')\n"
+ "GROUP BY RECIPIENTID\n"
+ "ORDER BY RECIPIENTID\n"
+ ") R\n"
+ "WHERE S.USERID = R.USERID\n"
+ "ORDER BY MESSAGE_COUNT DESC) M, USERS U\n"
+ "WHERE M.USER_ID = U.ID AND ROWNUM <= ?";
prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, numberOfMonths);
prepStatement.setString(2, numberOfMonths);
prepStatement.setInt(3, numResults);
resultSet = prepStatement.executeQuery();
System.out.println("\nQuery success, data is...\n"
+ "[RECORD#] [MSG_COUNT],[FNAME],[LNAME],[EMAIL]");
int counter = 1;
System.out.println("[FNAME],[LNAME],[NUM MESSAGES]");
while (resultSet.next()) {
System.out.println("Record " + counter + ": "
+ resultSet.getString(1) + ", "
+ resultSet.getString(2) + ", "
+ resultSet.getString(3) + ", "
+ resultSet.getString(4));
counter++;
}
} catch (SQLException e) {
System.out.println(String.format("\n!! SQL Error: %s", e.getMessage()));
} catch (Exception e) {
if (e.getMessage().equals("No User Found")) {
System.out.println("\nThe user name you entered does not exist");
} else {
System.out.println(String.format("\n!! Error: %s", e.getMessage()));
}
} finally {
try {
if (statement != null) {
statement.close();
}
if (prepStatement != null) {
prepStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println("\nCannot close object. Machine error: " + e.getMessage());
}
}
}
}
// * GET THE EMAIL OF USER THAT IS TO BE FRIENDED |
package uk.ac.ebi.quickgo.annotation.controller;
import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.WITH_FROM;
import static uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class})
@WebAppConfiguration
public class AnnotationControllerIT {
// temporary data store for solr's data, which is automatically cleaned on exit
@ClassRule
public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore();
private static final int NUMBER_OF_GENERIC_DOCS = 3;
private static final String ASSIGNED_BY_PARAM = "assignedBy";
private static final String GO_EVIDENCE_PARAM = "goEvidence";
private static final String REF_PARAM = "reference";
private static final String QUALIFIER_PARAM = "qualifier";
private static final String ECO_ID = "ecoId";
private static final String PAGE_PARAM = "page";
private static final String LIMIT_PARAM = "limit";
private static final String TAXON_ID_PARAM = "taxon";
private static final String WITHFROM_PARAM= "withFrom";
private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ";
private static final String RESOURCE_URL = "/QuickGO/services/annotation";
//Test data
private static final String EXISTING_ECO_ID1 = "ECO:0000256";
private static final String EXISTING_ECO_ID2 = "ECO:0000323"; //exists
private static final String NOTEXISTS_ECO_ID3 = "ECO:0000888"; //doesn't exist
public static final int NUM_RESULTS = 6;
private MockMvc mockMvc;
private List<AnnotationDocument> genericDocs;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private AnnotationRepository repository;
@Before
public void setup() {
repository.deleteAll();
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS);
repository.save(genericDocs);
genericDocs = createGenericDocs2(NUMBER_OF_GENERIC_DOCS);
repository.save(genericDocs);
}
private List<AnnotationDocument> createGenericDocs(int n) {
return IntStream.range(0, n)
.mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect
(Collectors.toList());
}
private List<AnnotationDocument> createGenericDocs2(int n) {
return IntStream.range(0, n)
.mapToObj(i -> AnnotationDocMocker.createAnnotationDocUniqueData(createId(i))).collect
(Collectors.toList());
}
private String createId(int idNum) {
return String.format("A0A%03d", idNum);
}
//ASSIGNED BY
@Test
public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception {
String geneProductId = "P99999";
String assignedBy = "ASPGD";
AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId);
doc.assignedBy = assignedBy;
return doc;
}
@Test
public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception {
String geneProductId1 = "P99999";
String assignedBy1 = "ASPGD";
AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1);
repository.save(document1);
String geneProductId2 = "P99998";
String assignedBy2 = "BHF-UCL";
AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy1 + "," + assignedBy2));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2));
}
@Test
public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception {
String geneProductId1 = "P99999";
String assignedBy1 = "ASPGD";
AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1);
repository.save(document1);
String geneProductId2 = "P99998";
String assignedBy2 = "BHF-UCL";
AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(ASSIGNED_BY_PARAM, assignedBy1)
.param(ASSIGNED_BY_PARAM, assignedBy2));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2));
}
@Test
public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception {
String geneProductId = "P99999";
String assignedBy = "ASPGD";
AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + ","
+ assignedBy));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
@Test
public void invalidAssignedByThrowsAnError() throws Exception {
String invalidAssignedBy = "_ASPGD";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, invalidAssignedBy));
response.andDo(print())
.andExpect(status().isBadRequest());
}
//TAXON ID
@Test
public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception {
String geneProductId = "P99999";
int taxonId = 2;
AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "2"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId);
doc.taxonId = taxonId;
return doc;
}
@Test
public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception {
String geneProductId1 = "P99999";
int taxonId1 = 2;
AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1);
repository.save(document1);
String geneProductId2 = "P99998";
int taxonId2 = 3;
AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(TAXON_ID_PARAM, String.valueOf(taxonId1))
.param(TAXON_ID_PARAM, String.valueOf(taxonId2)));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2));
}
@Test
public void invalidTaxIdThrowsError() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "-2"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void lookupAnnotationFilterByGoEvidenceCodeSuccessfully() throws Exception {
String goEvidenceCode = "IEA";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size()))
.andExpect(fieldsInAllResultsExist(genericDocs.size()))
.andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode));
}
@Test
public void lookupAnnotationFilterByLowercaseGoEvidenceCodeSuccessfully() throws Exception {
String goEvidenceCode = "iea";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size()))
.andExpect(fieldsInAllResultsExist(genericDocs.size()))
.andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode.toUpperCase()));
}
@Test public void lookupAnnotationFilterByNonExistentGoEvidenceCodeReturnsNothing() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "ZZZ"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterAnnotationsUsingMultipleGoEvidenceCodesSuccessfully() throws Exception {
String goEvidenceCode = "IEA";
String goEvidenceCode1 = "BSS";
AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createId(999));
annoDoc1.goEvidence = goEvidenceCode1;
repository.save(annoDoc1);
String goEvidenceCode2 = "AWE";
AnnotationDocument annoDoc2 = AnnotationDocMocker.createAnnotationDoc(createId(998));
annoDoc2.goEvidence = goEvidenceCode2;
repository.save(annoDoc2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "IEA,BSS,AWE,PEG"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size() + 2))
.andExpect(fieldsInAllResultsExist(genericDocs.size() + 2))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode1, 1))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode2, 1))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode, genericDocs.size()));
}
@Test
public void invalidGoEvidenceThrowsException() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "BlahBlah"));
response.andExpect(status().isBadRequest())
.andExpect(contentTypeToBeJson());
}
//todo test valid values for qualifier once a custom validator has been created
@Test
public void successfullyLookupAnnotationsByQualifier() throws Exception {
String qualifier = "enables";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM, qualifier));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccurInField(QUALIFIER, qualifier));
}
@Test
public void failToFindAnnotationsWhenQualifierDoesntExist() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM, "peeled"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterAnnotationsUsingSingleEcoIdReturnsResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ECO_ID, EXISTING_ECO_ID1));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size()))
.andExpect(fieldsInAllResultsExist(genericDocs.size()))
.andExpect(atLeastOneResultHasItem(ECO_ID, EXISTING_ECO_ID1));
}
@Test
public void filterAnnotationsUsingMultipleEcoIdsInSingleParameterProducesMixedResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ECO_ID, EXISTING_ECO_ID1 + "," + EXISTING_ECO_ID2));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size() * 2))
.andExpect(fieldsInAllResultsExist(genericDocs.size() * 2))
.andExpect(itemExistsExpectedTimes(ECO_ID, EXISTING_ECO_ID1, 3))
.andExpect(itemExistsExpectedTimes(ECO_ID, EXISTING_ECO_ID2, 3))
.andExpect(itemExistsExpectedTimes(ECO_ID, NOTEXISTS_ECO_ID3, 0));
}
@Test
public void filterAnnotationsUsingMultipleEcoIdsAsIndependentParametersProducesMixedResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ECO_ID, EXISTING_ECO_ID1)
.param(ECO_ID, EXISTING_ECO_ID2));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size() * 2))
.andExpect(fieldsInAllResultsExist(genericDocs.size() * 2))
.andExpect(itemExistsExpectedTimes(ECO_ID, EXISTING_ECO_ID1, 3))
.andExpect(itemExistsExpectedTimes(ECO_ID, EXISTING_ECO_ID2, 3))
.andExpect(itemExistsExpectedTimes(ECO_ID, NOTEXISTS_ECO_ID3, 0));
}
@Test
public void filterByNonExistentEcoIdReturnsZeroResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ECO_ID, NOTEXISTS_ECO_ID3));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void retrievesSecondPageOfAllEntriesRequest() throws Exception {
int totalEntries = 60;
repository.deleteAll();
repository.save(createGenericDocs(totalEntries));
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(PAGE_PARAM, "2"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(totalEntries))
.andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE))
.andExpect(
pageInfoMatches(
2,
totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE),
DEFAULT_ENTRIES_PER_PAGE)
);
}
private int totalPages(int totalEntries, int resultsPerPage) {
return (int) Math.ceil(totalEntries / resultsPerPage) + 1;
}
@Test
public void pageRequestEqualToAvailablePagesReturns200() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(PAGE_PARAM, "1"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(genericDocs.size() * 2))
.andExpect(
pageInfoMatches(
1,
totalPages(genericDocs.size() * 2, DEFAULT_ENTRIES_PER_PAGE),
DEFAULT_ENTRIES_PER_PAGE)
);
}
@Test
public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(PAGE_PARAM, "0"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void pageRequestHigherThanAvailablePagesReturns400() throws Exception {
repository.deleteAll();
int existingPages = 4;
createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(PAGE_PARAM, String.valueOf(existingPages + 1)));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void successfulLookupWithFromForSingleId()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "InterPro:IPR015421"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUM_RESULTS))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015421"));
}
@Test
public void successfulLookupWithFromForMultipleValues()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM,
"InterPro:IPR015421,InterPro:IPR015422"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUM_RESULTS))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015421"))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015422"));
}
@Test
public void searchingForUnknownWithFromBringsBackNoResults()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "XXX:54321"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void successfulLookupWithFromUsingDatabaseNameOnly()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "InterPro"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUM_RESULTS))
.andExpect(fieldsInAllResultsExist(NUM_RESULTS))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015421"))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015422"));
}
@Test
public void successfulLookupWithFromUsingDatabaseIdOnly()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "IPR015421"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUM_RESULTS))
.andExpect(fieldsInAllResultsExist(genericDocs.size()))
.andExpect(valueOccursInCollection(WITH_FROM,"InterPro:IPR015421"));
}
@Test
public void limitForPageExceedsMaximumAllowed() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(LIMIT_PARAM, "101"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void limitForPageWithinMaximumAllowed() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(LIMIT_PARAM, "100"));
response.andExpect(status().isOk())
.andExpect(totalNumOfResults(NUM_RESULTS))
.andExpect(pageInfoMatches(1, 1, 100));
}
@Test
public void limitForPageThrowsErrorWhenNegative() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search")
.param(LIMIT_PARAM, "-20"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
} |
package fi.metropolia.yellow_spaceship.androidadvproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import fi.metropolia.yellow_spaceship.androidadvproject.api.ApiClient;
import fi.metropolia.yellow_spaceship.androidadvproject.menu.ListRowData;
import fi.metropolia.yellow_spaceship.androidadvproject.menu.SoundLibraryListAdapter;
import fi.metropolia.yellow_spaceship.androidadvproject.models.DAMSound;
import fi.metropolia.yellow_spaceship.androidadvproject.models.SoundCategory;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class SoundLibraryChildFragment extends Fragment {
private SoundCategory category;
private RecyclerView.LayoutManager layoutManager;
ArrayList<ListRowData> data;
private SoundLibraryListAdapter adapter;
private RecyclerView recyclerView;
public static SoundLibraryChildFragment newInstance() {
SoundLibraryChildFragment fragment = new SoundLibraryChildFragment();
return fragment;
}
public SoundLibraryChildFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(null);
this.category = SoundCategory.fromApi(getArguments().getString("category"));
// Data for RecycleView
data = new ArrayList<ListRowData>();
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.sound_library_child_fragment, container, false);
// Adapter for RecyclerView
adapter = new SoundLibraryListAdapter(getActivity(), null, data);
recyclerView = (RecyclerView)fragmentView.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
loadData();
return fragmentView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set onClickListener for back button
((Toolbar)getActivity().findViewById(R.id.toolbar)).setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
}
private void loadData() {
ApiClient.getDAMApiClient().getCategory("M4B-lnwO3clT-MGJmnMM1NGOpJF4q4YNxaBoQzLTjMx9dit4w1QoUZxO3LuVJeQWO03fxaNfdX38tMN1oJ_2ViQq7h_2e1hKcv_h_jAhYXPJJnMayzS-Ih6FcgwvBVaB",
this.category,
true,
new Callback<List<List<DAMSound>>>() {
@Override
public void success(List<List<DAMSound>> lists, Response response) {
data.clear();
for (List<DAMSound> d : lists) {
data.add(new ListRowData(d.get(0).getTitle(), null, null));
}
recyclerView.getAdapter().notifyDataSetChanged();
}
@Override
public void failure(RetrofitError error) {
error.printStackTrace();
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Downloading sounds failed, please try again", Toast.LENGTH_SHORT);
toast.show();
}
});
}
} |
package fr.paris10.projet.assogenda.assogenda.ui.activites;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.storage.images.FirebaseImageLoader;
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 com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import fr.paris10.projet.assogenda.assogenda.R;
import fr.paris10.projet.assogenda.assogenda.model.Association;
import fr.paris10.projet.assogenda.assogenda.model.User;
public class ShowAssociationActivity extends AppCompatActivity {
private String associationID;
private Association association;
private TextView nameAsso;
private TextView descAsso;
private Button createEvent;
private ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_association);
logo = (ImageView) findViewById(R.id.activity_show_association_logo_asso);
nameAsso = (TextView) findViewById(R.id.activity_show_association_name_asso);
descAsso = (TextView) findViewById(R.id.activity_show_association_description_asso);
createEvent = (Button) findViewById(R.id.activity_show_association_create_event);
associationID = (String) getIntent().getExtras().get("associationID");
nameAsso.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), association.name, Toast.LENGTH_SHORT).show();
}
});
descAsso.setMovementMethod(new ScrollingMovementMethod());
FirebaseDatabase.getInstance()
.getReference("association")
.child(associationID)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
association = dataSnapshot.getValue(Association.class);
nameAsso.setText(association.name);
descAsso.setText(association.description);
if (association.logo != null) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference imagePath = storageReference.child(association.logo);
Glide.with(getApplicationContext())
.using(new FirebaseImageLoader())
.load(imagePath)
.into(logo);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("onCancelled", databaseError.getMessage());
}
});
createEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CreateEventActivity.class);
intent.putExtra("assoID", associationID);
startActivity(intent);
}
});
}
} |
package org.ovirt.engine.core.bll.validator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.scheduling.SchedulingManager;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.validator.storage.DiskImagesValidator;
import org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator;
import org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageFileType;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.osinfo.OsRepository;
import org.ovirt.engine.core.common.queries.GetImagesListParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.utils.SimpleDependecyInjector;
import org.ovirt.engine.core.common.utils.customprop.VmPropertiesUtils;
import org.ovirt.engine.core.common.vdscommands.IsVmDuringInitiatingVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.StorageDomainDao;
import org.ovirt.engine.core.dao.VdsDynamicDao;
import org.ovirt.engine.core.dao.network.NetworkDao;
import org.ovirt.engine.core.dao.network.VmNicDao;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.utils.NetworkUtils;
public class RunVmValidator {
private VM vm;
private RunVmParams runVmParam;
private boolean isInternalExecution;
private Guid activeIsoDomainId;
private OsRepository osRepository;
private List<Disk> cachedVmDisks;
private List<DiskImage> cachedVmImageDisks;
private Set<String> cachedInterfaceNetworkNames;
private List<Network> cachedClusterNetworks;
private Set<String> cachedClusterNetworksNames;
public RunVmValidator(VM vm, RunVmParams rumVmParam, boolean isInternalExecution, Guid activeIsoDomainId) {
this.vm = vm;
this.runVmParam = rumVmParam;
this.isInternalExecution = isInternalExecution;
this.activeIsoDomainId = activeIsoDomainId;
this.osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class);
}
/**
* Used for testings
*/
protected RunVmValidator() {
}
/**
* A general method for run vm validations. used in runVmCommand and in VmPoolCommandBase
*
* @param messages
* @param storagePool
* @param vdsBlackList
* - hosts that we already tried to run on
* @param vdsWhiteList
* - initial host list, mainly runOnSpecificHost (runOnce/migrateToHost)
* @param destVdsList
* @param vdsGroup
* @return
*/
public boolean canRunVm(List<String> messages, StoragePool storagePool, List<Guid> vdsBlackList,
List<Guid> vdsWhiteList, List<Guid> destVdsList, VDSGroup vdsGroup) {
if (vm.getStatus() == VMStatus.Paused) {
// if the VM is paused, we should only check the VDS status
// as the rest of the checks were already checked before
return validate(validateVdsStatus(vm), messages);
} else if (vm.getStatus() == VMStatus.Suspended) {
return validate(new VmValidator(vm).vmNotLocked(), messages) &&
validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) &&
validate(validateVmStatusUsingMatrix(vm), messages) &&
validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) &&
validate(vmDuringInitialization(vm), messages) &&
validate(validateStorageDomains(vm, isInternalExecution, getVmImageDisks()), messages) &&
validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) &&
getSchedulingManager().canSchedule(
vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages);
}
return
validateVmProperties(vm, runVmParam.getCustomProperties(), messages) &&
validate(validateBootSequence(vm, runVmParam.getBootSequence(), getVmDisks(), activeIsoDomainId), messages) &&
validate(validateDisplayType(), messages) &&
validate(new VmValidator(vm).vmNotLocked(), messages) &&
validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) &&
validate(validateVmStatusUsingMatrix(vm), messages) &&
validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) &&
validate(validateIsoPath(vm, runVmParam.getDiskPath(), runVmParam.getFloppyPath(), activeIsoDomainId), messages) &&
validate(vmDuringInitialization(vm), messages) &&
validate(validateStatelessVm(vm, runVmParam.getRunAsStateless()), messages) &&
validate(validateFloppy(), messages) &&
validate(validateStorageDomains(vm,
isInternalExecution,
filterReadOnlyAndPreallocatedDisks(getVmImageDisks())), messages)
&&
validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) &&
validate(validateMemorySize(vm), messages) &&
getSchedulingManager().canSchedule(
vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages);
}
private List<DiskImage> filterReadOnlyAndPreallocatedDisks(List<DiskImage> vmImageDisks) {
List<DiskImage> retVal = new ArrayList<>();
for (DiskImage disk : vmImageDisks) {
if (!(disk.getVolumeType() == VolumeType.Preallocated || disk.getReadOnly())) {
retVal.add(disk);
}
}
return retVal;
}
private SchedulingManager getSchedulingManager() {
return Injector.get(SchedulingManager.class);
}
protected ValidationResult validateMemorySize(VM vm) {
int maxSize;
if (getOsRepository().get64bitOss().contains(vm.getOs())) {
maxSize = Config.getValue(ConfigValues.VM64BitMaxMemorySizeInMB,
vm.getVdsGroupCompatibilityVersion().getValue());
} else {
maxSize = Config.getValue(ConfigValues.VM32BitMaxMemorySizeInMB);
}
if (vm.getMemSizeMb() > maxSize) {
return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_MEMORY_EXCEEDS_SUPPORTED_LIMIT);
}
return ValidationResult.VALID;
}
public ValidationResult validateFloppy() {
if (StringUtils.isNotEmpty(runVmParam.getFloppyPath()) && !VmValidationUtils.isFloppySupported(vm.getOs(),
vm.getVdsGroupCompatibilityVersion())) {
return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_FLOPPY_IS_NOT_SUPPORTED_BY_OS);
}
return ValidationResult.VALID;
}
/**
* @return true if all VM network interfaces are valid
*/
public ValidationResult validateNetworkInterfaces() {
ValidationResult validationResult = validateInterfacesConfigured(vm);
if (!validationResult.isValid()) {
return validationResult;
}
validationResult = validateInterfacesAttachedToClusterNetworks(vm, getClusterNetworksNames(), getInterfaceNetworkNames());
if (!validationResult.isValid()) {
return validationResult;
}
validationResult = validateInterfacesAttachedToVmNetworks(getClusterNetworks(), getInterfaceNetworkNames());
if (!validationResult.isValid()) {
return validationResult;
}
return ValidationResult.VALID;
}
protected ValidationResult validateDisplayType() {
if (!VmValidationUtils.isGraphicsAndDisplaySupported(vm.getOs(),
vm.getVdsGroupCompatibilityVersion(),
getVmActiveGraphics(),
vm.getDefaultDisplayType())) {
return new ValidationResult(
EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS);
}
return ValidationResult.VALID;
}
private Set<GraphicsType> getVmActiveGraphics() {
if (vm.getGraphicsInfos() != null && !vm.getGraphicsInfos().isEmpty()) { // graphics overriden in runonce
return vm.getGraphicsInfos().keySet();
} else {
List<VmDevice> graphicDevices =
DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.GRAPHICS);
Set<GraphicsType> graphicsTypes = new HashSet<>();
for (VmDevice graphicDevice : graphicDevices) {
GraphicsType type = GraphicsType.fromString(graphicDevice.getDevice());
graphicsTypes.add(type);
}
return graphicsTypes;
}
}
protected boolean validateVmProperties(VM vm, String runOnceCustomProperties, List<String> messages) {
String customProperties = runOnceCustomProperties != null ?
runOnceCustomProperties : vm.getCustomProperties();
return getVmPropertiesUtils().validateVmProperties(
vm.getVdsGroupCompatibilityVersion(),
customProperties,
messages);
}
protected ValidationResult validateBootSequence(VM vm, BootSequence runOnceBootSequence,
List<Disk> vmDisks, Guid activeIsoDomainId) {
BootSequence bootSequence = runOnceBootSequence != null ?
runOnceBootSequence : vm.getDefaultBootSequence();
// Block from running a VM with no HDD when its first boot device is
// HD and no other boot devices are configured
if (bootSequence == BootSequence.C && vmDisks.isEmpty()) {
return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_DISK_WITHOUT_DISK);
}
// If CD appears as first and there is no ISO in storage
// pool/ISO inactive - you cannot run this VM
if (bootSequence == BootSequence.CD && activeIsoDomainId == null) {
return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
}
// if there is network in the boot sequence, check that the
// vm has network, otherwise the vm cannot be run in vdsm
if (bootSequence == BootSequence.N
&& getVmNicDao().getAllForVm(vm.getId()).isEmpty()) {
return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_NETWORK_WITHOUT_NETWORK);
}
return ValidationResult.VALID;
}
/**
* Check storage domains. Storage domain status and disk space are checked only for non-HA VMs.
*
* @param vm
* The VM to run
* @param isInternalExecution
* Command is internal?
* @param vmImages
* The VM's image disks
* @return <code>true</code> if the VM can be run, <code>false</code> if not
*/
protected ValidationResult validateStorageDomains(VM vm, boolean isInternalExecution,
List<DiskImage> vmImages) {
if (vmImages.isEmpty()) {
return ValidationResult.VALID;
}
if (!vm.isAutoStartup() || !isInternalExecution) {
Set<Guid> storageDomainIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages);
MultipleStorageDomainsValidator storageDomainValidator =
new MultipleStorageDomainsValidator(vm.getStoragePoolId(), storageDomainIds);
ValidationResult result = storageDomainValidator.allDomainsExistAndActive();
if (!result.isValid()) {
return result;
}
result = !vm.isAutoStartup() ? storageDomainValidator.allDomainsWithinThresholds()
: ValidationResult.VALID;
if (!result.isValid()) {
return result;
}
}
return ValidationResult.VALID;
}
/**
* Check isValid only if VM is not HA VM
*/
protected ValidationResult validateImagesForRunVm(VM vm, List<DiskImage> vmDisks) {
if (vmDisks.isEmpty()) {
return ValidationResult.VALID;
}
return !vm.isAutoStartup() ?
new DiskImagesValidator(vmDisks).diskImagesNotLocked() : ValidationResult.VALID;
}
protected ValidationResult validateIsoPath(VM vm, String diskPath, String floppyPath, Guid activeIsoDomainId) {
if (vm.isAutoStartup()) {
return ValidationResult.VALID;
}
if (StringUtils.isEmpty(vm.getIsoPath()) && StringUtils.isEmpty(diskPath) && StringUtils.isEmpty(floppyPath)) {
return ValidationResult.VALID;
}
if (activeIsoDomainId == null) {
return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
}
if (!StringUtils.isEmpty(diskPath) && !isRepoImageExists(diskPath, activeIsoDomainId, ImageFileType.ISO)) {
return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_ISO_IMAGE_PATH);
}
if (!StringUtils.isEmpty(floppyPath) && !isRepoImageExists(floppyPath, activeIsoDomainId, ImageFileType.Floppy)) {
return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_FLOPPY_IMAGE_PATH);
}
return ValidationResult.VALID;
}
protected ValidationResult vmDuringInitialization(VM vm) {
if (vm.isRunning() || vm.getStatus() == VMStatus.NotResponding ||
isVmDuringInitiating(vm)) {
return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_IS_RUNNING);
}
return ValidationResult.VALID;
}
protected ValidationResult validateVdsStatus(VM vm) {
if (vm.getStatus() == VMStatus.Paused && vm.getRunOnVds() != null &&
getVdsDynamic(vm.getRunOnVds()).getStatus() != VDSStatus.Up) {
return new ValidationResult(
EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL,
EngineMessage.VAR__HOST_STATUS__UP.toString());
}
return ValidationResult.VALID;
}
protected ValidationResult validateStatelessVm(VM vm, Boolean stateless) {
// if the VM is not stateless, there is nothing to check
if (stateless != null ? !stateless : !vm.isStateless()) {
return ValidationResult.VALID;
}
ValidationResult previewValidation = getSnapshotValidator().vmNotInPreview(vm.getId());
if (!previewValidation.isValid()) {
return previewValidation;
}
// if the VM itself is stateless or run once as stateless
if (vm.isAutoStartup()) {
return new ValidationResult(EngineMessage.VM_CANNOT_RUN_STATELESS_HA);
}
ValidationResult hasSpaceValidation = hasSpaceForSnapshots();
if (!hasSpaceValidation.isValid()) {
return hasSpaceValidation;
}
return ValidationResult.VALID;
}
protected ValidationResult validateVmStatusUsingMatrix(VM vm) {
if (!VdcActionUtils.canExecute(Arrays.asList(vm), VM.class,
VdcActionType.RunVm)) {
return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(vm.getStatus()));
}
return ValidationResult.VALID;
}
/**
* check that we can create snapshots for all disks
* return true if all storage domains have enough space to create snapshots for this VM plugged disks
*/
protected ValidationResult hasSpaceForSnapshots() {
List<Disk> disks = DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId());
List<DiskImage> allDisks = ImagesHandler.filterImageDisks(disks, false, true, false);
Set<Guid> sdIds = ImagesHandler.getAllStorageIdsForImageIds(allDisks);
MultipleStorageDomainsValidator msdValidator = getStorageDomainsValidator(sdIds);
ValidationResult retVal = msdValidator.allDomainsWithinThresholds();
if (retVal == ValidationResult.VALID) {
return msdValidator.allDomainsHaveSpaceForNewDisks(allDisks);
}
return retVal;
}
protected MultipleStorageDomainsValidator getStorageDomainsValidator(Collection<Guid> sdIds) {
Guid spId = vm.getStoragePoolId();
return new MultipleStorageDomainsValidator(spId, sdIds);
}
protected ValidationResult validateStoragePoolUp(VM vm, StoragePool storagePool, List<DiskImage> vmImages) {
if (vmImages.isEmpty() || vm.isAutoStartup()) {
return ValidationResult.VALID;
}
return new StoragePoolValidator(storagePool).isUp();
}
/**
* Checking that the interfaces are all configured, interfaces with no network are allowed only if network linking
* is supported.
*
* @return true if all VM network interfaces are attached to existing cluster networks, or to no network (when
* network linking is supported).
*/
protected ValidationResult validateInterfacesConfigured(VM vm) {
for (VmNetworkInterface nic : vm.getInterfaces()) {
if (nic.getVnicProfileId() == null) {
return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ?
ValidationResult.VALID:
new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED);
}
}
return ValidationResult.VALID;
}
/**
* @param vm The VM to be run
* @param clusterNetworkNames cluster logical networks names
* @param interfaceNetworkNames VM interface network names
* @return true if all VM network interfaces are attached to existing cluster networks
*/
protected ValidationResult validateInterfacesAttachedToClusterNetworks(VM vm,
final Set<String> clusterNetworkNames, final Set<String> interfaceNetworkNames) {
Set<String> result = new HashSet<>(interfaceNetworkNames);
result.removeAll(clusterNetworkNames);
if (FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion())) {
result.remove(null);
}
// If after removing the cluster network names we still have objects, then we have interface on networks that
// aren't attached to the cluster
return result.isEmpty() ?
ValidationResult.VALID
: new ValidationResult(
EngineMessage.ACTION_TYPE_FAILED_NETWORK_NOT_IN_CLUSTER,
String.format("$networks %1$s", StringUtils.join(result, ",")));
}
/**
* @param clusterNetworks
* cluster logical networks
* @param interfaceNetworkNames
* VM interface network names
* @return true if all VM network interfaces are attached to VM networks
*/
protected ValidationResult validateInterfacesAttachedToVmNetworks(final List<Network> clusterNetworks,
Set<String> interfaceNetworkNames) {
List<String> nonVmNetworkNames =
NetworkUtils.filterNonVmNetworkNames(clusterNetworks, interfaceNetworkNames);
return nonVmNetworkNames.isEmpty() ?
ValidationResult.VALID
: new ValidationResult(
EngineMessage.ACTION_TYPE_FAILED_NOT_A_VM_NETWORK,
String.format("$networks %1$s", StringUtils.join(nonVmNetworkNames, ",")));
}
/// Utility methods ///
protected boolean validate(ValidationResult validationResult, List<String> message) {
if (!validationResult.isValid()) {
message.add(validationResult.getMessage().name());
for (String variableReplacement : validationResult.getVariableReplacements()) {
message.add(variableReplacement);
}
}
return validationResult.isValid();
}
protected NetworkDao getNetworkDao() {
return DbFacade.getInstance().getNetworkDao();
}
protected VdsDynamicDao getVdsDynamicDao() {
return DbFacade.getInstance().getVdsDynamicDao();
}
protected BackendInternal getBackend() {
return Backend.getInstance();
}
protected VmNicDao getVmNicDao() {
return DbFacade.getInstance().getVmNicDao();
}
protected StorageDomainDao getStorageDomainDao() {
return DbFacade.getInstance().getStorageDomainDao();
}
protected VmPropertiesUtils getVmPropertiesUtils() {
return VmPropertiesUtils.getInstance();
}
protected DiskDao getDiskDao() {
return DbFacade.getInstance().getDiskDao();
}
private boolean isRepoImageExists(String repoImagePath, Guid storageDomainId, ImageFileType imageFileType) {
VdcQueryReturnValue ret = getBackend().runInternalQuery(
VdcQueryType.GetImagesList,
new GetImagesListParameters(storageDomainId, imageFileType));
if (ret != null && ret.getReturnValue() != null && ret.getSucceeded()) {
for (RepoImage isoFileMetaData : ret.<List<RepoImage>>getReturnValue()) {
if (repoImagePath.equals(isoFileMetaData.getRepoImageId())) {
return true;
}
}
}
return false;
}
protected boolean isVmDuringInitiating(VM vm) {
return (Boolean) getBackend()
.getResourceManager()
.RunVdsCommand(VDSCommandType.IsVmDuringInitiating,
new IsVmDuringInitiatingVDSCommandParameters(vm.getId()))
.getReturnValue();
}
protected SnapshotsValidator getSnapshotValidator() {
return new SnapshotsValidator();
}
private VdsDynamic getVdsDynamic(Guid vdsId) {
return getVdsDynamicDao().get(vdsId);
}
private List<Disk> getVmDisks() {
if (cachedVmDisks == null) {
cachedVmDisks = getDiskDao().getAllForVm(vm.getId(), true);
}
return cachedVmDisks;
}
private List<DiskImage> getVmImageDisks() {
if (cachedVmImageDisks == null) {
cachedVmImageDisks = ImagesHandler.filterImageDisks(getVmDisks(), true, false, false);
cachedVmImageDisks.addAll(ImagesHandler.filterDisksBasedOnCinder(getVmDisks(), true));
}
return cachedVmImageDisks;
}
private Set<String> getInterfaceNetworkNames() {
if (cachedInterfaceNetworkNames == null) {
cachedInterfaceNetworkNames = Entities.vmInterfacesByNetworkName(vm.getInterfaces()).keySet();
}
return cachedInterfaceNetworkNames;
}
private List<Network> getClusterNetworks() {
if (cachedClusterNetworks == null) {
cachedClusterNetworks = getNetworkDao().getAllForCluster(vm.getVdsGroupId());
}
return cachedClusterNetworks;
}
private Set<String> getClusterNetworksNames() {
if (cachedClusterNetworksNames == null) {
cachedClusterNetworksNames = Entities.objectNames(getClusterNetworks());
}
return cachedClusterNetworksNames;
}
public OsRepository getOsRepository() {
return osRepository;
}
} |
package org.eclipse.smarthome.core.net;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Some utility functions related to network interfaces etc.
*
* @author Markus Rathgeb - Initial contribution and API
* @author Mark Herwege - Added methods to find broadcast address(es)
* @author Stefan Triller - Converted to OSGi service with primary ipv4 conf
*/
@Component(configurationPid = "org.eclipse.smarthome.network", property = { "service.pid=org.eclipse.smarthome.network",
"service.config.description.uri=system:network", "service.config.label=Network Settings",
"service.config.category=system" })
@NonNullByDefault
public class NetUtil implements NetworkAddressService {
private static final String PRIMARY_ADDRESS = "primaryAddress";
private static final String BROADCAST_ADDRESS = "broadcastAddress";
private static final Logger LOGGER = LoggerFactory.getLogger(NetUtil.class);
private static final Pattern IPV4_PATTERN = Pattern
.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
private @Nullable String primaryAddress;
private @Nullable String configuredBroadcastAddress;
@Activate
protected void activate(Map<String, Object> props) {
modified(props);
}
@Modified
public synchronized void modified(Map<String, Object> config) {
String primaryAddressConf = (String) config.get(PRIMARY_ADDRESS);
if (primaryAddressConf == null || primaryAddressConf.isEmpty() || !isValidIPConfig(primaryAddressConf)) {
// if none is specified we return the default one for backward compatibility
primaryAddress = getFirstLocalIPv4Address();
} else {
primaryAddress = primaryAddressConf;
}
String broadcastAddressConf = (String) config.get(BROADCAST_ADDRESS);
if (broadcastAddressConf == null || broadcastAddressConf.isEmpty() || !isValidIPConfig(broadcastAddressConf)) {
// if none is specified we return the one matching the primary ip
configuredBroadcastAddress = getPrimaryBroadcastAddress();
} else {
configuredBroadcastAddress = broadcastAddressConf;
}
}
@Override
public @Nullable String getPrimaryIpv4HostAddress() {
String primaryIP;
if (primaryAddress != null) {
String[] addrString = primaryAddress.split("/");
if (addrString.length > 1) {
String ip = getIPv4inSubnet(addrString[0], addrString[1]);
if (ip == null) {
// an error has occurred, using first interface like nothing has been configured
LOGGER.warn("Invalid address '{}', will use first interface instead.", primaryAddress);
primaryIP = getFirstLocalIPv4Address();
} else {
primaryIP = ip;
}
} else {
primaryIP = addrString[0];
}
} else {
// we do not seem to have any network interfaces
primaryIP = null;
}
return primaryIP;
}
/**
* @deprecated Please use the NetworkAddressService with {@link #getPrimaryIpv4HostAddress()}
*
* Get the first candidate for a local IPv4 host address (non loopback, non localhost).
*/
@Deprecated
public static @Nullable String getLocalIpv4HostAddress() {
try {
String hostAddress = null;
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
final NetworkInterface current = interfaces.nextElement();
if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
continue;
}
final Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()) {
final InetAddress currentAddr = addresses.nextElement();
if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
continue;
}
if (hostAddress != null) {
LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
} else {
hostAddress = currentAddr.getHostAddress();
}
}
}
return hostAddress;
} catch (SocketException ex) {
LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
return null;
}
}
private @Nullable String getFirstLocalIPv4Address() {
try {
String hostAddress = null;
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
final NetworkInterface current = interfaces.nextElement();
if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
continue;
}
final Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()) {
final InetAddress currentAddr = addresses.nextElement();
if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
continue;
}
if (hostAddress != null) {
LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
} else {
hostAddress = currentAddr.getHostAddress();
}
}
}
return hostAddress;
} catch (SocketException ex) {
LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
return null;
}
}
/**
* Get all broadcast addresses on the current host
*
* @return list of broadcast addresses, empty list if no broadcast addresses found
*/
public static List<String> getAllBroadcastAddresses() {
List<String> broadcastAddresses = new LinkedList<String>();
try {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
final NetworkInterface networkInterface = networkInterfaces.nextElement();
final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : interfaceAddresses) {
final InetAddress addr = interfaceAddress.getAddress();
if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
broadcastAddresses.add(interfaceAddress.getBroadcast().getHostAddress());
}
}
}
} catch (SocketException ex) {
LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
}
return broadcastAddresses;
}
@Override
public @Nullable String getConfiguredBroadcastAddress() {
String broadcastAddr;
if (configuredBroadcastAddress != null) {
broadcastAddr = configuredBroadcastAddress;
} else {
// we do not seem to have any network interfaces
broadcastAddr = null;
}
return broadcastAddr;
}
private @Nullable String getPrimaryBroadcastAddress() {
String primaryIp = getPrimaryIpv4HostAddress();
String broadcastAddress = null;
if (primaryIp != null) {
try {
Short prefix = getAllInterfaceAddresses().stream()
.filter(a -> a.getAddress().getHostAddress().equals(primaryIp)).map(a -> a.getPrefix())
.findFirst().get().shortValue();
broadcastAddress = getIpv4NetBroadcastAddress(primaryIp, prefix);
} catch (IllegalArgumentException ex) {
LOGGER.error("Invalid IP address parameter: {}", ex.getMessage(), ex);
}
}
if (broadcastAddress == null) {
// an error has occurred, using broadcast address of first interface instead
broadcastAddress = getFirstIpv4BroadcastAddress();
LOGGER.warn(
"Could not find broadcast address of primary IP, using broadcast address {} of first interface instead",
broadcastAddress);
}
return broadcastAddress;
}
/**
* @deprecated Please use the NetworkAddressService with {@link #getConfiguredBroadcastAddress()}
*
* Get the first candidate for a broadcast address
*
* @return broadcast address, null if no broadcast address is found
*/
@Deprecated
public static @Nullable String getBroadcastAddress() {
final List<String> broadcastAddresses = getAllBroadcastAddresses();
if (!broadcastAddresses.isEmpty()) {
return broadcastAddresses.get(0);
} else {
return null;
}
}
private static @Nullable String getFirstIpv4BroadcastAddress() {
final List<String> broadcastAddresses = getAllBroadcastAddresses();
if (!broadcastAddresses.isEmpty()) {
return broadcastAddresses.get(0);
} else {
return null;
}
}
/**
* Gets every IPv4+IPv6 Address on each Interface except the loopback interface.
* The Address format is in the CIDR notation which is ip/prefix-length e.g. 129.31.31.1/24.
*
* Example to get a list of only IPv4 addresses in string representation:
* List<String> l = getAllInterfaceAddresses().stream().filter(a->a.getAddress() instanceof
* Inet4Address).map(a->a.getAddress().getHostAddress()).collect(Collectors.toList());
*
* @return The collected IPv4 and IPv6 Addresses
*/
public static Collection<CidrAddress> getAllInterfaceAddresses() {
Collection<CidrAddress> interfaceIPs = new ArrayList<>();
Enumeration<NetworkInterface> en;
try {
en = NetworkInterface.getNetworkInterfaces();
} catch (SocketException ex) {
LOGGER.error("Could not find interface IP addresses: {}", ex.getMessage(), ex);
return interfaceIPs;
}
while (en.hasMoreElements()) {
NetworkInterface networkInterface = en.nextElement();
try {
if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue;
}
} catch (SocketException ignored) {
continue;
}
for (InterfaceAddress cidr : networkInterface.getInterfaceAddresses()) {
final InetAddress address = cidr.getAddress();
assert address != null; // NetworkInterface.getInterfaceAddresses() should return only non-null
// addresses
interfaceIPs.add(new CidrAddress(address, cidr.getNetworkPrefixLength()));
}
}
return interfaceIPs;
}
/**
* Converts a netmask in bits into a string representation
* i.e. 24 bits -> 255.255.255.0
*
* @param prefixLength bits of the netmask
* @return string representation of netmask (i.e. 255.255.255.0)
*/
public static String networkPrefixLengthToNetmask(int prefixLength) {
if (prefixLength > 32 || prefixLength < 1) {
throw new IllegalArgumentException("Network prefix length is not within bounds");
}
int ipv4Netmask = 0xFFFFFFFF;
ipv4Netmask <<= (32 - prefixLength);
byte[] octets = new byte[] { (byte) (ipv4Netmask >>> 24), (byte) (ipv4Netmask >>> 16),
(byte) (ipv4Netmask >>> 8), (byte) ipv4Netmask };
String result = "";
for (int i = 0; i < 4; i++) {
result += octets[i] & 0xff;
if (i < 3) {
result += ".";
}
}
return result;
}
public static String getIpv4NetAddress(String ipAddressString, short netMask) {
String errorString = "IP '" + ipAddressString + "' is not a valid IPv4 address";
if (!isValidIPConfig(ipAddressString)) {
throw new IllegalArgumentException(errorString);
}
if (netMask < 1 || netMask > 32) {
throw new IllegalArgumentException("Netmask '" + netMask + "' is out of bounds (1-32)");
}
String subnetMaskString = networkPrefixLengthToNetmask(netMask);
String[] netMaskOctets = subnetMaskString.split("\\.");
String[] ipv4AddressOctets = ipAddressString.split("\\.");
String netAddress = "";
try {
for (int i = 0; i < 4; i++) {
netAddress += Integer.parseInt(ipv4AddressOctets[i]) & Integer.parseInt(netMaskOctets[i]);
if (i < 3) {
netAddress += ".";
}
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(errorString);
}
return netAddress;
}
public static String getIpv4NetBroadcastAddress(String ipAddressString, short prefix) {
String errorString = "IP '" + ipAddressString + "' is not a valid IPv4 address";
if (!isValidIPConfig(ipAddressString)) {
throw new IllegalArgumentException(errorString);
}
if (prefix < 1 || prefix > 32) {
throw new IllegalArgumentException("Prefix '" + prefix + "' is out of bounds (1-32)");
}
try {
byte[] addr = InetAddress.getByName(ipAddressString).getAddress();
byte[] netmask = InetAddress.getByName(networkPrefixLengthToNetmask(prefix)).getAddress();
byte[] broadcast = new byte[] { (byte) (~netmask[0] | addr[0]), (byte) (~netmask[1] | addr[1]),
(byte) (~netmask[2] | addr[2]), (byte) (~netmask[3] | addr[3]) };
return InetAddress.getByAddress(broadcast).getHostAddress();
} catch (UnknownHostException ex) {
throw new IllegalArgumentException(errorString);
}
}
private @Nullable String getIPv4inSubnet(String ipAddress, String subnetMask) {
try {
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
final NetworkInterface current = interfaces.nextElement();
if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
continue;
}
for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) {
InetAddress addr = ifAddr.getAddress();
if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) {
continue;
}
String ipv4AddressOnInterface = addr.getHostAddress();
String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface,
ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());
String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/"
+ subnetMask;
// use first IP within this subnet
if (subnetStringOnInterface.equals(configuredSubnetString)) {
return ipv4AddressOnInterface;
}
}
}
} catch (SocketException ex) {
LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
}
return null;
}
/**
* Checks if the given String is a valid IPv4 Address
* or IPv4 address in CIDR notation
*
* @param ipAddress in format xxx.xxx.xxx.xxx or xxx.xxx.xxx.xxx/xx
* @return true if it is a valid address
*/
public static boolean isValidIPConfig(String ipAddress) {
if (ipAddress.contains("/")) {
String parts[] = ipAddress.split("/");
boolean ipMatches = IPV4_PATTERN.matcher(parts[0]).matches();
int netMask = Integer.parseInt(parts[1]);
boolean netMaskMatches = false;
if (netMask > 0 || netMask < 32) {
netMaskMatches = true;
}
if (ipMatches && netMaskMatches) {
return true;
}
} else {
return IPV4_PATTERN.matcher(ipAddress).matches();
}
return false;
}
} |
package org.openhab.core.library.items;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.types.State;
/**
* A ColorItem can be used for color values, e.g. for LED lights
*
* @author Kai Kreuzer
* @since 1.2.0
*
*/public class ColorItem extends DimmerItem {
static {
acceptedDataTypes.add(HSBType.class);
acceptedCommandTypes.add(HSBType.class);
}
public ColorItem(String name) {
super(name);
}
public void send(HSBType command) {
internalSend(command);
}
/**
* {@inheritDoc}
*/
@Override
public void setState(State state) {
State currentState = this.state;
if(currentState instanceof HSBType) {
DecimalType hue = ((HSBType) currentState).getHue();
PercentType saturation = ((HSBType) currentState).getSaturation();
// we map ON/OFF values to dark/bright, so that the hue and saturation values are not changed
if(state==OnOffType.OFF) {
this.state = new HSBType(hue, saturation, PercentType.ZERO);
} else if(state==OnOffType.ON) {
this.state = new HSBType(hue, saturation, PercentType.HUNDRED);
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(hue, saturation, (PercentType) state);
} else {
super.setState(state);
}
} else {
// we map ON/OFF values to black/white and percentage values to grey scale
if(state==OnOffType.OFF) {
this.state = HSBType.BLACK;
} else if(state==OnOffType.ON) {
this.state = HSBType.WHITE;
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(DecimalType.ZERO, PercentType.ZERO, (PercentType) state);
} else {
super.setState(state);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public State getStateAs(Class<? extends State> typeClass) {
if(typeClass==HSBType.class) {
return this.state;
} else {
return super.getStateAs(typeClass);
}
}
} |
package gov.nih.nci.cabig.caaers.api.impl;
import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.ParticipantDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.ReportStatus;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.domain.repository.ReportRepository;
import gov.nih.nci.cabig.caaers.domain.validation.ExpeditedAdverseEventReportValidator;
import gov.nih.nci.cabig.caaers.event.EventFactory;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdverseEventReport;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.BaseAdverseEventReport;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.BaseReportType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.BaseReports;
import gov.nih.nci.cabig.caaers.integration.schema.aereportid.ReportIdCriteria;
import gov.nih.nci.cabig.caaers.integration.schema.aereportid.SafetyReportIdentifer;
import gov.nih.nci.cabig.caaers.integration.schema.common.CaaersServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.common.ResponseDataType;
import gov.nih.nci.cabig.caaers.service.AdeersIntegrationFacade;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.ReportSubmissionService;
import gov.nih.nci.cabig.caaers.service.migrator.BaseExpeditedAdverseEventReportConverter;
import gov.nih.nci.cabig.caaers.service.migrator.ExpeditedAdverseEventReportConverter;
import gov.nih.nci.cabig.caaers.service.migrator.report.ExpeditedReportMigrator;
import gov.nih.nci.cabig.caaers.service.synchronizer.report.ExpeditedAdverseEventReportSynchronizer;
import gov.nih.nci.cabig.caaers.utils.DateUtils;
import gov.nih.nci.cabig.caaers.validation.ValidationError;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.transaction.annotation.Transactional;
public class SafetyReportServiceImpl {
private static Log logger = LogFactory.getLog(SafetyReportServiceImpl.class);
/** Base Expedited Report Converter. **/
private BaseExpeditedAdverseEventReportConverter baseEaeConverter;
/** Expedited Report Converter. **/
private ExpeditedAdverseEventReportConverter eaeConverter;
private ParticipantServiceImpl participantService;
private ParticipantDao participantDao;
private StudyDao studyDao;
private MessageSource messageSource;
private ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao;
private StudyParticipantAssignmentDao studyParticipantAssignmentDao;
/** Validator Service. **/
private ExpeditedAdverseEventReportValidator aeReportValidator;
/** Expedited Report Migrator. **/
private ExpeditedReportMigrator aeReportMigrator;
private ExpeditedAdverseEventReportSynchronizer aeReportSynchronizer;
/** The report Repository. */
private ReportRepository reportRepository;
private ReportSubmissionService reportSubmissionService;
private IDServiceImpl idServiceImpl;
private AdeersIntegrationFacade adeersIntegrationFacade;
private EventFactory eventFactory;
public EventFactory getEventFactory() {
return eventFactory;
}
public void setEventFactory(EventFactory eventFactory) {
this.eventFactory = eventFactory;
}
public AdeersIntegrationFacade getAdeersIntegrationFacade() {
return adeersIntegrationFacade;
}
public void setAdeersIntegrationFacade(AdeersIntegrationFacade adeersIntegrationFacade) {
this.adeersIntegrationFacade = adeersIntegrationFacade;
}
public ReportRepository getReportRepository() {
return reportRepository;
}
public void setReportRepository(ReportRepository reportRepository) {
this.reportRepository = reportRepository;
}
public void setReportSubmissionService(ReportSubmissionService reportSubmissionService) {
this.reportSubmissionService = reportSubmissionService;
}
public IDServiceImpl getIdServiceImpl() {
return idServiceImpl;
}
public void setIdServiceImpl(IDServiceImpl idServiceImpl) {
this.idServiceImpl = idServiceImpl;
}
/**
* Does the validation of the input message
* @param aeSrcReport
* @return
*/
@SuppressWarnings("unused")
private ValidationErrors validateInput(ExpeditedAdverseEventReport aeSrcReport){
AdverseEventReportingPeriod rpSrc = aeSrcReport.getReportingPeriod();
ValidationErrors errors = new ValidationErrors();
//do I have reporting period ?
if(rpSrc == null){
errors.addValidationError( "ER-RP-1", "Missing Reporting period and Adverse event in input message");
return errors;
}
//do I have AEs ?
if(rpSrc.getAdverseEvents() == null || rpSrc.getAdverseEvents().isEmpty()){
errors.addValidationError("WS_AEMS_025", "Missing Adverse Events in the input message");
return errors;
}
//do I have study site details ?
StudySite studySiteSrc = rpSrc.getStudySite();
if(studySiteSrc == null){
errors.addValidationError("WS_AEMS_034", "StudySite information is missing in input message");
return errors;
}
if(studySiteSrc.getOrganization() == null || studySiteSrc.getOrganization().getNciInstituteCode() == null){
errors.addValidationError("ER-STU-3", "Missing Study Site details - Organization NCI code");
return errors;
}
//do I have study details ?
Study studySrc = rpSrc.getStudy();
if(studySrc == null || studySrc.getFundingSponsorIdentifierValue() == null){
logger.error("Missing study identifier");
errors.addValidationError("WS_AEMS_034", "Missing Study Identifier" );
return errors;
}
if(studySrc.getFundingSponsorIdentifierValue() == null){
logger.error("Missing study identifier");
errors.addValidationError("WS_AEMS_034", "Missing Study Identifier");
return errors;
}
//do I have subject details ?
Participant subjectSrc = rpSrc.getParticipant();
if(subjectSrc == null ){
errors.addValidationError("ER-SUB-1", "Subject information is missing in input message");
return errors;
}
return errors;
}
private CaaersServiceResponse populateErrors(CaaersServiceResponse response, ValidationErrors errors){
logger.error("Adverse Event Management Service create or update call failed :" + String.valueOf(errors));
for(ValidationError ve : errors.getErrors()) {
String message = messageSource.getMessage(ve.getCode(), ve.getReplacementVariables(), ve.getMessage(), Locale.getDefault());
Helper.populateError(response, ve.getCode(), message);
}
return response;
}
private void migrate(ExpeditedAdverseEventReport aeSrcReport, ExpeditedAdverseEventReport aeDestReport, ValidationErrors errors){
try{
adeersIntegrationFacade.updateStudy(aeSrcReport.getStudy().getId(), true);
}catch (Exception e){
logger.warn("Study synchronization failed.", e);
}
DomainObjectImportOutcome<ExpeditedAdverseEventReport> outCome = new DomainObjectImportOutcome<ExpeditedAdverseEventReport>();
aeReportMigrator.migrate(aeSrcReport, aeDestReport, outCome);
if(outCome.hasErrors()) errors.addValidationErrors(outCome.getValidationErrors().getErrors());
}
private void transferStudySubjectIfRequired(ExpeditedAdverseEventReport aeSrcReport, ExpeditedAdverseEventReport aeDestReport,ValidationErrors errors){
try {
StudySite originalSite = aeDestReport.getAssignment().getStudySite();
Participant dbParticipant = aeDestReport.getAssignment().getParticipant();
Organization organizationTransferredTo = aeSrcReport.getAssignment().getStudySite().getOrganization();
if(!aeDestReport.getAssignment().getStudySite().getOrganization().getNciInstituteCode().
equals(aeSrcReport.getAssignment().getStudySite().getOrganization().getNciInstituteCode())){
participantService.transferParticipant(dbParticipant, originalSite, organizationTransferredTo, errors);
}
} catch (Exception e) {
logger.error("Error while transferring the StudySubject", e);
}
}
/**
* Will create a Report and associate it to the ExpeditedAdverseEventReport
* @param report
* @param aeReport
* @return
*/
public Report createReport(Report report, ExpeditedAdverseEventReport aeReport){
Date gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(aeReport.getUnReportedAdverseEvents());
report.getReportDefinition().setBaseDate(gradedDate);
Report newReport = reportRepository.createReport(report.getReportDefinition(), aeReport) ;
newReport.copy(report);
reportRepository.save(newReport);
return newReport;
}
/**
* Will update a Report associated it to the ExpeditedAdverseEventReport and in parallel withdraw any Notifications
* that are submitted previously for the Report being withdrawn.
* @param report
* @param aeReport
* @return
*/
public Report withdrawReport(Report report, ExpeditedAdverseEventReport aeReport){
reportRepository.withdrawReport(report);
reportRepository.withdrawExternalReport(aeReport, report);
return report;
}
/**
* Will amend the Report
* @param report
* @param aeReport
* @return
*/
public Report amendReport(Report report, ExpeditedAdverseEventReport aeReport){
reportRepository.amendReport(report);
return report;
}
/**
* Will unamend an older version when a new revision of the report is withdrawn.
* @param report
* @param aeReport
* @return
*/
public Report unAmendReport(Report report, ExpeditedAdverseEventReport aeReport){
reportRepository.unAmendReport(report);
return report;
}
/**
* Will initiate an safety reporting action, and return the Report Id
* @param aeSrcReport
* @param dbReport
* @param errors
* @return
*/
public ExpeditedAdverseEventReport initiateSafetyReportAction(ExpeditedAdverseEventReport aeSrcReport, CaaersServiceResponse caaersServiceResponse, ValidationErrors errors){
//Determine the flow, create vs update
String externalId = aeSrcReport.getExternalId();
ExpeditedAdverseEventReport dbReport = null;
if(StringUtils.isEmpty(externalId)) {
SafetyReportIdentifer newReportId = idServiceImpl.generateSafetyReportId(new ReportIdCriteria());
aeSrcReport.setExternalId(newReportId.getSafetyReportId());
List<Report> reports = aeSrcReport.getReports();
for (Report report : reports) {
report.setCaseNumber(newReportId.getSafetyReportId());
}
} else {
dbReport = externalId != null ? expeditedAdverseEventReportDao.getByExternalId(externalId) : null;
}
List<Report> reportsAffected = new ArrayList<Report>();
ExpeditedAdverseEventReport aeDestReport = new ExpeditedAdverseEventReport();
migrate(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return aeDestReport;
if(dbReport != null) {
DomainObjectImportOutcome<ExpeditedAdverseEventReport> outCome = new DomainObjectImportOutcome<ExpeditedAdverseEventReport>();
aeReportSynchronizer.migrate(aeDestReport, dbReport, outCome);
if(outCome.hasErrors()) errors.addValidationErrors(outCome.getValidationErrors().getErrors());
if(errors.hasErrors()) return aeDestReport;
}
transferStudySubjectIfRequired(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return aeDestReport;
if(dbReport == null){
//create flow
// Deep copy the reports as it is throwing ConcurrentModification Exception.
aeDestReport.updateAESignatures();
expeditedAdverseEventReportDao.save(aeDestReport);
List<Report> reports = new ArrayList<Report>(aeDestReport.getReports());
aeDestReport.getReports().clear();
// Save the report(s) after Migration.
for ( Report rpt: reports ) {
Report createdReport = createReport(rpt, aeDestReport);
reportsAffected.add(createdReport);
if(caaersServiceResponse != null){
buildReportInformationOutput(createdReport, caaersServiceResponse, ActionType.CREATE);
}
}
}else{
//update flow
dbReport.updateAESignatures();
expeditedAdverseEventReportDao.save(dbReport);
for(Report r : dbReport.getActiveReports()) {
reportRepository.save(r);
}
inferReportingAction(aeSrcReport, dbReport, aeDestReport, reportsAffected, caaersServiceResponse);
}
if(getEventFactory() != null) getEventFactory().publishEntityModifiedEvent(aeDestReport);
return aeDestReport;
}
/**
* Will update an ExpeditedAdverseEventReport, and return the list of Reports that got updated.
* @param aeSrcReport
* @param dbReport
* @param errors
* @return
*/
public List<Report> updateSafetyReport(ExpeditedAdverseEventReport aeSrcReport, ExpeditedAdverseEventReport dbReport, ValidationErrors errors){
List<Report> reportsAffected = new ArrayList<Report>();
ExpeditedAdverseEventReport aeDestReport = new ExpeditedAdverseEventReport();
migrate(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return reportsAffected;
DomainObjectImportOutcome<ExpeditedAdverseEventReport> outCome = new DomainObjectImportOutcome<ExpeditedAdverseEventReport>();
aeReportSynchronizer.migrate(aeDestReport, dbReport, outCome);
if(outCome.hasErrors()) errors.addValidationErrors(outCome.getValidationErrors().getErrors());
if(errors.hasErrors()) return reportsAffected;
expeditedAdverseEventReportDao.save(dbReport);
for(Report r : dbReport.getActiveReports()) {
reportRepository.save(r);
}
transferStudySubjectIfRequired(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return reportsAffected;
dbReport.getAssignment().synchronizeMedicalHistoryFromReportToAssignment(dbReport);
studyParticipantAssignmentDao.save(dbReport.getAssignment());
inferReportingAction(aeSrcReport, dbReport, aeDestReport, reportsAffected, null);
if(getEventFactory() != null) getEventFactory().publishEntityModifiedEvent(aeDestReport);
return reportsAffected;
}
private void inferReportingAction(ExpeditedAdverseEventReport aeSrcReport,
ExpeditedAdverseEventReport dbReport,
ExpeditedAdverseEventReport aeDestReport,
List<Report> reportsAffected, CaaersServiceResponse caaersServiceResponse) {
//Withdraw active reports
//find active reports that are eligible for withdraw
List<Report> withdrawableReports = dbReport.getActiveReports();
List<Report> reportsToBeWithdrawn = new ArrayList<Report>();
for(Report report : aeDestReport.getReports()){
if(report.getWithdrawnOn() != null){
// add the withdrawn report to withdraw list
reportsToBeWithdrawn.add(report);
for(Report withdrawableReport : withdrawableReports){
if(withdrawableReport.isSameReportByCaseNumberOrReportDefinition(report)){
withdrawReport(withdrawableReport, dbReport);
if(caaersServiceResponse != null){
buildReportInformationOutput(withdrawableReport, caaersServiceResponse, ActionType.WITHDRAW);
}
}
}
}
}
// remove reports that are withdrawn
for(Report withdrawnreport : reportsToBeWithdrawn){
aeDestReport.getReports().remove(withdrawnreport);
}
// Find a relationship between parent and child exists. check if the parent report is already submitted.
Report parentCompletedReport = null;
for(Report srcReport : dbReport.getReports()){
if (srcReport.getStatus().equals(ReportStatus.COMPLETED) && srcReport.getReportDefinition().getName().equals(aeSrcReport.getReports().get(0).getReportDefinition().getName())) {
// Check if the child record exists.
parentCompletedReport = srcReport;
}
}
//if parent report is completed, change the updateReport definition to match the child report, ie, followup report
if ( parentCompletedReport != null ) {
for(Report srcReport : dbReport.getReports()){
if ( ! ( srcReport.getStatus().equals(ReportStatus.INPROCESS) || srcReport.getStatus().equals(ReportStatus.PENDING) )) continue; // If the Report is completed then skip it.
ReportDefinition parentReportDef = srcReport.getReportDefinition().getParent();
if (parentReportDef != null && parentReportDef.getName().equals(parentCompletedReport.getName()) ) {
// Override the Report Definition of the Source to Child since child Report is active.
if ( aeDestReport.getReports().size() != 0 ) {
aeDestReport.getReports().get(0).setReportDefinition(srcReport.getReportDefinition());
}
}
}
}
//create, amend or withdraw reports
for(Report srcReport : aeDestReport.getReports()){
List<Report> reportsToAmend = dbReport.findReportsToAmmend(srcReport.getReportDefinition());
for(Report report: reportsToAmend){
amendReport(report, dbReport);
//reportsAffected.add(createReport(srcReport, dbReport));
if(caaersServiceResponse != null){
buildReportInformationOutput(report, caaersServiceResponse, ActionType.AMEND);
}
}
List<Report> reportsToWithdraw = dbReport.findReportsToWithdraw(srcReport.getReportDefinition());
for(Report report: reportsToWithdraw){
withdrawReport(report, dbReport);
if(caaersServiceResponse != null){
buildReportInformationOutput(report, caaersServiceResponse, ActionType.WITHDRAW);
}
}
List<Report> reportsToEdit = dbReport.findReportsToEdit(srcReport.getReportDefinition());
if(reportsToEdit.isEmpty()) {
Report createdReport = createReport(srcReport, dbReport);
reportsAffected.add(createdReport);
if(caaersServiceResponse != null){
buildReportInformationOutput(createdReport, caaersServiceResponse, ActionType.CREATE);
}
} else {
for(Report report: reportsToEdit){
reportsAffected.add(report);
// Copy the Submitter Information from the Input Source.
//TODO : need to check if we should call the report.copy() to get all the info
report.setSubmitter(srcReport.getSubmitter());
report.setCaseNumber(srcReport.getCaseNumber());
if(caaersServiceResponse != null){
buildReportInformationOutput(report, caaersServiceResponse, ActionType.EDIT);
}
}
}
//TODO : BJ implement unammend feature
}
}
/**
* Will create an ExpeditedAdverseEventReport, then will return all the Reports that got created.
* @param aeSrcReport
* @param aeDestReport
* @param errors
* @return
*/
public List<Report> createSafetyReport(ExpeditedAdverseEventReport aeSrcReport, ExpeditedAdverseEventReport aeDestReport, ValidationErrors errors){
List<Report> reportsAffected = new ArrayList<Report>();
//Call the Migration
migrate(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return reportsAffected;
for(AdverseEvent ae : aeDestReport.getAdverseEvents()){
ae.setReport(aeDestReport);
}
// Set the signature for the AE.
aeDestReport.updateAESignatures();
//Call the ExpediteReportDao and save this report.
expeditedAdverseEventReportDao.save(aeDestReport);
// transfer the study subject if required.
transferStudySubjectIfRequired(aeSrcReport, aeDestReport, errors);
if(errors.hasErrors()) return reportsAffected;
aeDestReport.getAssignment().synchronizeMedicalHistoryFromReportToAssignment(aeDestReport);
studyParticipantAssignmentDao.save(aeDestReport.getAssignment());
// Deep copy the reports as it is throwing ConcurrentModification Exception.
List<Report> reports = new ArrayList<Report>(aeDestReport.getReports());
aeDestReport.getReports().clear();
// Save the report(s) after Migration.
for ( Report rpt: reports ) {
reportsAffected.add(createReport(rpt, aeDestReport));
}
if(getEventFactory() != null) getEventFactory().publishEntityModifiedEvent(aeDestReport);
return reportsAffected;
}
/**
* Will initiate the safety reporting action
* @param adverseEventReport
* @return
*/
@Transactional(readOnly=false)
public CaaersServiceResponse
initiateSafetyReportAction(BaseAdverseEventReport baseAadverseEventReport) throws Exception {
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
ValidationErrors errors = new ValidationErrors();
ExpeditedAdverseEventReport aeSrcReport = null;
try {
// 1. Call the Converter(s) to construct the domain object.
aeSrcReport = baseEaeConverter.convert(baseAadverseEventReport);
}catch (Exception e){
logger.error("Unable to convert the XML report to domain object", e);
Helper.populateError(caaersServiceResponse, "WS_GEN_000","Error while converting XML to domain object:" + e.getMessage() );
throw e;
}
try{
// initialize the service response
ResponseDataType rdType = new ResponseDataType();
caaersServiceResponse.getServiceResponse().setResponseData(rdType);
rdType.setAny(new BaseReports());
initiateSafetyReportAction(aeSrcReport, caaersServiceResponse, errors);
if(errors.hasErrors()) {
expeditedAdverseEventReportDao.clearSession();
populateErrors(caaersServiceResponse, errors);
} else {
caaersServiceResponse.getServiceResponse().setMessage("Initiated safety report action for the safety report, " + baseAadverseEventReport.getExternalId());
}
}catch (Exception e){
logger.error("Unable to initiate a safety report action from Safety Management Service", e);
Helper.populateError(caaersServiceResponse, "WS_GEN_000",e.getMessage() );
throw e;
}
return caaersServiceResponse;
}
/**
* Will create/update the ExpeditedAdverseEventReport and then will submit the Reports modified to external agency.
* @param adverseEventReport
* @return
*/
@Transactional(readOnly=false)
public CaaersServiceResponse submitSafetyReport(AdverseEventReport adverseEventReport) throws Exception {
CaaersServiceResponse response = Helper.createResponse();
try{
List<Report> reportsAffected = new ArrayList<Report>();
ValidationErrors errors = createOrUpdateSafetyReport(adverseEventReport, reportsAffected);
if(errors.hasErrors()) {
populateErrors(response, errors);
return response;
}
//submit report
List<Report> failedReports = new ArrayList<Report>();
for(Report report : reportsAffected){
reportSubmissionService.submitReport(report);
if(ReportStatus.FAILED.equals(report.getStatus())) {
failedReports.add(report);
}
}
if (!failedReports.isEmpty()) {
StringBuilder str = new StringBuilder(1024);
str.append("Could not send ").append(failedReports.size()).append(" out of ").append(reportsAffected.size()).append(" reports, for the following reasons;\n");
for(Report r : failedReports) {
str.append("Report: '").append(r.getName()).append("' (").append(r.getId()).append("); Error: ").append(r.getSubmissionMessage()).append("\n\n");
}
logger.error(str.toString());
Helper.populateError(response, "WS_GEN_007", str.toString().trim());
}
} catch (Exception e) {
logger.error("Unable to Create/Update a Report from Safety Management Service", e);
Helper.populateError(response, "WS_GEN_000",e.getMessage() );
throw e;
}
return response;
}
/**
* Will save the ExpeditedAdverseEventReport
* @param adverseEventReport
* @return
*/
@Transactional(readOnly=false)
public CaaersServiceResponse saveSafetyReport(AdverseEventReport adverseEventReport) {
CaaersServiceResponse response = Helper.createResponse();
try{
ValidationErrors errors = createOrUpdateSafetyReport(adverseEventReport, new ArrayList<Report>());
if(errors.hasErrors()) populateErrors(response, errors);
}catch (Exception e){
logger.error("Unable to Create/Update a Report from Safety Management Service", e);
Helper.populateError(response, "WS_GEN_000",e.getMessage() );
}
return response;
}
private void buildReportInformationOutput(Report report, CaaersServiceResponse caaersServiceResponse, ActionType actionType){
BaseReportType baseReport = new BaseReportType();
baseReport.setReportID(report.getAeReport().getExternalId());
baseReport.setAction(actionType.getDisplayName());
if(report.getLastVersion().getAmendmentNumber() != null) {
baseReport.setAmendmentNumber(report.getLastVersion().getAmendmentNumber().toString());
}
baseReport.setReportName(report.getReportDefinition().getName());
baseReport.setCaseNumber(report.getCaseNumber());
if((report.getStatus() == ReportStatus.AMENDED || report.getStatus() == ReportStatus.PENDING || report.getStatus() == ReportStatus.FAILED ||
report.getStatus() == ReportStatus.INPROCESS) && report.getDueOn() != null){
baseReport.setDueDate(DateUtils.getDateWithTimeZone(report.getDueOn()).toString());
}
baseReport.setActionText(actionType.name().substring(0, 1).toUpperCase() +
actionType.name().substring(1, actionType.name().length()).toLowerCase() +
" the " + report.getReportDefinition().getName());
((BaseReports)(caaersServiceResponse.getServiceResponse().getResponseData().getAny())).getBaseReport().add(baseReport);
}
/**
* Will create or update an ExpeditedAdverseEventReport, and updates the reportsAffected with the Reports that
* got amended/edited/created.
* @param adverseEventReport
* @param reportsAffected
* @return
* @throws Exception
*/
public ValidationErrors createOrUpdateSafetyReport(AdverseEventReport adverseEventReport, List<Report> reportsAffected) throws Exception {
ValidationErrors errors = new ValidationErrors();
ExpeditedAdverseEventReport aeSrcReport = null;
try {
// 1. Call the Converter(s) to construct the domain object.
aeSrcReport = eaeConverter.convert(adverseEventReport);
}catch(Exception e) {
logger.error("Error while converting AdverseEvent XML to domain object", e);
errors.addValidationError( "WS_GEN_008","Error while converting XML to domain object:" + e.getMessage() );
return errors;
}
try {
//2. Do some basic validations (if needed)
//3. Determine the flow, create vs update
String externalId = aeSrcReport.getExternalId();
ExpeditedAdverseEventReport dbAeReport = externalId != null ? expeditedAdverseEventReportDao.getByExternalId(externalId) : null;
if(dbAeReport == null){
//create flow
reportsAffected.addAll(createSafetyReport(aeSrcReport, new ExpeditedAdverseEventReport(), errors));
}else{
//update flow
reportsAffected.addAll(updateSafetyReport(aeSrcReport, dbAeReport, errors));
}
if(errors.hasErrors()) {
expeditedAdverseEventReportDao.clearSession();
return errors;
}
}catch(Exception e) {
expeditedAdverseEventReportDao.clearSession();
logger.error("Unable to Create/Update a Report from Safety Management Service", e);
errors.addValidationError( "WS_GEN_000","Error while creating or updating safety report:" + e.getMessage() );
}
return errors;
}
public BaseExpeditedAdverseEventReportConverter getBaseEaeConverter() {
return baseEaeConverter;
}
public void setBaseEaeConverter(
BaseExpeditedAdverseEventReportConverter baseEaeConverter) {
this.baseEaeConverter = baseEaeConverter;
}
public ExpeditedAdverseEventReportConverter getEaeConverter() {
return eaeConverter;
}
public void setEaeConverter(ExpeditedAdverseEventReportConverter eaeConverter) {
this.eaeConverter = eaeConverter;
}
public ParticipantServiceImpl getParticipantService() {
return participantService;
}
public void setParticipantService(ParticipantServiceImpl participantService) {
this.participantService = participantService;
}
public ParticipantDao getParticipantDao() {
return participantDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public StudyDao getStudyDao() {
return studyDao;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public MessageSource getMessageSource() {
return messageSource;
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public ExpeditedAdverseEventReportDao getExpeditedAdverseEventReportDao() {
return expeditedAdverseEventReportDao;
}
public void setExpeditedAdverseEventReportDao(ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao) {
this.expeditedAdverseEventReportDao = expeditedAdverseEventReportDao;
}
public ExpeditedReportMigrator getAeReportMigrator() {
return aeReportMigrator;
}
public void setAeReportMigrator(ExpeditedReportMigrator aeReportMigrator) {
this.aeReportMigrator = aeReportMigrator;
}
public ExpeditedAdverseEventReportValidator getAeReportValidator() {
return aeReportValidator;
}
public void setAeReportValidator(
ExpeditedAdverseEventReportValidator aeReportValidator) {
this.aeReportValidator = aeReportValidator;
}
public ExpeditedAdverseEventReportSynchronizer getAeReportSynchronizer() {
return aeReportSynchronizer;
}
public void setAeReportSynchronizer(ExpeditedAdverseEventReportSynchronizer aeReportSynchronizer) {
this.aeReportSynchronizer = aeReportSynchronizer;
}
public StudyParticipantAssignmentDao getStudyParticipantAssignmentDao() {
return studyParticipantAssignmentDao;
}
public void setStudyParticipantAssignmentDao(StudyParticipantAssignmentDao studyParticipantAssignmentDao) {
this.studyParticipantAssignmentDao = studyParticipantAssignmentDao;
}
} |
package org.jasig.cas.web.flow;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.util.StringUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
/**
* Class to automatically set the paths for the CookieGenerators.
* <p>
* Note: This is technically not threadsafe, but because its overriding with a
* constant value it doesn't matter.
* <p>
* Note: As of CAS 3.1, this is a required class that retrieves and exposes the
* values in the two cookies for subclasses to use.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.1
*/
public final class InitialFlowSetupAction extends AbstractAction {
/** CookieGenerator for the Warnings. */
@NotNull
private CookieRetrievingCookieGenerator warnCookieGenerator;
/** CookieGenerator for the TicketGrantingTickets. */
@NotNull
private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
/** Extractors for finding the service. */
@NotNull
@Size(min=1)
private List<ArgumentExtractor> argumentExtractors;
/** Boolean to note whether we've set the values on the generators or not. */
private boolean pathPopulated = false;
protected Event doExecute(final RequestContext context) throws Exception {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
if (!this.pathPopulated) {
final String contextPath = context.getExternalContext().getContextPath();
final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + "/" : "/";
logger.info("Setting path for cookies to: "
+ cookiePath);
this.warnCookieGenerator.setCookiePath(cookiePath);
this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);
this.pathPopulated = true;
}
context.getFlowScope().put(
"ticketGrantingTicketId", this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
context.getFlowScope().put(
"warnCookieValue",
Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));
final Service service = WebUtils.getService(this.argumentExtractors,
context);
if (service != null && logger.isDebugEnabled()) {
logger.debug("Placing service in FlowScope: " + service.getId());
}
context.getFlowScope().put("service", service);
return result("success");
}
public void setTicketGrantingTicketCookieGenerator(
final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {
this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;
}
public void setWarnCookieGenerator(final CookieRetrievingCookieGenerator warnCookieGenerator) {
this.warnCookieGenerator = warnCookieGenerator;
}
public void setArgumentExtractors(
final List<ArgumentExtractor> argumentExtractors) {
this.argumentExtractors = argumentExtractors;
}
} |
package com.archimatetool.editor.propertysections;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
import com.archimatetool.model.IArchimateConcept;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IArchimateModelObject;
import com.archimatetool.model.IArchimatePackage;
import com.archimatetool.model.IProfile;
import com.archimatetool.model.util.ArchimateModelUtils;
import com.archimatetool.model.util.LightweightEContentAdapter;
/**
* Property Section for a Specialization
*
* @author Phillip Beauvoir
*/
public class SpecializationSection extends AbstractECorePropertySection {
private static final String HELP_ID = "com.archimatetool.help.elementPropertySection"; //$NON-NLS-1$
/**
* Filter to show or reject this section depending on input value
*/
public static class Filter extends ObjectFilter {
@Override
public boolean isRequiredType(Object object) {
return object instanceof IArchimateConcept;
}
@Override
public Class<?> getAdaptableType() {
return IArchimateConcept.class;
}
}
private ComboViewer fComboViewer;
/**
* Set this to true when updating control to stop recursive update
*/
private boolean fIsRefreshing;
/**
* Dummy Profile representing "none"
*/
private IProfile NONE_PROFILE;
/**
* Model that we are listening to changes on
*/
private IArchimateModel fModel;
/**
* Adapter to listen to Model's changes, basically an AdapterImpl
*/
private LightweightEContentAdapter eAdapter = new LightweightEContentAdapter(this::notifyChanged);
@Override
protected void createControls(Composite parent) {
NONE_PROFILE = IArchimateFactory.eINSTANCE.createProfile();
NONE_PROFILE.setName("(none)");
createLabel(parent, "Specialization:", ITabbedLayoutConstants.STANDARD_LABEL_WIDTH, SWT.CENTER);
fComboViewer = new ComboViewer(new Combo(parent, SWT.READ_ONLY | SWT.BORDER));
fComboViewer.getCombo().setVisibleItemCount(12);
fComboViewer.getControl().setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
getWidgetFactory().adapt(fComboViewer.getControl(), true, true);
fComboViewer.addSelectionChangedListener(event -> {
if(fIsRefreshing) { // A Viewer will get a selectionChanged event when setting it
return;
}
IProfile profile = (IProfile)((IStructuredSelection)event.getSelection()).getFirstElement();
if(profile != null) {
// None Profile is null
if(profile == NONE_PROFILE) {
profile = null;
}
CompoundCommand result = new CompoundCommand();
for(EObject object : getEObjects()) {
if(isAlive(object)) {
Command cmd = new SetProfileCommand((IArchimateConcept)object, profile);
if(cmd.canExecute()) {
result.add(cmd);
}
}
}
executeCommand(result.unwrap());
}
});
fComboViewer.setContentProvider(new IStructuredContentProvider() {
/**
* Return a list of suitable Profiles in the model given the concept type of the first selected object
*/
@Override
public Object[] getElements(Object inputElement) {
IArchimateConcept firstSelected = (IArchimateConcept)getFirstSelectedObject();
if(firstSelected == null) {
return new Object[0];
}
List<IProfile> list = ArchimateModelUtils.findProfilesForConceptType(firstSelected.getArchimateModel(), firstSelected.eClass());
// Sort the Profiles by name
Collections.sort(list, new Comparator<IProfile>() {
@Override
public int compare(IProfile p1, IProfile p2) {
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
// Add the "none" Profile at the top
list.add(0, NONE_PROFILE);
return list.toArray();
}
});
fComboViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
return ((IProfile)element).getName();
}
});
fComboViewer.setInput(""); //$NON-NLS-1$
// Help ID
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HELP_ID);
}
@Override
protected void notifyChanged(Notification msg) {
Object feature = msg.getFeature();
// If model profiles changed or this concept's profile changed
if(feature == IArchimatePackage.Literals.ARCHIMATE_MODEL__PROFILES || feature == IArchimatePackage.Literals.PROFILES__PROFILES) {
update();
}
}
@Override
protected void update() {
IArchimateModelObject firstSelected = getFirstSelectedObject();
// Check also if the selected object has been deleted in case the Properties View is still showing the object if it has the focus
if(fIsExecutingCommand || !isAlive(getFirstSelectedObject())) {
return;
}
fComboViewer.refresh();
if(firstSelected instanceof IArchimateConcept) {
fIsRefreshing = true; // A Viewer will get a selectionChanged event when setting it
EList<IProfile> profiles = ((IArchimateConcept)firstSelected).getProfiles();
if(!profiles.isEmpty()) {
fComboViewer.setSelection(new StructuredSelection(profiles.get(0)));
}
else {
fComboViewer.setSelection(new StructuredSelection(NONE_PROFILE));
}
fIsRefreshing = false;
}
}
@Override
protected IObjectFilter getFilter() {
return new Filter();
}
@Override
protected void addAdapter() {
super.addAdapter();
// Add our adapter to the parent model to listen to its profile changes so we can update the combo
IArchimateModelObject selected = getFirstSelectedObject();
if(selected != null && selected.getArchimateModel() != null && !selected.getArchimateModel().eAdapters().contains(eAdapter)) {
fModel = selected.getArchimateModel(); // Store the parent model in case the selected object is deleted
fModel.eAdapters().add(eAdapter);
}
}
@Override
protected void removeAdapter() {
super.removeAdapter();
// Remove our adapter from the model
if(fModel != null) {
fModel.eAdapters().remove(eAdapter);
}
}
@Override
public void dispose() {
super.dispose(); // super first
fModel = null;
}
/**
* Set Profile Command
*/
private static class SetProfileCommand extends Command {
private IArchimateConcept owner;
private IProfile oldProfile, newProfile;
SetProfileCommand(IArchimateConcept owner, IProfile profile) {
this.owner = owner;
newProfile = profile;
setLabel("Set Specialization");
}
@Override
public void execute() {
// Contains no Profiles, so add it
if(owner.getProfiles().isEmpty()) {
owner.getProfiles().add(newProfile);
}
// Contains at least one Profile, so store old one and set to new one
else {
// Store old Profile
oldProfile = owner.getPrimaryProfile();
// New profile is null so remove Profile
if(newProfile == null) {
owner.getProfiles().remove(oldProfile);
}
// Set to new Profile
else {
owner.getProfiles().set(0, newProfile);
}
}
}
@Override
public void undo() {
// We have an old Profile
if(oldProfile != null) {
// If Empty add it
if(owner.getProfiles().isEmpty()) {
owner.getProfiles().add(oldProfile);
}
// Else set it
else {
owner.getProfiles().set(0, oldProfile);
}
}
// Else remove it
else {
owner.getProfiles().remove(newProfile);
}
}
@Override
public boolean canExecute() {
// This first - If the new Profile is null and owner has no Profiles then can't execute
if(newProfile == null) {
return !owner.getProfiles().isEmpty();
}
// If Profile's concept type doesn't match owner type
if(!owner.eClass().getName().equals(newProfile.getConceptType())) {
return false;
}
// If owner's Primary Profile is already set to this Profile
if(owner.getPrimaryProfile() == newProfile) {
return false;
}
return true;
}
@Override
public void dispose() {
owner = null;
oldProfile = null;
newProfile = null;
}
}
} |
package org.jboss.windup.config.operation.ruleelement;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.jboss.forge.furnace.Furnace;
import org.jboss.forge.furnace.services.Imported;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.selectables.SelectionFactory;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.GraphUtil;
import org.jboss.windup.graph.model.ArchiveModel;
import org.jboss.windup.graph.model.ArchiveModelPointer;
import org.jboss.windup.graph.model.WindupVertexFrame;
import org.ocpsoft.rewrite.context.EvaluationContext;
public class ConfigureArchiveTypes extends AbstractIterationOperator<ArchiveModel>
{
//private @Inject Imported<ArchiveModelPointer> archiveModelPointers;
private @Inject Furnace furnace;
private HashMap<String, Class> suffixToModelClass;
public ConfigureArchiveTypes(String variableName)
{
super(ArchiveModel.class, variableName);
}
public static ConfigureArchiveTypes forVar(String variableName)
{
return new ConfigureArchiveTypes(variableName);
}
@Override
public void perform(GraphRewrite event, EvaluationContext context, ArchiveModel archiveModel)
{
GraphContext graphContext = event.getGraphContext();
String filename = archiveModel.getArchiveName();
WindupVertexFrame newFrame = null;
for( Map.Entry<String, Class> entry : suffixToModelClass.entrySet() ) {
if( StringUtils.endsWith( filename, entry.getKey() ) ){
newFrame = GraphUtil.addTypeToModel(graphContext, archiveModel, entry.getValue());
}
}
} |
/*
* (e-mail:zhongxunking@163.com)
*/
/*
* :
* @author 2018-12-08 20:57
*/
package org.antframework.configcenter.facade.order;
import lombok.Getter;
import lombok.Setter;
import org.antframework.common.util.facade.AbstractOrder;
import org.antframework.configcenter.facade.vo.Property;
import org.antframework.configcenter.facade.vo.ReleaseConstant;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* order
*/
public class AddReleaseOrder extends AbstractOrder {
@NotBlank
@Getter
@Setter
private String appId;
@NotBlank
@Getter
@Setter
private String profileId;
@Min(ReleaseConstant.ORIGIN_VERSION)
@NotNull
@Getter
@Setter
private Long parentVersion;
@Getter
@Setter
private String memo;
@NotNull
@Getter
private Set<Property> addedOrModifiedProperties = new HashSet<>();
@NotNull
@Getter
private Set<String> deletedPropertyKeys = new HashSet<>();
public void addAddedOrModifiedProperty(Property property) {
addedOrModifiedProperties.add(property);
}
public void addDeletedPropertyKey(String propertyKey) {
deletedPropertyKeys.add(propertyKey);
}
} |
package com.sequenceiq.cloudbreak.service.cluster.flow;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
@Component
public class FixedDefaultConfigProvider implements DefaultConfigProvider {
@Override
public List<BlueprintConfigurationEntry> getDefaultConfigs() {
List<BlueprintConfigurationEntry> defaultConfigEntries = new ArrayList<>();
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "mapreduce.map.memory.mb", "1536"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "mapreduce.reduce.memory.mb", "3072"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "mapreduce.map.java.opts", "-Xmx1228m"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "mapreduce.reduce.java.opts", "-Xmx2457m"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "mapreduce.task.io.sort.mb", "614"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("yarn-site", "yarn.scheduler.minimum-allocation-mb", "1536"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("yarn-site", "yarn.scheduler.maximum-allocation-mb", "6144"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("yarn-site", "yarn.nodemanager.resource.memory-mb", "6144"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("mapred-site", "yarn.app.mapreduce.am.resource.mb", "3072"));
defaultConfigEntries
.add(new BlueprintConfigurationEntry("mapred-site", "yarn.app.mapreduce.am.command-opts", "-Xmx2457m -Dhdp.version=${hdp.version}"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.falcon.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.hbase.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.hcat.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.hive.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.oozie.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "hadoop.proxyuser.root.groups", "*"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("core-site", "proxyuser_group", "hadoop"));
defaultConfigEntries.add(new BlueprintConfigurationEntry("hbase-site", "zookeeper.recovery.retry", "10"));
return defaultConfigEntries;
}
} |
package com.gaiagps.iburn.api;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.gaiagps.iburn.SECRETS;
import com.gaiagps.iburn.api.response.Art;
import com.gaiagps.iburn.api.response.Camp;
import com.gaiagps.iburn.api.response.DataManifest;
import com.gaiagps.iburn.api.response.Event;
import com.gaiagps.iburn.api.response.EventOccurrence;
import com.gaiagps.iburn.api.response.PlayaItem;
import com.gaiagps.iburn.api.response.ResourceManifest;
import com.gaiagps.iburn.api.typeadapter.PlayaDateTypeAdapter;
import com.gaiagps.iburn.database.ArtTable;
import com.gaiagps.iburn.database.CampTable;
import com.gaiagps.iburn.database.DataProvider;
import com.gaiagps.iburn.database.EventTable;
import com.gaiagps.iburn.database.PlayaDatabase;
import com.gaiagps.iburn.database.PlayaItemTable;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.sqlbrite.SqlBrite;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import retrofit.RestAdapter;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
import retrofit.http.GET;
import retrofit.http.Streaming;
import rx.Observable;
import timber.log.Timber;
public class IBurnService {
public static final String PREFS_NAME = "api";
/**
* API Definition
*/
public interface IBurnAPIService {
@GET("/update.json.js")
Observable<DataManifest> getDataManifest();
@GET("/camps.json.js")
Observable<List<Camp>> getCamps();
@GET("/art.json.js")
Observable<List<Art>> getArt();
@GET("/events.json.js")
Observable<List<Event>> getEvents();
@GET("/iburn.mbtiles.jar")
@Streaming
Observable<Response> getTiles();
}
/**
* A mechanism for migrating internal app data not defined by the iBurn API.
*/
public interface UpgradeLifeboat {
/**
* Save any database data not represented by the iBurn API
*
* @param database the internal app database
*/
Observable<Boolean> saveData(SqlBrite database);
/**
* @param row the row of refreshsed data from the iBurn API.
* Add any internal data captured in {@link #saveData(SqlBrite)}.
* Be explicit and do not make assumptions about default values, as
* row may be recycled from a previous item.
*/
void restoreData(ContentValues row);
}
/**
* Persist user-defined favorites based on {@link PlayaItemTable#playaId}.
* This is suitable for {@link PlayaDatabase#ART} and {@link PlayaDatabase#CAMPS} collections.
* <p>
* It *cannot* be used with {@link PlayaDatabase#EVENTS} because there may be multiple Event entries
* sharing the same playaId but having differing start and end times
*/
private class SimpleLifeboat implements UpgradeLifeboat {
private String tableName;
private List<Integer> favoritePlayaIds;
public SimpleLifeboat(String tableName) {
this.tableName = tableName;
}
@Override
public Observable<Boolean> saveData(SqlBrite database) {
return database.createQuery(tableName, "SELECT " + PlayaItemTable.playaId + " FROM " + tableName + " WHERE " + PlayaItemTable.favorite + " = ?", new String[]{"1"})
.map(SqlBrite.Query::run)
.map(cursor -> {
favoritePlayaIds = new ArrayList<>(cursor.getCount());
Timber.d("Found %d %s favorites", cursor.getCount(), tableName);
while (cursor.moveToNext()) {
favoritePlayaIds.add(cursor.getInt(cursor.getColumnIndex(PlayaItemTable.playaId)));
}
cursor.close();
return true;
})
.first();
}
@Override
public void restoreData(ContentValues row) {
row.put(PlayaItemTable.favorite, favoritePlayaIds.contains(row.getAsInteger(PlayaItemTable.playaId)));
}
}
private class EventLifeboat implements UpgradeLifeboat {
private final String tableName = PlayaDatabase.EVENTS;
private HashMap<Integer, HashSet<String>> favoriteIds;
@Override
public Observable<Boolean> saveData(SqlBrite database) {
return database.createQuery(tableName, "SELECT " + PlayaItemTable.playaId + " , " + EventTable.startTime + " FROM " + tableName + " WHERE " + PlayaItemTable.favorite + " = ?", new String[]{"1"})
.map(SqlBrite.Query::run)
.map(cursor -> {
favoriteIds = new HashMap<>(cursor.getCount());
Timber.d("Found %d %s favorites", cursor.getCount(), tableName);
int favoriteId;
while (cursor.moveToNext()) {
favoriteId = cursor.getInt(0);
if (!favoriteIds.containsKey(favoriteId))
favoriteIds.put(favoriteId, new HashSet<>());
Timber.d("Added fav event with id %d start time %s", cursor.getInt(0), cursor.getString(1));
favoriteIds.get(favoriteId).add(cursor.getString(1));
}
cursor.close();
return true;
})
.first();
}
@Override
public void restoreData(ContentValues row) {
int playaId = row.getAsInteger(EventTable.playaId);
row.put(EventTable.favorite, favoriteIds.containsKey(playaId) &&
favoriteIds.get(playaId).contains(row.getAsString(EventTable.startTime)));
}
}
Context context;
IBurnAPIService service;
DataManifest dataManifest;
public IBurnService(@NonNull Context context) {
this.context = context;
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new PlayaDateTypeAdapter())
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(SECRETS.IBURN_API_URL)
.setConverter(new GsonConverter(gson))
// .setLogLevel(RestAdapter.LogLevel.HEADERS_AND_ARGS)
.build();
service = restAdapter.create(IBurnAPIService.class);
}
public void updateData() {
// Check local update dates for each endpoint, update those that are stale
final SharedPreferences storage = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
service.getDataManifest()
.flatMap(dataManifest1 -> {
IBurnService.this.dataManifest = dataManifest1;
Timber.d("Got Data Manifest. art : %s, camps : %s, events : %s",
dataManifest1.art.updated, dataManifest1.camps.updated, dataManifest1.events.updated);
ResourceManifest[] resources = new ResourceManifest[]
{dataManifest1.art, dataManifest1.camps, dataManifest1.events, dataManifest1.tiles};
return Observable.from(resources);
})
.filter(resourceManifest -> shouldUpdateResource(storage, resourceManifest))
.flatMap(resourceManifest -> {
//Timber.d("Should update " + resourceManifest.file);
return updateResource(resourceManifest, dataManifest);
})
.reduce((aBoolean, aBoolean2) -> {
//Timber.d("Success %b %b", aBoolean, aBoolean2);
return aBoolean && aBoolean2;
})
.subscribe(aBoolean -> {
Timber.d("Updated All data successfully " + aBoolean);
});
}
private Observable<Boolean> updateArt() {
Timber.d("Updating art");
final String tableName = PlayaDatabase.ART;
return updateTable(service.getArt(), tableName, new SimpleLifeboat(tableName), (item, values, database) -> {
Art art = (Art) item;
values.put(ArtTable.artist, art.artist);
values.put(ArtTable.artistLoc, art.artistLocation);
database.insert(values);
});
}
private Observable<Boolean> updateCamps() {
Timber.d("Updating Camps");
final String tableName = PlayaDatabase.CAMPS;
return updateTable(service.getCamps(), tableName, new SimpleLifeboat(tableName), (item, values, database) -> {
values.put(CampTable.hometown, ((Camp) item).hometown);
database.insert(values);
});
}
private Observable<Boolean> updateEvents() {
Timber.d("Updating Events");
// Date format for machine-readable
final SimpleDateFormat mahineDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ", Locale.US);
// Date format for human-readable specific-time
final SimpleDateFormat timeDayFormatter = new SimpleDateFormat("EE M/d h:mm a", Locale.US);
// Date format for human-readable all-day
final SimpleDateFormat dayFormatter = new SimpleDateFormat("EE M/d", Locale.US);
final String tableName = PlayaDatabase.EVENTS;
return updateTable(service.getEvents(), tableName, new EventLifeboat(), (item, values, database) -> {
Event event = (Event) item;
// Event uses title, not name
values.put(EventTable.name, event.title);
values.put(EventTable.allDay, event.allDay ? 1 : 0);
values.put(EventTable.checkLocation, event.checkLocation ? 1 : 0);
values.put(EventTable.eventType, event.eventType.abbr);
if (event.hostedByCamp != null) {
values.put(EventTable.campName, event.hostedByCamp.name);
values.put(EventTable.campPlayaId, event.hostedByCamp.id);
}
for (EventOccurrence occurrence : event.occurrenceSet) {
values.put(EventTable.startTime, mahineDateFormatter.format(occurrence.startTime));
values.put(EventTable.startTimePrint, event.allDay ? dayFormatter.format(occurrence.startTime) :
timeDayFormatter.format(occurrence.startTime));
values.put(EventTable.endTime, mahineDateFormatter.format(occurrence.endTime));
values.put(EventTable.endTimePrint, event.allDay ? dayFormatter.format(occurrence.endTime) :
timeDayFormatter.format(occurrence.endTime));
database.insert(values);
}
});
}
private Observable<Boolean> updateTable(Observable<? extends Iterable<? extends PlayaItem>> items,
String tableName,
UpgradeLifeboat lifeboat,
BindObjectToContentValues binder) {
final AtomicBoolean initializedInsert = new AtomicBoolean(false);
final SqlBrite sqlBrite = DataProvider.getSqlBriteInstance(context);
final android.content.ContentValues values = new android.content.ContentValues();
// Fetch remote JSON and all existing internal records that are favorites, simultaneously
return Observable.zip(
items.doOnNext(resp -> Timber.d("got items")),
lifeboat.saveData(sqlBrite).doOnNext(result -> Timber.d("saved data")), (playaItems, lifeboatSuccess) -> {
if (!lifeboatSuccess)
throw new IllegalStateException("Lifeboat did not complete successfully!");
return playaItems;
})
.flatMap(Observable::from)
.doOnCompleted(() -> {
Timber.d("Finished %s insert", tableName);
sqlBrite.setTransactionSuccessful();
sqlBrite.endTransaction();
})
.map(item -> {
// Delete all old rows before inserting first new row
if (!initializedInsert.getAndSet(true)) {
int numDeleted = sqlBrite.delete(tableName, PlayaItemTable.id + " > 0", null);
Timber.d("Deleted %d existing rows. Beginning %s inserts", numDeleted, tableName);
sqlBrite.beginTransaction();
}
values.clear();
bindBaseValues(item, values);
binder.bindAndInsertValues(item, values, finalValues -> {
lifeboat.restoreData(finalValues);
sqlBrite.insert(tableName, finalValues);
});
return true;
})
.doOnError(throwable -> {
Timber.e(throwable, "Error inserting " + tableName);
sqlBrite.endTransaction();
})
.reduce((thisSuccess, accumulatedSuccess) -> thisSuccess && accumulatedSuccess);
}
interface BindObjectToContentValues<T extends PlayaItem> {
/**
* @param item the data source which extends {@link PlayaItem}
* @param values the persisted data sink, which already has all common {@link PlayaItem}
* attributes bound
* @param database the database on which to perform the insert via {@link com.gaiagps.iburn.api.IBurnService.DataBaseSink#insert(ContentValues)}
*/
void bindAndInsertValues(T item, android.content.ContentValues values, DataBaseSink database);
}
interface DataBaseSink {
void insert(ContentValues values);
}
/**
* Bind {@link PlayaItemTable} values described by the iBurn API. This does not include
* internal data columns like {@link PlayaItemTable#favorite}
*/
private void bindBaseValues(PlayaItem item, android.content.ContentValues values) {
// Name is a required column
values.put(PlayaItemTable.name, item.name != null ? item.name : "?");
values.put(PlayaItemTable.contact, item.contactEmail);
values.put(PlayaItemTable.description, item.description);
values.put(PlayaItemTable.playaId, item.id);
values.put(PlayaItemTable.latitude, item.latitude);
values.put(PlayaItemTable.longitude, item.longitude);
values.put(PlayaItemTable.playaAddress, item.location);
values.put(PlayaItemTable.url, item.url);
}
private Observable<Boolean> updateResource(ResourceManifest resourceManifest, DataManifest dataManifest) {
String resourceName = resourceManifest.file;
if (resourceName.equals(dataManifest.art.file))
return updateArt();
else if (resourceName.equals(dataManifest.camps.file))
return updateCamps();
else if (resourceName.equals(dataManifest.events.file))
return updateEvents();
else if (resourceName.equals(dataManifest.tiles.file))
return Observable.just(true);
// updateTiles();
// Unknown or Unimplemented situation
return Observable.just(false);
}
private boolean shouldUpdateResource(SharedPreferences storage, ResourceManifest resource) {
//Timber.d("%s ver local : %d remote: %d", resource.file, storage.getLong(resource.file, 0), resource.updated.getTime());
return storage.getLong(resource.file, 0) < resource.updated.getTime();
}
} |
package org.jboss.as.server.deployment.scanner;
import java.io.File;
import java.io.IOException;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.threads.JBossThreadFactory;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.ALL_ATTRIBUTES;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.AUTO_DEPLOY_EXPLODED;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.AUTO_DEPLOY_XML;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.AUTO_DEPLOY_ZIPPED;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.DEPLOYMENT_TIMEOUT;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.RELATIVE_TO;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.SCAN_ENABLED;
import static org.jboss.as.server.deployment.scanner.DeploymentScannerDefinition.SCAN_INTERVAL;
/**
* Operation adding a new {@link DeploymentScannerService}.
*
* @author John E. Bailey
* @author Emanuel Muckenhuber
* @author Stuart Douglas
*/
class DeploymentScannerAdd implements OperationStepHandler {
private final PathManager pathManager;
public DeploymentScannerAdd(final PathManager pathManager) {
this.pathManager = pathManager;
}
/**
* {@inheritDoc
*/
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final Resource resource = context.createResource(PathAddress.EMPTY_ADDRESS);
populateModel(context, operation, resource);
final ModelNode model = resource.getModel();
boolean stepCompleted = false;
if (context.isNormalServer()) {
final Boolean enabled = SCAN_ENABLED.resolveModelAttribute(context, operation).asBoolean();
final boolean bootTimeScan = context.isBooting() && (enabled == null || enabled == true);
final String path = DeploymentScannerDefinition.PATH.resolveModelAttribute(context, operation).asString();
final ModelNode relativeToNode = RELATIVE_TO.resolveModelAttribute(context, operation);
final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
final Boolean autoDeployZip = AUTO_DEPLOY_ZIPPED.resolveModelAttribute(context, operation).asBoolean();
final Boolean autoDeployExp = AUTO_DEPLOY_EXPLODED.resolveModelAttribute(context, operation).asBoolean();
final Boolean autoDeployXml = AUTO_DEPLOY_XML.resolveModelAttribute(context, operation).asBoolean();
final Long deploymentTimeout = DEPLOYMENT_TIMEOUT.resolveModelAttribute(context, operation).asLong();
final Integer scanInterval = SCAN_INTERVAL.resolveModelAttribute(context, operation).asInt();
final ThreadFactory threadFactory = new JBossThreadFactory(new ThreadGroup("DeploymentScanner-threads"), Boolean.FALSE, null, "%G - %t", null, null, AccessController.getContext());
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2, threadFactory);
final FileSystemDeploymentService bootTimeScanner;
if (bootTimeScan) {
final String pathName = pathManager.resolveRelativePathEntry(path, relativeTo);
File relativePath = null;
if (relativeTo != null) {
relativePath = new File(pathManager.getPathEntry(relativeTo).resolvePath());
}
bootTimeScanner = new FileSystemDeploymentService(relativeTo, new File(pathName), relativePath, null, scheduledExecutorService);
bootTimeScanner.setAutoDeployExplodedContent(autoDeployExp);
bootTimeScanner.setAutoDeployZippedContent(autoDeployZip);
bootTimeScanner.setAutoDeployXMLContent(autoDeployXml);
if (deploymentTimeout != null) {
bootTimeScanner.setDeploymentTimeout(deploymentTimeout);
}
if (scanInterval != null) {
bootTimeScanner.setScanInterval(scanInterval);
}
} else {
bootTimeScanner = null;
}
context.addStep(new OperationStepHandler() {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final List<ServiceController<?>> controllers = new ArrayList<ServiceController<?>>();
final ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
performRuntime(context, operation, model, verificationHandler, controllers, scheduledExecutorService, bootTimeScanner);
context.addStep(verificationHandler, OperationContext.Stage.VERIFY);
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
rollbackRuntime(context, operation, model, controllers);
}
});
}
}, OperationContext.Stage.RUNTIME);
if (bootTimeScan) {
final AtomicReference<ModelNode> deploymentOperation = new AtomicReference<ModelNode>();
final AtomicReference<ModelNode> deploymentResults = new AtomicReference<ModelNode>(new ModelNode());
final CountDownLatch scanDoneLatch = new CountDownLatch(1);
final CountDownLatch deploymentDoneLatch = new CountDownLatch(1);
final DeploymentOperations deploymentOps = new BootTimeScannerDeployment(deploymentOperation, deploymentDoneLatch, deploymentResults, scanDoneLatch);
scheduledExecutorService.submit(new Runnable() {
@Override
public void run() {
try {
bootTimeScanner.oneOffScan(deploymentOps);
} catch (Throwable t){
DeploymentScannerLogger.ROOT_LOGGER.initialScanFailed(t);
} finally {
scanDoneLatch.countDown();
}
}
});
boolean interrupted = false;
boolean asyncCountDown = false;
try {
scanDoneLatch.await();
final ModelNode op = deploymentOperation.get();
if (op != null) {
final ModelNode result = new ModelNode();
final PathAddress opPath = PathAddress.pathAddress(op.get(OP_ADDR));
final OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(opPath, op.get(OP).asString());
context.addStep(result, op, handler, OperationContext.Stage.MODEL);
stepCompleted = true;
context.completeStep(new OperationContext.ResultHandler() {
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
try {
deploymentResults.set(result);
} finally {
deploymentDoneLatch.countDown();
}
}
});
asyncCountDown = true;
} else {
stepCompleted = true;
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
} catch (InterruptedException e) {
interrupted = true;
throw new RuntimeException(e);
} finally {
if (!asyncCountDown) {
deploymentDoneLatch.countDown();
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
if (!stepCompleted) {
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException {
for (SimpleAttributeDefinition atr : ALL_ATTRIBUTES) {
atr.validateAndSet(operation, resource.getModel());
}
}
protected void performRuntime(final OperationContext context, ModelNode operation, ModelNode model, ServiceVerificationHandler verificationHandler,
List<ServiceController<?>> newControllers, final ScheduledExecutorService executorService,
final FileSystemDeploymentService bootTimeScanner) throws OperationFailedException {
final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
final String name = address.getLastElement().getValue();
final String path = DeploymentScannerDefinition.PATH.resolveModelAttribute(context, operation).asString();
final Boolean enabled = SCAN_ENABLED.resolveModelAttribute(context, operation).asBoolean();
final Integer interval = SCAN_INTERVAL.resolveModelAttribute(context, operation).asInt();
final String relativeTo = operation.hasDefined(CommonAttributes.RELATIVE_TO) ? RELATIVE_TO.resolveModelAttribute(context, operation).asString() : null;
final Boolean autoDeployZip = AUTO_DEPLOY_ZIPPED.resolveModelAttribute(context, operation).asBoolean();
final Boolean autoDeployExp = AUTO_DEPLOY_EXPLODED.resolveModelAttribute(context, operation).asBoolean();
final Boolean autoDeployXml = AUTO_DEPLOY_XML.resolveModelAttribute(context, operation).asBoolean();
final Long deploymentTimeout = DEPLOYMENT_TIMEOUT.resolveModelAttribute(context, operation).asLong();
final ServiceTarget serviceTarget = context.getServiceTarget();
DeploymentScannerService.addService(serviceTarget, name, relativeTo, path, interval, TimeUnit.MILLISECONDS,
autoDeployZip, autoDeployExp, autoDeployXml, enabled, deploymentTimeout, newControllers, bootTimeScanner, executorService, verificationHandler);
}
/**
* Rollback runtime changes made in {@link #performRuntime(org.jboss.as.controller.OperationContext, org.jboss.dmr.ModelNode, org.jboss.dmr.ModelNode, org.jboss.as.controller.ServiceVerificationHandler, java.util.List, ScheduledExecutorService, FileSystemDeploymentService}.
* <p>
* This default implementation removes all services in the given list of {@code controllers}. The contents of
* {@code controllers} is the same as what was in the {@code newControllers} parameter passed to {@code performRuntime()}
* when that method returned.
* </p>
*
* @param context the operation context
* @param operation the operation being executed
* @param model persistent configuration model node that corresponds to the address of {@code operation}
* @param controllers holder for the {@link ServiceController} for any new services installed by
* {@link #performRuntime(org.jboss.as.controller.OperationContext, org.jboss.dmr.ModelNode, org.jboss.dmr.ModelNode, org.jboss.as.controller.ServiceVerificationHandler, java.util.List}
*/
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final ModelNode model, List<ServiceController<?>> controllers) {
for (ServiceController<?> controller : controllers) {
context.removeService(controller.getName());
}
}
private static class BootTimeScannerDeployment implements DeploymentOperations {
private final AtomicReference<ModelNode> deploymentOperation;
private final CountDownLatch deploymentDoneLatch;
private final AtomicReference<ModelNode> deploymentResults;
private final CountDownLatch scanDoneLatch;
public BootTimeScannerDeployment(final AtomicReference<ModelNode> deploymentOperation, final CountDownLatch deploymentDoneLatch, final AtomicReference<ModelNode> deploymentResults, final CountDownLatch scanDoneLatch) {
this.deploymentOperation = deploymentOperation;
this.deploymentDoneLatch = deploymentDoneLatch;
this.deploymentResults = deploymentResults;
this.scanDoneLatch = scanDoneLatch;
}
@Override
public Future<ModelNode> deploy(final ModelNode operation, final ScheduledExecutorService scheduledExecutor) {
try {
deploymentOperation.set(operation);
final FutureTask<ModelNode> task = new FutureTask<ModelNode>(new Callable<ModelNode>() {
@Override
public ModelNode call() throws Exception {
deploymentDoneLatch.await();
return deploymentResults.get();
}
});
scheduledExecutor.submit(task);
return task;
} finally {
scanDoneLatch.countDown();
}
}
@Override
public Map<String, Boolean> getDeploymentsStatus() {
return Collections.emptyMap();
}
@Override
public void close() throws IOException {
}
}
} |
package bisq.desktop.main.portfolio.pendingtrades.steps.seller;
import bisq.desktop.components.BusyAnimation;
import bisq.desktop.components.InfoTextField;
import bisq.desktop.components.TextFieldWithCopyIcon;
import bisq.desktop.components.TitledGroupBg;
import bisq.desktop.components.indicator.TxConfidenceIndicator;
import bisq.desktop.main.overlays.popups.Popup;
import bisq.desktop.main.portfolio.pendingtrades.PendingTradesViewModel;
import bisq.desktop.main.portfolio.pendingtrades.steps.TradeStepView;
import bisq.desktop.util.DisplayUtils;
import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.Layout;
import bisq.core.locale.Res;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.PaymentAccountUtil;
import bisq.core.payment.payload.AssetsAccountPayload;
import bisq.core.payment.payload.BankAccountPayload;
import bisq.core.payment.payload.CashDepositAccountPayload;
import bisq.core.payment.payload.F2FAccountPayload;
import bisq.core.payment.payload.HalCashAccountPayload;
import bisq.core.payment.payload.MoneyGramAccountPayload;
import bisq.core.payment.payload.PaymentAccountPayload;
import bisq.core.payment.payload.PaymentMethod;
import bisq.core.payment.payload.SepaAccountPayload;
import bisq.core.payment.payload.SepaInstantAccountPayload;
import bisq.core.payment.payload.USPostalMoneyOrderAccountPayload;
import bisq.core.payment.payload.WesternUnionAccountPayload;
import bisq.core.trade.Contract;
import bisq.core.trade.Trade;
import bisq.core.trade.txproof.AssetTxProofResult;
import bisq.core.user.DontShowAgainLookup;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.util.Tuple2;
import bisq.common.util.Tuple4;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.geometry.Insets;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.Subscription;
import javafx.beans.value.ChangeListener;
import java.util.Optional;
import javax.annotation.Nullable;
import static bisq.desktop.util.FormBuilder.*;
import static com.google.common.base.Preconditions.checkNotNull;
public class SellerStep3View extends TradeStepView {
private Button confirmButton;
private Label statusLabel;
private BusyAnimation busyAnimation;
private Subscription tradeStatePropertySubscription;
private Timer timeoutTimer;
@Nullable
private InfoTextField assetTxProofResultField;
@Nullable
private TxConfidenceIndicator assetTxConfidenceIndicator;
@Nullable
private ChangeListener<Number> proofResultListener;
// Constructor, Initialisation
public SellerStep3View(PendingTradesViewModel model) {
super(model);
}
@Override
public void activate() {
super.activate();
if (timeoutTimer != null)
timeoutTimer.stop();
tradeStatePropertySubscription = EasyBind.subscribe(trade.stateProperty(), state -> {
if (timeoutTimer != null)
timeoutTimer.stop();
if (trade.isFiatSent() && !trade.isFiatReceived()) {
showPopup();
} else if (trade.isFiatReceived()) {
if (!trade.hasFailed()) {
switch (state) {
case SELLER_CONFIRMED_IN_UI_FIAT_PAYMENT_RECEIPT:
case SELLER_PUBLISHED_PAYOUT_TX:
case SELLER_SENT_PAYOUT_TX_PUBLISHED_MSG:
busyAnimation.play();
// confirmButton.setDisable(true);
statusLabel.setText(Res.get("shared.sendingConfirmation"));
timeoutTimer = UserThread.runAfter(() -> {
busyAnimation.stop();
// confirmButton.setDisable(false);
statusLabel.setText(Res.get("shared.sendingConfirmationAgain"));
}, 10);
break;
case SELLER_SAW_ARRIVED_PAYOUT_TX_PUBLISHED_MSG:
busyAnimation.stop();
statusLabel.setText(Res.get("shared.messageArrived"));
break;
case SELLER_STORED_IN_MAILBOX_PAYOUT_TX_PUBLISHED_MSG:
busyAnimation.stop();
statusLabel.setText(Res.get("shared.messageStoredInMailbox"));
break;
case SELLER_SEND_FAILED_PAYOUT_TX_PUBLISHED_MSG:
// We get a popup and the trade closed, so we dont need to show anything here
busyAnimation.stop();
// confirmButton.setDisable(false);
statusLabel.setText("");
break;
default:
log.warn("Unexpected case: State={}, tradeId={} " + state.name(), trade.getId());
busyAnimation.stop();
// confirmButton.setDisable(false);
statusLabel.setText(Res.get("shared.sendingConfirmationAgain"));
break;
}
} else {
log.warn("confirmButton gets disabled because trade contains error message {}", trade.getErrorMessage());
// confirmButton.setDisable(true);
statusLabel.setText("");
}
}
});
if (isXmrTrade()) {
proofResultListener = (observable, oldValue, newValue) -> {
applyAssetTxProofResult(trade.getAssetTxProofResult());
};
trade.getAssetTxProofResultUpdateProperty().addListener(proofResultListener);
applyAssetTxProofResult(trade.getAssetTxProofResult());
}
}
@Override
public void deactivate() {
super.deactivate();
if (tradeStatePropertySubscription != null) {
tradeStatePropertySubscription.unsubscribe();
tradeStatePropertySubscription = null;
}
busyAnimation.stop();
if (timeoutTimer != null) {
timeoutTimer.stop();
}
if (isXmrTrade()) {
trade.getAssetTxProofResultUpdateProperty().removeListener(proofResultListener);
}
}
// Content
@Override
protected void addContent() {
gridPane.getColumnConstraints().get(1).setHgrow(Priority.ALWAYS);
addTradeInfoBlock();
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 3,
Res.get("portfolio.pending.step3_seller.confirmPaymentReceipt"), Layout.COMPACT_GROUP_DISTANCE);
TextFieldWithCopyIcon field = addTopLabelTextFieldWithCopyIcon(gridPane, gridRow,
Res.get("portfolio.pending.step3_seller.amountToReceive"),
model.getFiatVolume(), Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE).second;
field.setCopyWithoutCurrencyPostFix(true);
String myPaymentDetails = "";
String peersPaymentDetails = "";
String myTitle = "";
String peersTitle = "";
boolean isBlockChain = false;
String currencyName = getCurrencyName(trade);
Contract contract = trade.getContract();
if (contract != null) {
PaymentAccountPayload myPaymentAccountPayload = contract.getSellerPaymentAccountPayload();
PaymentAccountPayload peersPaymentAccountPayload = contract.getBuyerPaymentAccountPayload();
myPaymentDetails = PaymentAccountUtil.findPaymentAccount(myPaymentAccountPayload, model.getUser())
.map(PaymentAccount::getAccountName)
.orElse("");
if (myPaymentAccountPayload instanceof AssetsAccountPayload) {
if (myPaymentDetails.isEmpty()) {
// Not expected
myPaymentDetails = ((AssetsAccountPayload) myPaymentAccountPayload).getAddress();
}
peersPaymentDetails = ((AssetsAccountPayload) peersPaymentAccountPayload).getAddress();
myTitle = Res.get("portfolio.pending.step3_seller.yourAddress", currencyName);
peersTitle = Res.get("portfolio.pending.step3_seller.buyersAddress", currencyName);
isBlockChain = true;
} else {
if (myPaymentDetails.isEmpty()) {
// Not expected
myPaymentDetails = myPaymentAccountPayload.getPaymentDetails();
}
peersPaymentDetails = peersPaymentAccountPayload.getPaymentDetails();
myTitle = Res.get("portfolio.pending.step3_seller.yourAccount");
peersTitle = Res.get("portfolio.pending.step3_seller.buyersAccount");
}
}
if (!isBlockChain && !checkNotNull(trade.getOffer()).getPaymentMethod().equals(PaymentMethod.F2F)) {
addTopLabelTextFieldWithCopyIcon(
gridPane, gridRow, 1, Res.get("shared.reasonForPayment"),
model.dataModel.getReference(), Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE);
GridPane.setRowSpan(titledGroupBg, 4);
}
if (isXmrTrade()) {
assetTxProofResultField = new InfoTextField();
Tuple2<Label, VBox> topLabelWithVBox = getTopLabelWithVBox(Res.get("portfolio.pending.step3_seller.autoConf.status.label"), assetTxProofResultField);
VBox vBox = topLabelWithVBox.second;
assetTxConfidenceIndicator = new TxConfidenceIndicator();
assetTxConfidenceIndicator.setId("xmr-confidence");
assetTxConfidenceIndicator.setProgress(0);
assetTxConfidenceIndicator.setTooltip(new Tooltip());
assetTxProofResultField.setContentForInfoPopOver(createPopoverLabel(Res.get("setting.info.msg")));
HBox.setMargin(assetTxConfidenceIndicator, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
HBox hBox = new HBox();
HBox.setHgrow(vBox, Priority.ALWAYS);
hBox.setSpacing(10);
hBox.getChildren().addAll(vBox, assetTxConfidenceIndicator);
GridPane.setRowIndex(hBox, gridRow);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(hBox);
}
TextFieldWithCopyIcon myPaymentDetailsTextField = addCompactTopLabelTextFieldWithCopyIcon(gridPane, ++gridRow,
0, myTitle, myPaymentDetails).second;
myPaymentDetailsTextField.setMouseTransparent(false);
myPaymentDetailsTextField.setTooltip(new Tooltip(myPaymentDetails));
TextFieldWithCopyIcon peersPaymentDetailsTextField = addCompactTopLabelTextFieldWithCopyIcon(gridPane, gridRow,
1, peersTitle, peersPaymentDetails).second;
peersPaymentDetailsTextField.setMouseTransparent(false);
peersPaymentDetailsTextField.setTooltip(new Tooltip(peersPaymentDetails));
String counterCurrencyTxId = trade.getCounterCurrencyTxId();
String counterCurrencyExtraData = trade.getCounterCurrencyExtraData();
if (counterCurrencyTxId != null && !counterCurrencyTxId.isEmpty() &&
counterCurrencyExtraData != null && !counterCurrencyExtraData.isEmpty()) {
TextFieldWithCopyIcon txHashTextField = addCompactTopLabelTextFieldWithCopyIcon(gridPane, ++gridRow,
0, Res.get("portfolio.pending.step3_seller.xmrTxHash"), counterCurrencyTxId).second;
txHashTextField.setMouseTransparent(false);
txHashTextField.setTooltip(new Tooltip(myPaymentDetails));
TextFieldWithCopyIcon txKeyDetailsTextField = addCompactTopLabelTextFieldWithCopyIcon(gridPane, gridRow,
1, Res.get("portfolio.pending.step3_seller.xmrTxKey"), counterCurrencyExtraData).second;
txKeyDetailsTextField.setMouseTransparent(false);
txKeyDetailsTextField.setTooltip(new Tooltip(peersPaymentDetails));
}
Tuple4<Button, BusyAnimation, Label, HBox> tuple = addButtonBusyAnimationLabelAfterGroup(gridPane, ++gridRow,
Res.get("portfolio.pending.step3_seller.confirmReceipt"));
GridPane.setColumnSpan(tuple.fourth, 2);
confirmButton = tuple.first;
confirmButton.setOnAction(e -> onPaymentReceived());
busyAnimation = tuple.second;
statusLabel = tuple.third;
}
@Override
protected void updateConfirmButtonDisableState(boolean isDisabled) {
confirmButton.setDisable(isDisabled);
}
// Info
@Override
protected String getInfoText() {
String currencyName = getCurrencyName(trade);
if (model.isBlockChainMethod()) {
return Res.get("portfolio.pending.step3_seller.buyerStartedPayment", Res.get("portfolio.pending.step3_seller.buyerStartedPayment.altcoin", currencyName));
} else {
return Res.get("portfolio.pending.step3_seller.buyerStartedPayment", Res.get("portfolio.pending.step3_seller.buyerStartedPayment.fiat", currencyName));
}
}
// Warning
@Override
protected String getFirstHalfOverWarnText() {
String substitute = model.isBlockChainMethod() ?
Res.get("portfolio.pending.step3_seller.warn.part1a", getCurrencyName(trade)) :
Res.get("portfolio.pending.step3_seller.warn.part1b");
return Res.get("portfolio.pending.step3_seller.warn.part2", substitute);
}
// Dispute
@Override
protected String getPeriodOverWarnText() {
return Res.get("portfolio.pending.step3_seller.openForDispute");
}
@Override
protected void applyOnDisputeOpened() {
}
// UI Handlers
private void onPaymentReceived() {
if (isDisputed()) {
return;
}
// The confirmPaymentReceived call will trigger the trade protocol to do the payout tx. We want to be sure that we
// are well connected to the Bitcoin network before triggering the broadcast.
if (model.dataModel.isReadyForTxBroadcast()) {
String key = "confirmPaymentReceived";
if (!DevEnv.isDevMode() && DontShowAgainLookup.showAgain(key)) {
PaymentAccountPayload paymentAccountPayload = model.dataModel.getSellersPaymentAccountPayload();
String message = Res.get("portfolio.pending.step3_seller.onPaymentReceived.part1", getCurrencyName(trade));
if (!(paymentAccountPayload instanceof AssetsAccountPayload)) {
if (!(paymentAccountPayload instanceof WesternUnionAccountPayload) &&
!(paymentAccountPayload instanceof HalCashAccountPayload) &&
!(paymentAccountPayload instanceof F2FAccountPayload)) {
message += Res.get("portfolio.pending.step3_seller.onPaymentReceived.fiat", trade.getShortId());
}
Optional<String> optionalHolderName = getOptionalHolderName();
if (optionalHolderName.isPresent()) {
message += Res.get("portfolio.pending.step3_seller.onPaymentReceived.name", optionalHolderName.get());
}
}
message += Res.get("portfolio.pending.step3_seller.onPaymentReceived.note");
if (model.dataModel.isSignWitnessTrade()) {
message += Res.get("portfolio.pending.step3_seller.onPaymentReceived.signer");
}
new Popup()
.headLine(Res.get("portfolio.pending.step3_seller.onPaymentReceived.confirm.headline"))
.confirmation(message)
.width(700)
.actionButtonText(Res.get("portfolio.pending.step3_seller.onPaymentReceived.confirm.yes"))
.onAction(this::confirmPaymentReceived)
.closeButtonText(Res.get("shared.cancel"))
.show();
} else {
confirmPaymentReceived();
}
}
}
private void showPopup() {
PaymentAccountPayload paymentAccountPayload = model.dataModel.getSellersPaymentAccountPayload();
String key = "confirmPayment" + trade.getId();
String message = "";
String tradeVolumeWithCode = DisplayUtils.formatVolumeWithCode(trade.getTradeVolume());
String currencyName = getCurrencyName(trade);
String part1 = Res.get("portfolio.pending.step3_seller.part", currencyName);
String id = trade.getShortId();
if (paymentAccountPayload instanceof AssetsAccountPayload) {
String address = ((AssetsAccountPayload) paymentAccountPayload).getAddress();
String explorerOrWalletString = isXmrTrade() ?
Res.get("portfolio.pending.step3_seller.altcoin.wallet", currencyName) :
Res.get("portfolio.pending.step3_seller.altcoin.explorer", currencyName);
message = Res.get("portfolio.pending.step3_seller.altcoin", part1, explorerOrWalletString, address, tradeVolumeWithCode, currencyName);
} else {
if (paymentAccountPayload instanceof USPostalMoneyOrderAccountPayload) {
message = Res.get("portfolio.pending.step3_seller.postal", part1, tradeVolumeWithCode, id);
} else if (!(paymentAccountPayload instanceof WesternUnionAccountPayload) &&
!(paymentAccountPayload instanceof HalCashAccountPayload) &&
!(paymentAccountPayload instanceof F2FAccountPayload)) {
message = Res.get("portfolio.pending.step3_seller.bank", currencyName, tradeVolumeWithCode, id);
}
String part = Res.get("portfolio.pending.step3_seller.openDispute");
if (paymentAccountPayload instanceof CashDepositAccountPayload)
message = message + Res.get("portfolio.pending.step3_seller.cash", part);
else if (paymentAccountPayload instanceof WesternUnionAccountPayload)
message = message + Res.get("portfolio.pending.step3_seller.westernUnion");
else if (paymentAccountPayload instanceof MoneyGramAccountPayload)
message = message + Res.get("portfolio.pending.step3_seller.moneyGram");
else if (paymentAccountPayload instanceof HalCashAccountPayload)
message = message + Res.get("portfolio.pending.step3_seller.halCash");
else if (paymentAccountPayload instanceof F2FAccountPayload)
message = part1;
Optional<String> optionalHolderName = getOptionalHolderName();
if (optionalHolderName.isPresent()) {
message += Res.get("portfolio.pending.step3_seller.bankCheck", optionalHolderName.get(), part);
}
if (model.dataModel.isSignWitnessTrade()) {
message += Res.get("portfolio.pending.step3_seller.onPaymentReceived.signer");
}
}
if (!DevEnv.isDevMode() && DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup().headLine(Res.get("popup.attention.forTradeWithId", id))
.attention(message)
.show();
}
}
private void confirmPaymentReceived() {
log.info("User pressed the [Confirm payment receipt] button for Trade {}", trade.getShortId());
busyAnimation.play();
statusLabel.setText(Res.get("shared.sendingConfirmation"));
if (!trade.isPayoutPublished())
trade.setState(Trade.State.SELLER_CONFIRMED_IN_UI_FIAT_PAYMENT_RECEIPT);
model.dataModel.onFiatPaymentReceived(() -> {
// In case the first send failed we got the support button displayed.
// If it succeeds at a second try we remove the support button again.
//TODO check for support. in case of a dispute we dont want to hide the button
//if (notificationGroup != null)
// notificationGroup.setButtonVisible(false);
}, errorMessage -> {
// confirmButton.setDisable(false);
busyAnimation.stop();
new Popup().warning(Res.get("popup.warning.sendMsgFailed")).show();
});
}
private Optional<String> getOptionalHolderName() {
Contract contract = trade.getContract();
if (contract != null) {
PaymentAccountPayload paymentAccountPayload = contract.getBuyerPaymentAccountPayload();
if (paymentAccountPayload instanceof BankAccountPayload)
return Optional.of(((BankAccountPayload) paymentAccountPayload).getHolderName());
else if (paymentAccountPayload instanceof SepaAccountPayload)
return Optional.of(((SepaAccountPayload) paymentAccountPayload).getHolderName());
else if (paymentAccountPayload instanceof SepaInstantAccountPayload)
return Optional.of(((SepaInstantAccountPayload) paymentAccountPayload).getHolderName());
else
return Optional.empty();
} else {
return Optional.empty();
}
}
private void applyAssetTxProofResult(@Nullable AssetTxProofResult result) {
checkNotNull(assetTxProofResultField);
checkNotNull(assetTxConfidenceIndicator);
String txt = GUIUtil.getProofResultAsString(result);
assetTxProofResultField.setText(txt);
if (result == null) {
assetTxConfidenceIndicator.setProgress(0);
return;
}
switch (result) {
case PENDING:
case COMPLETED:
if (result.getNumRequiredConfirmations() > 0) {
int numRequiredConfirmations = result.getNumRequiredConfirmations();
int numConfirmations = result.getNumConfirmations();
if (numConfirmations == 0) {
assetTxConfidenceIndicator.setProgress(-1);
} else {
double progress = Math.min(1, (double) numConfirmations / (double) numRequiredConfirmations);
assetTxConfidenceIndicator.setProgress(progress);
assetTxConfidenceIndicator.getTooltip().setText(
Res.get("portfolio.pending.autoConf.blocks",
numConfirmations, numRequiredConfirmations));
}
}
break;
default:
// Set invisible by default
assetTxConfidenceIndicator.setProgress(0);
break;
}
}
private Label createPopoverLabel(String text) {
Label label = new Label(text);
label.setPrefWidth(600);
label.setWrapText(true);
label.setPadding(new Insets(10));
return label;
}
} |
package hu.elte.txtuml.export.cpp.structural;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.Region;
import org.eclipse.uml2.uml.StateMachine;
import org.eclipse.uml2.uml.UMLPackage;
import hu.elte.txtuml.export.cpp.CppExporterUtils;
import hu.elte.txtuml.export.cpp.statemachine.StateMachineExporter;
import hu.elte.txtuml.export.cpp.templates.GenerationNames;
import hu.elte.txtuml.export.cpp.templates.GenerationTemplates;
import hu.elte.txtuml.export.cpp.templates.PrivateFunctionalTemplates;
import hu.elte.txtuml.export.cpp.templates.RuntimeTemplates;
import hu.elte.txtuml.export.cpp.templates.statemachine.EventTemplates;
import hu.elte.txtuml.export.cpp.templates.structual.ConstructorTemplates;
import hu.elte.txtuml.export.cpp.templates.structual.HeaderTemplates;
import hu.elte.txtuml.export.cpp.templates.structual.HeaderTemplates.HeaderInfo;
import hu.elte.txtuml.export.cpp.templates.structual.LinkTemplates;
import hu.elte.txtuml.utils.Pair;
public class ClassExporter extends StructuredElementExporter<Class> {
private List<String> additionalSourcesNames;
private List<String> baseClasses;
private List<String> interfacesToImplement;
private AssociationExporter associationExporter;
private ConstructorExporter constructorExporter;
private StateMachineExporter stateMachineExporter;
private PortExporter portExporter;
private String abstractInterface;
private int poolId;
public ClassExporter(Class structuredElement, String name, String sourceDestination) {
super(structuredElement, name, sourceDestination);
super.init();
baseClasses = new LinkedList<String>();
interfacesToImplement = new LinkedList<String>();
constructorExporter = new ConstructorExporter(structuredElement.getOwnedOperations(), super.activityExporter);
associationExporter = new AssociationExporter(structuredElement.getOwnedAttributes());
additionalSourcesNames = new ArrayList<String>();
baseClasses.clear();
interfacesToImplement.clear();
portExporter = new PortExporter();
StateMachine classSM = CppExporterUtils.getStateMachine(structuredElement);
if (classSM != null) {
stateMachineExporter = new StateMachineExporter(classSM, this, poolId);
}
}
public List<String> getAdditionalSources() {
return additionalSourcesNames;
}
public void setPoolId(int poolId) {
this.poolId = poolId;
}
public List<String> getSubmachines() {
assert(stateMachineExporter != null);
if(stateMachineExporter != null) {
return stateMachineExporter.getAllSubmachineName();
} else {
return Collections.emptyList();
}
}
public void setAbstractInterface(String abstractInterface) {
this.abstractInterface = abstractInterface;
}
public void removeAbstractInterface() {
this.abstractInterface = null;
}
private void collectModelBaseClasses() {
for (Generalization base : structuredElement.getGeneralizations()) {
baseClasses.add(base.getGeneral().getName());
}
if (abstractInterface != null && !baseClasses.contains(abstractInterface)) {
interfacesToImplement.add(abstractInterface);
}
}
@Override
public String getUnitNamespace() {
return GenerationNames.Namespaces.ModelNamespace;
}
@Override
public void createAddtionoalSources() throws FileNotFoundException, UnsupportedEncodingException {
if(CppExporterUtils.isStateMachineOwner(structuredElement)) {
stateMachineExporter.createSubMachineSources(getDesniation());
}
}
@Override
public String createUnitCppCode() {
StringBuilder source = new StringBuilder("");
List<StateMachine> smList = new ArrayList<StateMachine>();
CppExporterUtils.getTypedElements(smList, UMLPackage.Literals.STATE_MACHINE,
structuredElement.allOwnedElements());
if (CppExporterUtils.isStateMachineOwner(structuredElement)) {
source.append(stateMachineExporter.createStateMachineRelatedCppSourceCodes());
}
source.append(super.createOperationDefinitions());
source.append(constructorExporter.exportConstructorsDefinitions(name, CppExporterUtils.isStateMachineOwner(structuredElement)));
source.append(CppExporterUtils.isStateMachineOwner(structuredElement) ? ConstructorTemplates.destructorDef(name, true)
: ConstructorTemplates.destructorDef(name, false));
return source.toString();
}
@Override
public String createUnitHeaderCode() {
String source = "";
StringBuilder privateParts = new StringBuilder(
super.createPrivateAttrbutes() + super.createPrivateOperationsDeclarations());
StringBuilder protectedParts = new StringBuilder(
super.createProtectedAttributes() + super.createProtectedOperationsDeclarations());
StringBuilder publicParts = new StringBuilder(
super.createPublicAttributes() + super.createPublicOperationDeclarations());
publicParts.append(constructorExporter.exportConstructorDeclarations(name));
publicParts.append(ConstructorTemplates.destructorDecl(name));
publicParts.append("\n" + associationExporter.createAssociationMemberDeclarationsCode());
publicParts.append(LinkTemplates.templateLinkFunctionGeneralDef(LinkTemplates.LinkFunctionType.Link));
publicParts.append(LinkTemplates.templateLinkFunctionGeneralDef(LinkTemplates.LinkFunctionType.Unlink));
publicParts.append(portExporter.createPortEnumCode(structuredElement.getOwnedPorts()));
collectModelBaseClasses();
if (CppExporterUtils.isStateMachineOwner(structuredElement)) {
publicParts.append(stateMachineExporter.createStateEnumCode());
privateParts.append(stateMachineExporter.createStateMachineRelatedHeadedDeclarationCodes());
HeaderInfo stateMachineHeaderInfo = new HeaderInfo(name,
new HeaderTemplates.StateMachineClassHeaderType(stateMachineExporter.ownSubMachine() ?
Optional.of(getSubmachines()) : Optional.empty()));
source = HeaderTemplates
.classHeader("", baseClasses, interfacesToImplement,
publicParts.toString(), protectedParts.toString(), privateParts.toString(),
stateMachineHeaderInfo
);
dependencyExporter.addHeaderOnlyIncludeDependencies(stateMachineHeaderInfo.getRelatedBaseClassInclude());
} else {
HeaderInfo simpleClassHeaderInfo = new HeaderInfo(name, new HeaderTemplates.SimpleClassHeaderType());
source = HeaderTemplates
.classHeader("", baseClasses, interfacesToImplement, publicParts.toString(),
protectedParts.toString(), privateParts.toString(),
simpleClassHeaderInfo);
dependencyExporter.addHeaderOnlyIncludeDependencies(simpleClassHeaderInfo.getRelatedBaseClassInclude());
}
String externalDeclerations = associationExporter.createLinkFunctionDeclarations(name);
return source + externalDeclerations;
}
@Override
public String getUnitDependencies(UnitType type) {
StringBuilder source = new StringBuilder("");
dependencyExporter.addDependencies(associationExporter.getAssociatedPropertyTypes());
for (String baseClassName : baseClasses) {
source.append(PrivateFunctionalTemplates.include(baseClassName));
}
for (String pureInterfaceName : interfacesToImplement) {
source.append(PrivateFunctionalTemplates.include(pureInterfaceName));
}
if (CppExporterUtils.isStateMachineOwner(structuredElement)) {
for (Map.Entry<String, Pair<String, Region>> entry : stateMachineExporter.getSubMachineMap().entrySet()) {
dependencyExporter.addDependency(entry.getValue().getFirst());
}
dependencyExporter.addHeaderOnlyDependencies(stateMachineExporter.getAllSubmachineName());
}
if (type == UnitType.Cpp) {
source.append(dependencyExporter.createDependencyCppIncludeCode(name));
if (CppExporterUtils.isStateMachineOwner(structuredElement)) {
source.append(PrivateFunctionalTemplates.include(GenerationTemplates.DeploymentHeader));
source.append(GenerationTemplates.debugOnlyCodeBlock(GenerationTemplates.StandardIOinclude));
}
source.append(PrivateFunctionalTemplates.include(EventTemplates.EventHeaderName));
if (associationExporter.ownAssociation()) {
source.append(PrivateFunctionalTemplates.include(LinkTemplates.AssociationsStructuresHreaderName));
}
// TODO analyze what dependency is necessary..
source.append(PrivateFunctionalTemplates.include(GenerationNames.FileNames.ActionPath));
source.append(PrivateFunctionalTemplates.include(GenerationNames.FileNames.StringUtilsPath));
source.append(PrivateFunctionalTemplates.include(GenerationNames.FileNames.CollectionUtilsPath));
} else if(type == UnitType.Header) {
dependencyExporter.addHeaderOnlyIncludeDependency(GenerationNames.FileNames.TypesFilePath);
if (associationExporter.ownAssociation()) {
dependencyExporter.addHeaderOnlyIncludeDependency(RuntimeTemplates.RTPath + LinkTemplates.AssocationHeader);
dependencyExporter.addHeaderOnlyIncludeDependency(LinkTemplates.AssociationsStructuresHreaderName);
}
source.append(dependencyExporter.createDependencyHeaderIncludeCode(GenerationNames.Namespaces.ModelNamespace));
}
source.append("\n");
return source.toString();
}
} |
package consulo.dotnet.debugger.nodes.logicView;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.xdebugger.frame.XValueChildrenList;
import consulo.dotnet.debugger.DotNetDebugContext;
import consulo.dotnet.debugger.DotNetDebuggerSearchUtil;
import consulo.dotnet.debugger.nodes.DotNetAbstractVariableMirrorNode;
import consulo.dotnet.debugger.nodes.DotNetDebuggerCompilerGenerateUtil;
import consulo.dotnet.debugger.nodes.DotNetFieldOrPropertyMirrorNode;
import consulo.dotnet.debugger.nodes.DotNetStructValueInfo;
import consulo.dotnet.debugger.nodes.DotNetThisAsObjectValueMirrorNode;
import consulo.dotnet.debugger.proxy.DotNetFieldOrPropertyProxy;
import consulo.dotnet.debugger.proxy.DotNetPropertyProxy;
import consulo.dotnet.debugger.proxy.DotNetThreadProxy;
import consulo.dotnet.debugger.proxy.DotNetTypeProxy;
import consulo.dotnet.debugger.proxy.value.DotNetObjectValueProxy;
import consulo.dotnet.debugger.proxy.value.DotNetStructValueProxy;
import consulo.dotnet.debugger.proxy.value.DotNetValueProxy;
/**
* @author VISTALL
* @since 20.09.14
*/
public class DefaultDotNetLogicValueView extends BaseDotNetLogicView
{
@Override
public boolean canHandle(@NotNull DotNetDebugContext debugContext, @NotNull DotNetTypeProxy typeMirror)
{
return true;
}
@Override
public void computeChildrenImpl(@NotNull DotNetDebugContext debugContext,
@NotNull DotNetAbstractVariableMirrorNode parentNode,
@NotNull DotNetThreadProxy threadMirror,
@Nullable DotNetValueProxy value,
@NotNull XValueChildrenList childrenList)
{
if(value instanceof DotNetObjectValueProxy)
{
DotNetTypeProxy type = value.getType();
assert type != null;
DotNetThisAsObjectValueMirrorNode.addStaticNode(childrenList, debugContext, threadMirror, type);
DotNetFieldOrPropertyProxy[] mirrors = DotNetDebuggerSearchUtil.getFieldAndProperties(type, true);
for(DotNetFieldOrPropertyProxy fieldOrPropertyProxy : mirrors)
{
if(needSkip(fieldOrPropertyProxy))
{
continue;
}
childrenList.add(new DotNetFieldOrPropertyMirrorNode(debugContext, fieldOrPropertyProxy, threadMirror, (DotNetObjectValueProxy) value));
}
}
else if(value instanceof DotNetStructValueProxy)
{
Map<DotNetFieldOrPropertyProxy, DotNetValueProxy> fields = ((DotNetStructValueProxy) value).getValues();
for(Map.Entry<DotNetFieldOrPropertyProxy, DotNetValueProxy> entry : fields.entrySet())
{
DotNetFieldOrPropertyProxy fieldMirror = entry.getKey();
DotNetValueProxy fieldValue = entry.getValue();
DotNetStructValueInfo valueInfo = new DotNetStructValueInfo((DotNetStructValueProxy) value, parentNode, fieldMirror, fieldValue);
childrenList.add(new DotNetFieldOrPropertyMirrorNode(debugContext, fieldMirror, threadMirror, null, valueInfo));
}
}
}
private static boolean needSkip(DotNetFieldOrPropertyProxy fieldOrPropertyProxy)
{
if(fieldOrPropertyProxy.isStatic())
{
return true;
}
if(DotNetDebuggerCompilerGenerateUtil.needSkipVariableByName(fieldOrPropertyProxy.getName()))
{
return true;
}
if(fieldOrPropertyProxy instanceof DotNetPropertyProxy)
{
if(((DotNetPropertyProxy) fieldOrPropertyProxy).isArrayProperty())
{
return true;
}
}
return false;
}
} |
package edu.wpi.first.wpilib.plugins.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import edu.wpi.first.wpilib.plugins.core.ant.AntPropertiesParser;
import edu.wpi.first.wpilib.plugins.core.installer.ToolsInstaller;
import edu.wpi.first.wpilib.plugins.core.preferences.PreferenceConstants;
/**
* The activator class controls the plug-in life cycle
*/
public class WPILibCore extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "edu.wpi.first.wpilib.plugins.core"; //$NON-NLS-1$
// The shared instance
private static WPILibCore plugin;
/**
* The constructor
*/
public WPILibCore() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
new ToolsInstaller(getDefaultVersion()).installIfNecessary();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static WPILibCore getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public Properties getProjectProperties(IProject project) {
List<InputStream> streams = new ArrayList<InputStream>();
try {
if (project != null) {
try {
streams.add(project.getFile("build.properties")
.getContents());
} catch (CoreException e) {
} // No properties file
}
File file = new File(getWPILibBaseDir() + "/wpilib.properties");
streams.add(new FileInputStream(file));
return new AntPropertiesParser(streams).getProperties();
} catch (Exception e) {
WPILibCore.logError("Error loading project properties.", e);
return new Properties();
}
}
public void saveGlobalProperties(Properties props) {
try {
props.store(new FileOutputStream(new File(WPILibCore.getDefault()
.getWPILibBaseDir() + "/wpilib.properties")),
"Don't add new properties, they will be deleted by the eclipse plugin.");
} catch (IOException e) {
WPILibCore.logError("Error saving global properties.", e);
}
}
public int getTeamNumber(IProject project) {
return Integer.parseInt(getProjectProperties(project).getProperty(
"team-number", "0"));
}
public String getTargetIP(IProject project) {
String target = getProjectProperties(project).getProperty("target");
if (target != null)
return target;
else {
int teamNumber = getTeamNumber(project);
return "roborio-" + teamNumber + ".local";
}
}
public String getWPILibBaseDir() {
return System.getProperty("user.home") + "/wpilib";
}
public String getDefaultVersion() {
return "2013-test-0.4";
}
public String getCurrentVersion() {
return getPreferenceStore()
.getString(PreferenceConstants.TOOLS_VERSION);
}
public static void logInfo(String msg) {
getDefault().getLog().log(new Status(Status.INFO, PLUGIN_ID, Status.OK, msg, null));
}
public static void logError(String msg, Exception e) {
getDefault().getLog().log(new Status(Status.ERROR, PLUGIN_ID, Status.OK, msg, e));
}
} |
package org.jboss.as.ejb3.component.stateful;
import java.lang.reflect.Method;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.as.ejb3.component.interceptors.SessionBeanHomeInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* Interceptor factory for SFSB's that invokes the ejbCreate method. This interceptor
* is only used when a component is created via a home interface method.
*
* @author Stuart Douglas
*/
public class StatefulInitMethodInterceptorFactory implements InterceptorFactory {
public static final InterceptorFactory INSTANCE = new StatefulInitMethodInterceptorFactory();
private StatefulInitMethodInterceptorFactory() {
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
final Method method = SessionBeanHomeInterceptorFactory.INIT_METHOD.get();
final Object[] params = SessionBeanHomeInterceptorFactory.INIT_PARAMETERS.get();
//we remove them immediatly, so they are not set for the rest of the invocation
//TODO: find a better way to handle this
SessionBeanHomeInterceptorFactory.INIT_METHOD.remove();
SessionBeanHomeInterceptorFactory.INIT_PARAMETERS.remove();
return new AbstractEJBInterceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (method != null) {
method.invoke(context.getTarget(), params);
}
return context.proceed();
}
};
}
} |
package org.eclipse.birt.report.engine.api;
import java.io.File;
/**
* Defines various constants that engine host may need to use
*/
public class EngineConstants {
public final static String APPCONTEXT_HTML_RENDER_CONTEXT = "HTML_RENDER_CONTEXT"; //$NON-NLS-1$
public final static String APPCONTEXT_PDF_RENDER_CONTEXT = "PDF_RENDER_CONTEXT"; //$NON-NLS-1$
public final static String APPCONTEXT_DATASET_CACHE_OPTION = "DATASET_CACHE_OPTION"; //$NON-NLS-1$
public final static String APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST = "BIRT_VIEWER_HTTPSERVET_REQUEST"; //$NON-NLS-1$
public final static String APPCONTEXT_CLASSLOADER_KEY = "PARENT_CLASSLOADER"; //$NON-NLS-1$
//chart and html will all use APPCONTEXT_CHART_RESOLUTION
public final static String APPCONTEXT_CHART_RESOLUTION = "CHART_RESOLUTION"; //$NON-NLS-1$//false
/**
* @deprecated use APPCONTEXT_CHART_RESOLUTION instead of APPCONTEXT_CHART_PRINT_RESOLUTION
*/
public final static String APPCONTEXT_CHART_PRINT_RESOLUTION = APPCONTEXT_CHART_RESOLUTION;
/**
* This property is a key for putting max row number of extended item in app
* context or global variables.
*/
public final static String PROPERTY_EXTENDED_ITEM_MAX_ROW = "EXTENDED_ITEM_MAX_ROW"; //$NON-NLS-1$
/**
* This property is a key for putting max variable size of extended item in app
* context or global variables.
*/
public final static String PROPERTY_EXTENDED_ITEM_MAX_VARIABLE_SIZE = "EXTENDED_ITEM_MAX_VARIABLE_SIZE"; //$NON-NLS-1$
//used by ScriptExecutor
public static final String PROPERTYSEPARATOR = File.pathSeparator;
public static final String WEBAPP_CLASSPATH_KEY = "webapplication.projectclasspath"; //$NON-NLS-1$
public static final String WORKSPACE_CLASSPATH_KEY = "workspace.projectclasspath"; //$NON-NLS-1$
public static final String PROJECT_CLASSPATH_KEY = "user.projectclasspath"; //$NON-NLS-1$
public static final String USER_ACL_KEY = "USER_ACL";
} |
package org.estatio.capex.dom.state;
import java.util.List;
import javax.inject.Inject;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.services.eventbus.EventBusService;
import org.apache.isis.applib.services.metamodel.MetaModelService3;
import org.apache.isis.applib.services.queryresultscache.QueryResultsCache;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.repository.RepositoryService;
import org.estatio.capex.dom.task.Task;
import org.estatio.dom.party.Person;
import org.estatio.dom.party.role.IPartyRoleType;
import org.estatio.dom.party.role.PartyRoleType;
import org.estatio.dom.party.role.PartyRoleTypeRepository;
import org.estatio.dom.party.role.PartyRoleTypeService;
@DomainService(nature = NatureOfService.DOMAIN)
public class StateTransitionService {
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
>
ST findFor(final Task task) {
return queryResultsCache.execute(
() -> doFindFor(task),
StateTransitionService.class,
"find", task);
}
/**
* factored out so can be cached.
*/
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST doFindFor(final Task task) {
StateTransitionServiceSupport supportService = supportFor(task.getTransitionObjectType());
return (ST) supportService.findFor(task);
}
/**
* Obtain the current state of the domain object, which will be the
* {@link StateTransition#getFromState() from state} of the {@link StateTransition} not yet completed (ie with a
* {@link StateTransition#getToState() to state} is null.
*
* <p>
* If there is no {@link StateTransition}, then should default to null (indicating that the domain object has only just been instantiated).
* </p>
*
* @param domainObject - upon which
* @param prototype - to specify which {@link StateTransitionType transition type} we are interested in.
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> S currentStateOf(
final DO domainObject,
final STT prototype) {
final StateTransitionServiceSupport<DO, ST, STT, S> supportService = supportFor(prototype);
return supportService.currentStateOf(domainObject);
}
/**
* Overload of {@link #currentStateOf(Object, StateTransitionType)}, but using the class of the
* {@link StateTransition} rather than a prototype value of the {@link StateTransitionType}.
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> S currentStateOf(
final DO domainObject,
final Class<ST> stateTransitionClass) {
if(domainObject instanceof Stateful) {
Stateful stateful = (Stateful) domainObject;
S currentStateIfKnown = stateful.getStateOf(stateTransitionClass);
if(currentStateIfKnown != null) {
return currentStateIfKnown;
}
}
final StateTransitionServiceSupport<DO, ST, STT, S> supportService = supportFor(stateTransitionClass);
return supportService.currentStateOf(domainObject);
}
/**
* Obtain the pending (incomplete) transition of the domain object, which will be the
* {@link StateTransition#getFromState() from state} of the {@link StateTransition} not yet completed (ie with a
* {@link StateTransition#getToState() to state} is null.
*
* @return the current transition, or possibly null for the very first (INSTANTIATE) transition
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST pendingTransitionOf(
final DO domainObject,
final STT prototype) {
final StateTransitionServiceSupport<DO, ST, STT, S> supportService = supportFor(prototype);
return supportService.pendingTransitionOf(domainObject);
}
/**
* Overload of {@link #pendingTransitionOf(Object, StateTransitionType)}, but using the class of the
* {@link StateTransition} rather than a prototype value of the {@link StateTransitionType}.
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST pendingTransitionOf(
final DO domainObject,
final Class<ST> stateTransitionClass) {
final StateTransitionServiceSupport<DO, ST, STT, S> supportService = supportFor(stateTransitionClass);
return supportService.pendingTransitionOf(domainObject);
}
/**
* Applies the state transition to the domain object that it refers to, marks the transition as
* {@link StateTransition#getCompletedOn() complete} and for {@link StateTransition#getTask() corresponding}
* {@link Task} (if there is one), also marks it as {@link Task#getCompletedBy()} complete}.
* If there are further available {@link StateTransition}s, then one is created (again, with a corresponding
* {@link Task} if required).
*
* <p>
* If the state transition does not apply to the current state of the referred domain object, or
* if the state transition's corresponding task is already complete, then does nothing and returns null.
* </p>
*
* @param stateTransition - expected to for a task still incomplete, and applicable to its domain object's state
* @return - the next state transition, or null if there isn't one defined by the transition just completing/ed
*/
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST checkState(final ST stateTransition) {
if(stateTransition.getTask().isCompleted()) {
return null;
}
final DO domainObject = stateTransition.getDomainObject();
final STT transitionType = stateTransition.getTransitionType();
Class<ST> stClass = transitionClassFor(transitionType);
return trigger(domainObject, stClass, null, null);
}
/**
* Apply the transition to the domain object and, if supported, create a {@link Task} for the <i>next</i> transition after that
*
* @param domainObject - the domain object whose
* @param requiredTransitionType - the type of transition being applied (but can be null for very first time)
* @param comment
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST trigger(
final DO domainObject,
final STT requiredTransitionType,
final String comment) {
final Class<ST> stateTransitionClass = transitionClassFor(requiredTransitionType);
return trigger(domainObject, stateTransitionClass, requiredTransitionType, comment);
}
/**
* Apply the transition to the domain object and, if supported, create a {@link Task} for the <i>next</i> transition after that.
*
* @param domainObject - the domain object whose
* @param stateTransitionClass - identifies the state chart being applied
* @param requiredTransitionTypeIfAny
* @param comment
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST trigger(
final DO domainObject,
final Class<ST> stateTransitionClass,
final STT requiredTransitionTypeIfAny,
final String comment) {
return trigger(domainObject, stateTransitionClass, requiredTransitionTypeIfAny, null, comment);
}
/**
* Apply the transition to the domain object and, if supported, create a {@link Task} for the <i>next</i> transition after that.
*
* @param domainObject - the domain object whose
* @param stateTransitionClass - identifies the state chart being applied
* @param requiredTransitionTypeIfAny
* @param comment
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST trigger(
final DO domainObject,
final Class<ST> stateTransitionClass,
final STT requiredTransitionTypeIfAny,
final Person personToAssignNextToIfAny,
final String comment) {
ST completedTransition = completeTransitionIfPossible(
domainObject, stateTransitionClass, requiredTransitionTypeIfAny,
null, comment);
boolean keepTransitioning = (completedTransition != null);
while(keepTransitioning) {
ST previousTransition = completedTransition;
completedTransition = completeTransitionIfPossible(
domainObject, stateTransitionClass, null, personToAssignNextToIfAny, null);
keepTransitioning = (completedTransition != null && previousTransition != completedTransition);
}
return mostRecentlyCompletedTransitionOf(domainObject, stateTransitionClass);
}
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST completeTransitionIfPossible(
final DO domainObject,
final Class<ST> stateTransitionClass,
final STT requestedTransitionTypeIfAny,
final Person personToAssignNextToIfAny,
final String comment) {
// check the override, if any
if(requestedTransitionTypeIfAny != null) {
boolean canTransition = requestedTransitionTypeIfAny.canTransitionFromCurrentStateAndIsMatch(domainObject,
serviceRegistry2
);
if(!canTransition) {
// what's been requested is a no-go.
return null;
}
}
// determine what previously was determined as the pending (if any)
ST pendingTransitionIfAny = pendingTransitionOf(domainObject, stateTransitionClass);
// what we now think as the pending (if any)
STT nextTransitionType = null;
// current state
final ST mostRecentTransitionIfAny = mostRecentlyCompletedTransitionOf(domainObject, stateTransitionClass);
final S currentStateIfAny =
mostRecentTransitionIfAny != null
? mostRecentTransitionIfAny.getTransitionType().getToState()
: null;
if (requestedTransitionTypeIfAny != null) {
nextTransitionType = requestedTransitionTypeIfAny;
} else {
if (mostRecentTransitionIfAny != null) {
// use most recent transition to determine the next transition (since one hasn't been requested)
final STT mostRecentTransitionType = mostRecentTransitionIfAny.getTransitionType();
final NextTransitionSearchStrategy<DO, ST, STT, S> transitionStrategy =
mostRecentTransitionType.getNextTransitionSearchStrategy();
if(transitionStrategy != null) {
nextTransitionType =
transitionStrategy.nextTransitionType(domainObject, mostRecentTransitionType,
serviceRegistry2
);
}
} else {
// can't proceed because unable to determine current state, and no transition specified
return null;
}
}
// if pending has changed, then reconcile
STT pendingTransitionType = pendingTransitionIfAny != null ? pendingTransitionIfAny.getTransitionType() : null;
if(pendingTransitionType != nextTransitionType) {
if(pendingTransitionType != null) {
if(nextTransitionType != null) {
final Task taskIfAny = pendingTransitionIfAny.getTask();
repositoryService.remove(pendingTransitionIfAny);
if(taskIfAny != null) {
repositoryService.removeAndFlush(taskIfAny);
}
pendingTransitionType = nextTransitionType;
pendingTransitionIfAny = createPendingTransition(
domainObject, currentStateIfAny, nextTransitionType,
personToAssignNextToIfAny);
} else {
// in this branch the transition strategy for the most recently completed transition
// must have returned null for nextTransitionType, and yet a pending transition does exist
// (pendingTransitionType is not null). This can only have come about if that pending
// transition was created directly (using createPendingTransition(...)).
// We don't want to discard this pending transition, so we use instead update nextTransitionType
// to this existing pending value.
nextTransitionType = pendingTransitionType;
}
} else {
// pendingTransitionType == null, so nextTransitionType != null because of outer if
pendingTransitionIfAny = createPendingTransition(
domainObject, currentStateIfAny, nextTransitionType,
personToAssignNextToIfAny);
pendingTransitionType = nextTransitionType;
}
}
if(pendingTransitionType == null) {
return null;
}
if(domainObject instanceof Stateful) {
final Stateful stateful = (Stateful) domainObject;
final S currentStateAccordingToDomainObject = stateful.getStateOf(stateTransitionClass);
if(currentStateAccordingToDomainObject == null && mostRecentTransitionIfAny != null) {
// self-healing
stateful.setStateOf(stateTransitionClass, mostRecentTransitionIfAny.getToState());
}
}
final Task taskIfAny = pendingTransitionIfAny.getTask();
if(taskIfAny != null) {
final PartyRoleType roleAssignedTo = taskIfAny.getAssignedTo();
final IPartyRoleType iRoleShouldBeAssignedTo = pendingTransitionType.getTaskAssignmentStrategy()
.getAssignTo(domainObject, serviceRegistry2);
// always overwrite the role
final PartyRoleType roleShouldBeAssignedTo = partyRoleTypeRepository.findOrCreate(roleAssignedTo);
if(roleAssignedTo != roleShouldBeAssignedTo) {
taskIfAny.setAssignedTo(roleShouldBeAssignedTo);
}
// only overwrite the person if not actually assigned
final Person personAssignedToIfAny = taskIfAny.getPersonAssignedTo();
if(personAssignedToIfAny == null) {
if(iRoleShouldBeAssignedTo != null) {
Person person = partyRoleTypeService.firstMemberOf(iRoleShouldBeAssignedTo, domainObject);
taskIfAny.setPersonAssignedTo(person);
}
}
}
if(! pendingTransitionType.isGuardSatisified(domainObject, serviceRegistry2) ) {
// cannot apply this state, while there is an available "road" to traverse, it is blocked
// (there must be a guard prohibiting it for this particular domain object)
return null;
}
if(nextTransitionType.advancePolicyFor(domainObject, serviceRegistry2).isManual() &&
requestedTransitionTypeIfAny == null) {
// do not proceed if this is an explicit transition and no explicit transition type provided.
return null;
}
// guard satisfied, so go ahead and complete this pending transition
final ST completedTransition = completeTransition(
domainObject, pendingTransitionIfAny, comment);
return completedTransition;
}
/**
* Has public visibility only so can be used in tests.
*/
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
>
ST createPendingTransition(
final DO domainObject,
final S currentState,
final STT transitionType,
final Person personToAssignToIfAny) {
final TaskAssignmentStrategy<DO, ST, STT, S> taskAssignmentStrategy =
transitionType.getTaskAssignmentStrategy();
IPartyRoleType assignToIfAny = null;
if(taskAssignmentStrategy != null) {
assignToIfAny = taskAssignmentStrategy.getAssignTo(domainObject, serviceRegistry2);
}
return transitionType
.createTransition(domainObject, currentState, assignToIfAny, personToAssignToIfAny, serviceRegistry2);
}
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST completeTransition(
final DO domainObject,
final ST transitionToComplete,
final String comment) {
final STT transitionType = transitionToComplete.getTransitionType();
final StateTransitionEvent<DO, ST, STT, S> event =
transitionType.newStateTransitionEvent(domainObject, transitionToComplete);
// transitioning
event.setPhase(StateTransitionEvent.Phase.TRANSITIONING);
eventBusService.post(event);
// transition
final Class<ST> stateTransitionClass = transitionClassFor(transitionType);
transitionType.applyTo(domainObject, stateTransitionClass, serviceRegistry2);
// mark tasks as complete
transitionToComplete.completed();
final Task taskIfAny = transitionToComplete.getTask();
if(taskIfAny != null) {
taskIfAny.completed(comment);
}
event.setPhase(StateTransitionEvent.Phase.TRANSITIONED);
eventBusService.post(event);
return transitionToComplete;
}
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> IPartyRoleType nextTaskRoleAssignToFor(
final DO domainObject,
final Class<ST> stateTransitionClass) {
final STT nextTransitionType = nextTaskTransitionTypeFor(domainObject, stateTransitionClass);
if (nextTransitionType == null) {
return null;
}
return nextTransitionType.getAssignTo(domainObject, serviceRegistry2);
}
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> STT nextTaskTransitionTypeFor(
final DO domainObject,
final Class<ST> stateTransitionClass) {
ST pendingTransitionIfAny = pendingTransitionOf(domainObject, stateTransitionClass);
if(pendingTransitionIfAny == null) {
return null;
}
STT transitionType = pendingTransitionIfAny.getTransitionType();
return transitionType.nextTransitionType(domainObject, serviceRegistry2);
}
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> IPartyRoleType peekTaskRoleAssignToAfter(
final DO domainObject,
final STT precedingTransitionType) {
final STT nextTransitionType = peekTaskTransitionTypeAfter(domainObject, precedingTransitionType);
if (nextTransitionType == null) {
return null;
}
return nextTransitionType.getAssignTo(domainObject, serviceRegistry2);
}
@Programmatic
public <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> STT peekTaskTransitionTypeAfter(
final DO domainObject,
final STT precedingTransitionType) {
NextTransitionSearchStrategy<DO, ST, STT, S> nextTransitionSearchStrategy = precedingTransitionType
.getNextTransitionSearchStrategy();
return nextTransitionSearchStrategy
.nextTransitionType(domainObject, precedingTransitionType, serviceRegistry2);
}
/**
* Obtains the most recently completed transition of the domain object, which will be the
* {@link StateTransition#getFromState() from state} of the {@link StateTransition} not yet completed (ie with a
* {@link StateTransition#getToState() to state} is null.
*/
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> ST mostRecentlyCompletedTransitionOf(
final DO domainObject,
final Class<ST> stateTransitionClass) {
final StateTransitionServiceSupport<DO, ST, STT, S> supportService = supportFor(stateTransitionClass);
return supportService.mostRecentlyCompletedTransitionOf(domainObject);
}
// REVIEW: we could cache the result, perhaps (it's idempotent)
@Programmatic
<
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
>
StateTransitionServiceSupport<DO,ST,STT,S> supportFor(final STT transitionType) {
if(supportServices == null) {
throw new IllegalArgumentException("No implementations of StateTransitionServiceSupport found");
}
for (final StateTransitionServiceSupport support : supportServices) {
if(support.supports(transitionType)) {
return support;
}
}
throw new IllegalArgumentException("No implementations of StateTransitionServiceSupport found for " + transitionType);
}
// REVIEW: we could cache the result, perhaps (it's idempotent)
@Programmatic
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
>
StateTransitionServiceSupport<DO,ST,STT,S> supportFor(final Class<ST> stateTransitionClass) {
final String transitionType = metaModelService3.toObjectType(stateTransitionClass);
return supportFor(transitionType);
}
// REVIEW: we could cache the result, perhaps (it's idempotent)
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
>
StateTransitionServiceSupport<DO,ST,STT,S> supportFor(final String transitionType) {
if(supportServices == null) {
throw new IllegalArgumentException("No implementations of StateTransitionServiceSupport found");
}
for (final StateTransitionServiceSupport supportService : supportServices) {
if(supportService.supports(transitionType)) {
return supportService;
}
}
throw new IllegalArgumentException("No implementations of StateTransitionServiceSupport found for " + transitionType);
}
// REVIEW: we could cache the result, perhaps (it's idempotent)
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> Class<ST> transitionClassFor(final STT requiredTransitionType) {
for (StateTransitionServiceSupport supportService : supportServices) {
Class<ST> transitionClass = supportService.transitionClassFor(requiredTransitionType);
if(transitionClass != null) {
return transitionClass;
}
}
return null;
}
@Inject
List<StateTransitionServiceSupport> supportServices;
@Inject
PartyRoleTypeService partyRoleTypeService;
@Inject
PartyRoleTypeRepository partyRoleTypeRepository;
@Inject
ServiceRegistry2 serviceRegistry2;
@Inject
QueryResultsCache queryResultsCache;
@Inject
RepositoryService repositoryService;
@Inject
MetaModelService3 metaModelService3;
@Inject
EventBusService eventBusService;
} |
package org.monarchinitiative.exomiser.core.analysis.util;
import de.charite.compbio.jannovar.annotation.VariantEffect;
import org.monarchinitiative.exomiser.core.model.Gene;
import org.monarchinitiative.exomiser.core.model.TopologicalDomain;
import org.monarchinitiative.exomiser.core.model.TranscriptAnnotation;
import org.monarchinitiative.exomiser.core.model.VariantEvaluation;
import org.monarchinitiative.exomiser.core.prioritisers.PriorityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static java.util.stream.Collectors.toList;
/**
* Reassigns regulatory non-coding variants to the gene with the best phenotype score in a topological domain
* (doi:10.1038/nature11082). 'Recent research shows that high-order chromosome structures make an important contribution
* to enhancer functionality by triggering their physical interactions with target genes.' (doi:10.1038/nature12753).
*
* @author Damian Smedley <damian.smedley@sanger.ac.uk>
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class GeneReassigner {
private static final Logger logger = LoggerFactory.getLogger(GeneReassigner.class);
private final PriorityType priorityType;
private final ChromosomalRegionIndex<TopologicalDomain> tadIndex;
private final Map<String, Gene> allGenes;
/**
* @param priorityType
* @param tadIndex
*/
public GeneReassigner(PriorityType priorityType, Map<String, Gene> allGenes, ChromosomalRegionIndex<TopologicalDomain> tadIndex) {
this.tadIndex = tadIndex;
this.allGenes = allGenes;
this.priorityType = priorityType;
logger.info("Made new GeneReassigner for {}", priorityType);
}
public void reassignRegulatoryRegionVariantToMostPhenotypicallySimilarGeneInTad(VariantEvaluation variantEvaluation) {
if (variantEvaluation.getVariantEffect() == VariantEffect.REGULATORY_REGION_VARIANT) {
logger.debug("Checking gene assignment for {} chr={} pos={}", variantEvaluation.getVariantEffect(), variantEvaluation
.getChromosome(), variantEvaluation.getPosition());
assignVariantToGeneWithHighestPhenotypeScore(variantEvaluation);
}
}
private void assignVariantToGeneWithHighestPhenotypeScore(VariantEvaluation variantEvaluation) {
Gene currentlyAssignedGene = getCurrentlyAssignedGene(variantEvaluation);
//assign this to the variant's current gene as we don't necessarily want ALL the regulatory region variants to clump into one gene.
double bestScore = prioritiserScore(currentlyAssignedGene);
List<Gene> genesInTad = getGenesInTadForVariant(variantEvaluation);
// Optional<Gene> bestScoringGeneInTad = genesInTad.stream().max(Comparator.comparingDouble(this::prioritiserScore));
// logger.info("bestScoringGeneInTad {}", bestScoringGeneInTad);
Gene geneWithHighestPhenotypeScore = null;
for (Gene gene : genesInTad) {
double geneScore = prioritiserScore(gene);
// logger.info("Gene {} in TAD has score {}", gene.getGeneSymbol(), geneScore);
if (geneScore > bestScore) {
bestScore = geneScore;
geneWithHighestPhenotypeScore = gene;
}
}
if (prioritiserScore(currentlyAssignedGene) == bestScore) {
//don't move the assignment if there is nowhere better to go...
return;
}
if (geneWithHighestPhenotypeScore != null) {
//given the physical ranges of topologically associated domains, the annotations are likely to be meaningless once reassigned
//but try to find any anything matching the new gene symbol.
String geneSymbol = geneWithHighestPhenotypeScore.getGeneSymbol();
List<TranscriptAnnotation> matchingGeneAnnotations = getTranscriptAnnotationsMatchingGene(variantEvaluation.getAnnotations(), geneSymbol);
assignVariantToGene(variantEvaluation, geneWithHighestPhenotypeScore, matchingGeneAnnotations);
}
}
private List<Gene> getGenesInTadForVariant(VariantEvaluation variantEvaluation) {
return tadIndex.getRegionsContainingVariant(variantEvaluation).stream()
.map(TopologicalDomain::getGenes)
.flatMap(geneMap -> geneMap.keySet().stream())
.map(allGenes::get)
.filter(Objects::nonNull)
.collect(toList());
}
private double prioritiserScore(Gene gene) {
//Fix for issue 224 - check everywhere for nulls!
if (gene == null || prioritiserHasNotRun(gene)) {
return 0d;
}
return gene.getPriorityResult(priorityType).getScore();
}
private boolean prioritiserHasNotRun(Gene gene) {
return !gene.getPriorityResults().containsKey(priorityType);
}
private List<TranscriptAnnotation> getTranscriptAnnotationsMatchingGene(List<TranscriptAnnotation> annotations, String geneSymbol) {
List<TranscriptAnnotation> matchingGeneAnnotations = new ArrayList<>();
for (TranscriptAnnotation annotation : annotations) {
if (annotation.getGeneSymbol().equals(geneSymbol)) {
matchingGeneAnnotations.add(annotation);
}
}
return matchingGeneAnnotations;
}
private void assignVariantToGene(VariantEvaluation variant, Gene gene, List<TranscriptAnnotation> matchingGeneAnnotations) {
logger.debug("Reassigning {} {}:{} {}->{} from {} to {}", variant.getVariantEffect(), variant.getChromosome(), variant
.getPosition(), variant.getRef(), variant.getAlt(), variant
.getGeneSymbol(), gene.getGeneSymbol());
variant.setGeneSymbol(gene.getGeneSymbol());
variant.setEntrezGeneId(gene.getEntrezGeneID());
variant.setAnnotations(matchingGeneAnnotations);
}
public void reassignGeneToMostPhenotypicallySimilarGeneInAnnotations(VariantEvaluation variantEvaluation) {
if (isInUnknownGene(variantEvaluation)) {
// very rarely a variant just has a single annotation with no gene i.e. geneSymbol is .
return;
}
List<String> geneSymbols = new ArrayList<>();
List<VariantEffect> variantEffects = new ArrayList<>();
List<TranscriptAnnotation> newAnnotations = new ArrayList<>();
for (TranscriptAnnotation annotation : variantEvaluation.getAnnotations()) {
String geneSymbol = annotation.getGeneSymbol();
geneSymbols.add(geneSymbol);
variantEffects.add(annotation.getVariantEffect());
newAnnotations.add(annotation);
// hack to deal with fusion protein Jannovar nonsense -
// ? should the separate genes not be part of the annotation anyway - don't seem to be, should maybe not do this split
if (isValidFusionProtein(geneSymbol)) {
String[] separateGeneSymbols = geneSymbol.split("-");
for (String separateGeneSymbol : separateGeneSymbols) {
geneSymbols.add(separateGeneSymbol);
// for - split entries we do not know effect
variantEffects.add(VariantEffect.CUSTOM);
newAnnotations.add(null);
}
}
}
// logger.info("variantEffects: {}", variantEffects);
// logger.info("newAnnotations: {}", newAnnotations);
Gene currentlyAssignedGene = getCurrentlyAssignedGene(variantEvaluation);
double bestScore = prioritiserScore(currentlyAssignedGene);
Gene geneWithHighestPhenotypeScore = null;
VariantEffect variantEffectForTopHit = null;
TranscriptAnnotation bestAnnotation = null;
for (int i = 0; i < geneSymbols.size(); i++) {
Gene gene = allGenes.get(geneSymbols.get(i));
double geneScore = prioritiserScore(gene);
if (geneScore > bestScore) {
bestScore = geneScore;
geneWithHighestPhenotypeScore = gene;
variantEffectForTopHit = variantEffects.get(i);
//bestAnnotation can be null here
bestAnnotation = newAnnotations.get(i);
// logger.info("Best annotation is {}", bestAnnotation);
}
}
// Keep original annotation if possible - used in RegFilter later on and for display
List<TranscriptAnnotation> finalAnnotations = new ArrayList<>();
if (bestAnnotation != null) {
finalAnnotations.add(bestAnnotation);
}
if (prioritiserScore(currentlyAssignedGene) == bestScore) {
//don't move the assignment if there is nowhere better to go...
return;
}
if (geneWithHighestPhenotypeScore == null) {
return;
}
if (variantEffectForTopHit == null) {
// had one variant where this happened in Genomiser runs and breaks a lot of downstream code
return;
}
/* Only reassign variant effect if it has not already been flagged by RegFeatureDao as a regulatory region variant.
Otherwise TAD reassignment and subsequent reg feature filter fail to work as expected
*/
if (variantEvaluation.getVariantEffect() != VariantEffect.REGULATORY_REGION_VARIANT) {
variantEvaluation.setVariantEffect(variantEffectForTopHit);
}
assignVariantToGene(variantEvaluation, geneWithHighestPhenotypeScore, finalAnnotations);
}
private Gene getCurrentlyAssignedGene(VariantEvaluation variantEvaluation) {
return allGenes.get(variantEvaluation.getGeneSymbol());
}
private boolean isInUnknownGene(VariantEvaluation variantEvaluation) {
return !allGenes.containsKey(variantEvaluation.getGeneSymbol());
}
// avoid RP11-489C13.1 type annotations
private boolean isValidFusionProtein(String geneSymbol) {
return geneSymbol.contains("-") && !geneSymbol.contains(".");
}
} |
package at.fhj.swd14.pse.person.tools;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.servlet.http.HttpServletRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import at.fhj.swd14.pse.department.DepartmentDto;
import at.fhj.swd14.pse.department.DepartmentService;
import at.fhj.swd14.pse.person.PersonUtil;
import at.fhj.swd14.pse.person.CommonPersonBeanTestData;
import at.fhj.swd14.pse.person.HobbyDto;
import at.fhj.swd14.pse.person.KnowledgeDto;
import at.fhj.swd14.pse.person.MailaddressDto;
import at.fhj.swd14.pse.person.PersonBean;
import at.fhj.swd14.pse.person.PersonDto;
import at.fhj.swd14.pse.person.PersonService;
import at.fhj.swd14.pse.person.PhonenumberDto;
import at.fhj.swd14.pse.person.StatusDto;
import at.fhj.swd14.pse.user.UserDto;
import at.fhj.swd14.pse.user.UserAssert;
import at.fhj.swd14.pse.user.UserService;
public class LoggedInPersonHandlerTest {
private LoggedInPersonPageHandler handler;
private PersonBean bean;
private UserService userService;
private PersonService personService;
private DepartmentService departmentService;
private PersonVerifier verifier;
private ExternalContext extContext;
private PersonDto person;
private List<StatusDto> stati;
private List<DepartmentDto> deps;
private UserDto user;
@Before
public void setup()
{
userService = Mockito.mock(UserService.class);
personService = Mockito.mock(PersonService.class);
departmentService = Mockito.mock(DepartmentService.class);
verifier = Mockito.mock(PersonVerifier.class);
bean = Mockito.mock(PersonBean.class);
Mockito.when(bean.getUserService()).thenReturn(userService);
Mockito.when(bean.getPersonService()).thenReturn(personService);
Mockito.when(bean.getDepartmentService()).thenReturn(departmentService);
Mockito.when(bean.getVerifier()).thenReturn(verifier);
handler = new LoggedInPersonPageHandler(bean);
CommonPersonBeanTestData data = PersonUtil.setupServices(userService, personService, departmentService);
person = data.getPerson();
extContext = data.getExtContext();
stati = data.getStati();
deps = data.getDeps();
user=person.getUser();
}
@Test(expected=IllegalArgumentException.class)
public void testBeanNull()
{
new LoggedInPersonPageHandler(null);
}
@Test
public void testLoggedInPerson()
{
String path = handler.showLoggedInPerson();
Assert.assertEquals("/user", path);
Mockito.verify(bean,Mockito.times(1)).setPerson(person);
Mockito.verify(bean,Mockito.times(1)).setStati(stati);
Mockito.verify(bean,Mockito.times(1)). setDepartments(deps);
}
@Test
public void testLoggedOtherPerson()
{
Mockito.when(bean.getPerson()).thenReturn(person);
person.getUser().setId(2L);
String path = handler.showLoggedInPerson();
Assert.assertEquals("/user", path);
Mockito.verify(bean,Mockito.times(1)).setPerson(person);
Mockito.verify(bean,Mockito.times(1)).setStati(stati);
Mockito.verify(bean,Mockito.times(1)). setDepartments(deps);
}
@Test
public void testAlreadyLoaded()
{
Mockito.when(bean.getPerson()).thenReturn(person);
String path = handler.showLoggedInPerson();
Assert.assertEquals("/user", path);
Mockito.verify(bean,Mockito.times(0)).setPerson(person);
Mockito.verify(bean,Mockito.times(1)).setStati(stati);
Mockito.verify(bean,Mockito.times(1)). setDepartments(deps);
}
@Test
public void testPersonNotFound()
{
when(userService.find(1L)).thenReturn(null);
handler.showLoggedInPerson();
Mockito.verify(bean,Mockito.times(1)).setPerson((PersonDto)Mockito.notNull());
}
@Test
public void testCreateInvalidLoggedInPerson()
{
Mockito.when(verifier.verifyName()).thenReturn(false);
String path = handler.createLoggedInPerson();
Assert.assertEquals("/user", path);
Mockito.verify(personService,Mockito.times(0)).saveLoggedInPerson(Mockito.any());
}
@Test
public void testCreateLoggedInPerson()
{
Mockito.when(verifier.verifyName()).thenReturn(true);
person.setUser(null);
person.setStatus(null);
Mockito.when(bean.getPerson()).thenReturn(person);
String path = handler.createLoggedInPerson();
Assert.assertEquals("/user", path);
Assert.assertNotNull(person.getUser());
UserAssert.assertEquals(user, person.getUser());
Assert.assertNotNull(person.getStatus());
Assert.assertEquals("online", person.getStatus().getName());
Mockito.verify(personService,Mockito.times(1)).saveLoggedInPerson(person);
}
@Test
public void testSaveData()
{
//this really is just for code coverage,there is nothing to verify...
handler.saveData();
}
@Test
public void testClearImageUrl()
{
Mockito.when(bean.getPerson()).thenReturn(person);
handler.clearImgUrl();
Assert.assertNull(person.getImageUrl());
}
@Test
public void testSaveInvalidPerson()
{
Mockito.when(verifier.verifyPerson()).thenReturn(false);
handler.savePerson();
Mockito.verify(personService,Mockito.times(0)).saveLoggedInPerson(Mockito.any());
}
@Test
public void testSavePerson()
{
Mockito.when(verifier.verifyPerson()).thenReturn(true);
Mockito.when(bean.getPerson()).thenReturn(person);
handler.savePerson();
Mockito.verify(personService,Mockito.times(1)).saveLoggedInPerson(person);
}
@Test
public void testMailExists()
{
Mockito.when(bean.getNewMail()).thenReturn(person.getAdditionalMails().get(0).getValue());
Mockito.when(bean.getPerson()).thenReturn(person);
handler.addMail();
Mockito.verify(bean,Mockito.times(1)).setNewMail(null);
Mockito.verify(verifier,Mockito.times(0)).verifyMail(Mockito.any());
}
@Test
public void testInvalidMail()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewMail()).thenReturn("hallo@hallo.at");
Mockito.when(verifier.verifyMail(Mockito.any())).thenReturn(false);
handler.addMail();
Mockito.verify(bean,Mockito.times(0)).setNewMail(null);
}
@Test
public void testAddMail()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewMail()).thenReturn("hallo@hallo.at");
Mockito.when(verifier.verifyMail(Mockito.any())).thenReturn(true);
handler.addMail();
Mockito.verify(bean,Mockito.times(1)).setNewMail(null);
}
@Test
public void testKnowledgeExists()
{
Mockito.when(bean.getNewKnowledge()).thenReturn(person.getKnowledges().get(0).getValue());
Mockito.when(bean.getPerson()).thenReturn(person);
handler.addKnowledge();
Mockito.verify(bean,Mockito.times(1)).setNewKnowledge(null);
Mockito.verify(verifier,Mockito.times(0)).verifyKnowledge(Mockito.any());
}
@Test
public void testInvalidKnowledge()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewKnowledge()).thenReturn("hallo");
Mockito.when(verifier.verifyKnowledge(Mockito.any())).thenReturn(false);
handler.addKnowledge();
Mockito.verify(bean,Mockito.times(0)).setNewKnowledge(null);
}
@Test
public void testAddKnowledge()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewKnowledge()).thenReturn("hallo");
Mockito.when(verifier.verifyKnowledge(Mockito.any())).thenReturn(true);
handler.addKnowledge();
Mockito.verify(bean,Mockito.times(1)).setNewKnowledge(null);
}
@Test
public void testHobbyExists()
{
Mockito.when(bean.getNewHobby()).thenReturn(person.getHobbies().get(0).getValue());
Mockito.when(bean.getPerson()).thenReturn(person);
handler.addHobby();
Mockito.verify(bean,Mockito.times(1)).setNewHobby(null);
Mockito.verify(verifier,Mockito.times(0)).verifyHobby(Mockito.any());
}
@Test
public void testInvalidHobby()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewHobby()).thenReturn("hallo");
Mockito.when(verifier.verifyHobby(Mockito.any())).thenReturn(false);
handler.addHobby();
Mockito.verify(bean,Mockito.times(0)).setNewHobby(null);
}
@Test
public void testAddHobby()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewHobby()).thenReturn("hallo");
Mockito.when(verifier.verifyHobby(Mockito.any())).thenReturn(true);
handler.addHobby();
Mockito.verify(bean,Mockito.times(1)).setNewHobby(null);
}
@Test
public void testNumberExists()
{
Mockito.when(bean.getNewNumber()).thenReturn(person.getPhonenumbers().get(0).getValue());
Mockito.when(bean.getPerson()).thenReturn(person);
handler.addNumber();
Mockito.verify(bean,Mockito.times(1)).setNewNumber(null);
Mockito.verify(verifier,Mockito.times(0)).verifyNumber(Mockito.any());
}
@Test
public void testInvalidNumber()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewNumber()).thenReturn("hallo");
Mockito.when(verifier.verifyNumber(Mockito.any())).thenReturn(false);
handler.addNumber();
Mockito.verify(bean,Mockito.times(0)).setNewNumber(null);
}
@Test
public void testAddNumber()
{
Mockito.when(bean.getPerson()).thenReturn(person);
Mockito.when(bean.getNewNumber()).thenReturn("hallo");
Mockito.when(verifier.verifyNumber(Mockito.any())).thenReturn(true);
handler.addNumber();
Mockito.verify(bean,Mockito.times(1)).setNewNumber(null);
}
@Test
public void testRemoveMail()
{
person.getAdditionalMails().add(new MailaddressDto(null, "hallo@hallo.de"));
Map<String,String> params = new HashMap<>();
params.put("value","hallo@hallo.de");
Mockito.when(extContext.getRequestParameterMap()).thenReturn(params);
Mockito.when(bean.getPerson()).thenReturn(person);
handler.removeMail();
Assert.assertEquals(1, person.getAdditionalMails().size());
}
@Test
public void testRemoveKnowledge()
{
person.getKnowledges().add(new KnowledgeDto(null, "hallo"));
Map<String,String> params = new HashMap<>();
params.put("value","hallo");
Mockito.when(extContext.getRequestParameterMap()).thenReturn(params);
Mockito.when(bean.getPerson()).thenReturn(person);
handler.removeKnowledge();
Assert.assertEquals(1, person.getKnowledges().size());
}
@Test
public void testRemoveHobby()
{
person.getHobbies().add(new HobbyDto(null, "hallo"));
Map<String,String> params = new HashMap<>();
params.put("value","hallo");
Mockito.when(extContext.getRequestParameterMap()).thenReturn(params);
Mockito.when(bean.getPerson()).thenReturn(person);
handler.removeHobby();
Assert.assertEquals(1, person.getHobbies().size());
}
@Test
public void testRemoveNumber()
{
person.getPhonenumbers().add(new PhonenumberDto(null, "hallo"));
Map<String,String> params = new HashMap<>();
params.put("value","hallo");
Mockito.when(extContext.getRequestParameterMap()).thenReturn(params);
Mockito.when(bean.getPerson()).thenReturn(person);
handler.removeNumber();
Assert.assertEquals(1, person.getPhonenumbers().size());
}
@Test
public void testFileUpload() throws IOException
{
FileUploadEvent event = Mockito.mock(FileUploadEvent.class);
byte[] filedata = doFileUpload(event);
verifyFileUpload(event, filedata, 0);
}
@Test
public void testFileUploadFailed() throws IOException
{
FileUploadEvent event = Mockito.mock(FileUploadEvent.class);
byte[] filedata = doFileUpload(event);
Mockito.doThrow(IOException.class).when(extContext).redirect(Mockito.anyString());
verifyFileUpload(event, filedata, 1);
}
private byte[] doFileUpload(FileUploadEvent event) {
UploadedFile file = Mockito.mock(UploadedFile.class);
Mockito.when(event.getFile()).thenReturn(file);
byte[] filedata=new byte[1];
Mockito.when(file.getContents()).thenReturn(filedata);
Mockito.when(file.getContentType()).thenReturn("png");
Mockito.when(bean.getPerson()).thenReturn(person);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(extContext.getRequest()).thenReturn(request);
Mockito.when(request.getRequestURI()).thenReturn("http://test");
return filedata;
}
private void verifyFileUpload(FileUploadEvent event, byte[] filedata, int times) throws IOException {
handler.handleFileUpload(event);
Mockito.verify(personService,Mockito.times(1)).savePersonImage(person, filedata, "png");
Mockito.verify(extContext,Mockito.times(1)).redirect("http://test");
Mockito.verify(bean,Mockito.times(times)).growl(Mockito.anyString(),Mockito.anyString());
Assert.assertEquals(person.getImageUrl(), "/swd14-fe/personImage?id="+person.getId());
}
} |
package com.tinkerpop.gremlin.structure.strategy;
import com.tinkerpop.gremlin.AbstractGremlinTest;
import com.tinkerpop.gremlin.FeatureRequirement;
import com.tinkerpop.gremlin.FeatureRequirementSet;
import com.tinkerpop.gremlin.LoadGraphWith;
import com.tinkerpop.gremlin.process.T;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Property;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.VertexProperty;
import com.tinkerpop.gremlin.structure.util.StringFactory;
import com.tinkerpop.gremlin.util.StreamFactory;
import org.javatuples.Pair;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.tinkerpop.gremlin.structure.Graph.Features.PropertyFeatures.FEATURE_PROPERTIES;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
@RunWith(Enclosed.class)
public class StrategyWrappedGraphTest {
public static class CoreTest extends AbstractGremlinTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowAStrategyWrappedGraphToBeReWrapped() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
new StrategyWrappedGraph(swg);
}
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldHaveGraphWrappedFromVertex() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
assertTrue(swg.addVertex().graph() instanceof StrategyWrappedGraph);
}
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldHaveGraphWrappedFromEdge() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final Vertex v = swg.addVertex();
assertTrue(v.addEdge("self", v).graph() instanceof StrategyWrappedGraph);
}
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES)
public void shouldHaveGraphWrappedFromVertexProperty() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
assertTrue(swg.addVertex().property("name", "stephen").graph() instanceof StrategyWrappedGraph);
}
}
@RunWith(Parameterized.class)
public static class ToStringConsistencyTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
return new ArrayList<Object[]>() {{
add(new Object[] {GraphStrategy.DefaultGraphStrategy.INSTANCE} );
add(new Object[] {IdGraphStrategy.build("key").create()} );
add(new Object[] {new PartitionGraphStrategy("partition", "A")} );
add(new Object[] {new ReadOnlyGraphStrategy()} );
add(new Object[] {new SequenceGraphStrategy(new ReadOnlyGraphStrategy(), new PartitionGraphStrategy("partition", "A"))} );
add(new Object[] {new SubgraphStrategy(v -> true, e -> true)} );
}};
}
@Parameterized.Parameter(value = 0)
public GraphStrategy strategy;
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldReturnWrappedVertexToString() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final Vertex v1 = swg.addVertex(T.label, "Person");
final Vertex originalVertex = ((StrategyWrappedVertex) v1).getBaseVertex();
swg.getStrategy().setGraphStrategy(strategy);
assertEquals(StringFactory.graphStrategyVertexString(strategy, originalVertex), v1.toString());
}
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldReturnWrappedEdgeToString() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final Vertex v1 = swg.addVertex(T.label, "Person");
final Vertex v2 = swg.addVertex(T.label, "Person");
final Edge e1 = v1.addEdge("friend", v2);
final Edge originalEdge = ((StrategyWrappedEdge) e1).getBaseEdge();
swg.getStrategy().setGraphStrategy(strategy);
assertEquals(StringFactory.graphStrategyEdgeString(strategy, originalEdge), e1.toString());
}
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldReturnWrappedVertexPropertyToString() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final Vertex v1 = swg.addVertex(T.label, "Person", "age", "one");
final VertexProperty age = v1.property("age");
final Vertex originalVertex = ((StrategyWrappedVertex) v1).getBaseVertex();
final VertexProperty originalVertexProperty = originalVertex.property("age");
swg.getStrategy().setGraphStrategy(strategy);
assertEquals(StringFactory.graphStrategyPropertyString(strategy, originalVertexProperty), age.toString());
}
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldReturnWrappedPropertyToString() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final Vertex v1 = swg.addVertex(T.label, "Person");
final Vertex v2 = swg.addVertex(T.label, "Person");
final Edge e1 = v1.addEdge("friend", v2, "weight", "fifty");
final Property weight = e1.property("weight");
final Edge originalEdge = ((StrategyWrappedEdge) e1).getBaseEdge();
final Property originalProperty = originalEdge.property("weight");
swg.getStrategy().setGraphStrategy(strategy);
assertEquals(StringFactory.graphStrategyPropertyString(strategy, originalProperty), weight.toString());
}
@Test
public void shouldReturnWrappedToString() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final GraphStrategy strategy = swg.getStrategy().getGraphStrategy().orElse(GraphStrategy.DefaultGraphStrategy.INSTANCE);
assertNotEquals(g.toString(), swg.toString());
swg.getStrategy().setGraphStrategy(strategy);
assertEquals(StringFactory.graphStrategyString(strategy, g), swg.toString());
}
}
public static class BlockBaseFunctionTest extends AbstractGremlinTest {
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldNotCallBaseFunctionThusNotRemovingTheVertex() throws Exception {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
// create an ad-hoc strategy that only marks a vertex as "deleted" and removes all edges and properties
// but doesn't actually blow it away
swg.getStrategy().setGraphStrategy(new GraphStrategy() {
@Override
public UnaryOperator<Supplier<Void>> getRemoveVertexStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
return (t) -> () -> {
final Vertex v = ctx.getCurrent().getBaseVertex();
v.bothE().remove();
v.properties().forEachRemaining(Property::remove);
v.property("deleted", true);
return null;
};
}
});
final Vertex toRemove = g.addVertex("name", "pieter");
toRemove.addEdge("likes", g.addVertex("feature", "Strategy"));
assertEquals(1, toRemove.properties().count().next().intValue());
assertEquals(new Long(1), toRemove.bothE().count().next());
assertFalse(toRemove.property("deleted").isPresent());
swg.V(toRemove.id()).remove();
final Vertex removed = g.V(toRemove.id()).next();
assertNotNull(removed);
assertEquals(1, removed.properties().count().next().intValue());
assertEquals(new Long(0), removed.bothE().count().next());
assertTrue(removed.property("deleted").isPresent());
}
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldNotCallBaseFunctionThusNotRemovingTheEdge() throws Exception {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
// create an ad-hoc strategy that only marks a vertex as "deleted" and removes all edges and properties
// but doesn't actually blow it away
swg.getStrategy().setGraphStrategy(new GraphStrategy() {
@Override
public UnaryOperator<Supplier<Void>> getRemoveEdgeStrategy(final Strategy.Context<StrategyWrappedEdge> ctx) {
return (t) -> () -> {
final Edge e = ctx.getCurrent().getBaseEdge();
e.properties().forEachRemaining(Property::remove);
e.property("deleted", true);
return null;
};
}
});
final Vertex v = g.addVertex("name", "pieter");
final Edge e = v.addEdge("likes", g.addVertex("feature", "Strategy"), "this", "something");
assertEquals(1, e.properties().count().next().intValue());
assertFalse(e.property("deleted").isPresent());
swg.E(e.id()).remove();
final Edge removed = g.E(e.id()).next();
assertNotNull(removed);
assertEquals(1, removed.properties().count().next().intValue());
assertTrue(removed.property("deleted").isPresent());
}
@Test
public void shouldAdHocTheCloseStrategy() throws Exception {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
final AtomicInteger counter = new AtomicInteger(0);
swg.getStrategy().setGraphStrategy(new GraphStrategy() {
@Override
public UnaryOperator<Supplier<Void>> getGraphCloseStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (t) -> () -> {
counter.incrementAndGet();
return null;
};
}
});
// allows multiple calls to close() - the test will clean up with a call to the base graph.close()
swg.close();
swg.close();
swg.close();
assertEquals(3, counter.get());
}
}
@RunWith(Parameterized.class)
public static class EdgePropertyShouldBeWrappedTests extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, Edge, Stream<Property<Object>>>>> tests = new ArrayList<>();
tests.add(Pair.with("e.property(all)", (Graph g, Edge e) -> Stream.of(e.property("all"))));
tests.add(Pair.with("e.iterators().properties()", (Graph g, Edge e) -> StreamFactory.stream(e.iterators().propertyIterator())));
tests.add(Pair.with("e.iterators().properties(any)", (Graph g, Edge e) -> StreamFactory.stream(e.iterators().propertyIterator("any"))));
tests.add(Pair.with("e.properties()", (Graph g, Edge e) -> StreamFactory.stream(e.properties())));
tests.add(Pair.with("e.property(extra,more)", (Graph g, Edge e) -> Stream.<Property<Object>>of(e.property("extra", "more"))));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, Edge, Stream<? extends Property<Object>>> streamGetter;
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final Vertex v = swg.addVertex();
final Edge e = v.addEdge("to", v, "all", "a", "any", "something", Graph.Key.hide("hideme"), "hidden");
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(swg, e).allMatch(p -> {
atLeastOne.set(true);
return p instanceof StrategyWrappedProperty;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class VertexPropertyPropertyShouldBeWrappedTests extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, VertexProperty, Stream<Property<Object>>>>> tests = new ArrayList<>();
tests.add(Pair.with("vp.property(food)", (Graph g, VertexProperty vp) -> Stream.of(vp.property("food"))));
tests.add(Pair.with("vp.property(moreFood,sandwhich)", (Graph g, VertexProperty vp) -> Stream.of(vp.property("moreFood","sandwhich"))));
tests.add(Pair.with("vp.property(Graph.Key.hide(more))", (Graph g, VertexProperty vp) -> Stream.of(vp.property(Graph.Key.hide("more")))));
tests.add(Pair.with("vp.property(Graph.Key.hide(extra,this))", (Graph g, VertexProperty vp) -> Stream.of(vp.property(Graph.Key.hide("extra"), "this"))));
tests.add(Pair.with("vp.iterators().properties()", (Graph g, VertexProperty vp) -> StreamFactory.stream(vp.iterators().propertyIterator())));
tests.add(Pair.with("vp.iterators().properties(food)", (Graph g, VertexProperty vp) -> StreamFactory.stream(vp.iterators().propertyIterator("food"))));
tests.add(Pair.with("vp.propertyMap().next().values()", (Graph g, VertexProperty vp) -> StreamFactory.stream(vp.propertyMap().next().values())));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, VertexProperty, Stream<? extends Property<Object>>> streamGetter;
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final Vertex v = swg.addVertex();
final VertexProperty vp = v.property("property", "on-property", "food", "taco", Graph.Key.hide("food"), "burger", "more", "properties", Graph.Key.hide("more"), "hidden");
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(swg, vp).allMatch(p -> {
atLeastOne.set(true);
return p instanceof StrategyWrappedProperty;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class VertexPropertyShouldBeWrappedTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, Vertex, Stream<VertexProperty<Object>>>>> tests = new ArrayList<>();
tests.add(Pair.with("v.property(all)", (Graph g, Vertex v) -> Stream.of(v.property("all"))));
tests.add(Pair.with("v.property(extra, data)", (Graph g, Vertex v) -> Stream.of(v.<Object>property("extra", "data"))));
tests.add(Pair.with("v.iterators().properties()", (Graph g, Vertex v) -> StreamFactory.stream(v.iterators().propertyIterator())));
tests.add(Pair.with("v.iterators().properties(any)", (Graph g, Vertex v) -> StreamFactory.stream(v.iterators().propertyIterator("any"))));
tests.add(Pair.with("v.properties()", (Graph g, Vertex v) -> StreamFactory.stream(v.properties())));
tests.add(Pair.with("v.property(extra,more)", (Graph g, Vertex v) -> Stream.<VertexProperty<Object>>of(v.property("extra", "more"))));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, Vertex, Stream<? extends Property<Object>>> streamGetter;
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final Vertex v = swg.addVertex("all", "a", "any", "something", Graph.Key.hide("hideme"), "hidden");
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(g, v).allMatch(p -> {
atLeastOne.set(true);
return p instanceof StrategyWrappedVertexProperty;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class VertexPropertyWithMultiPropertyShouldBeWrappedTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, Vertex, Stream<VertexProperty<Object>>>>> tests = new ArrayList<>();
tests.add(Pair.with("v.property(all)", (Graph g, Vertex v) -> Stream.of(v.property("all"))));
tests.add(Pair.with("v.property(extra, data)", (Graph g, Vertex v) -> Stream.of(v.<Object>property("extra", "data"))));
tests.add(Pair.with("v.iterators().properties()", (Graph g, Vertex v) -> StreamFactory.stream(v.iterators().propertyIterator())));
tests.add(Pair.with("v.iterators().properties(any)", (Graph g, Vertex v) -> StreamFactory.stream(v.iterators().propertyIterator("any"))));
tests.add(Pair.with("v.properties()", (Graph g, Vertex v) -> StreamFactory.stream(v.properties())));
tests.add(Pair.with("v.property(extra,more)", (Graph g, Vertex v) -> Stream.<VertexProperty<Object>>of(v.property("extra", "more"))));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, Vertex, Stream<? extends Property<Object>>> streamGetter;
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final Vertex v = swg.addVertex("all", "a", "any", "something", "any", "something-else", Graph.Key.hide("hideme"), "hidden", Graph.Key.hide("hideme"), "hidden-too");
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(g, v).allMatch(p -> {
atLeastOne.set(true);
return p instanceof StrategyWrappedVertexProperty;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class EdgeShouldBeWrappedTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, AbstractGremlinTest, Stream<Edge>>>> tests = new ArrayList<>();
tests.add(Pair.with("g.E()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.E())));
tests.add(Pair.with("g.iterators().edgeIterator()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.iterators().edgeIterator())));
tests.add(Pair.with("g.iterators().edgeIterator(11)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.iterators().edgeIterator(11))));
tests.add(Pair.with("g.E(11)", (Graph g, AbstractGremlinTest instance) -> Stream.of(g.E(instance.convertToEdgeId("josh", "created", "lop")).next())));
tests.add(Pair.with("g.V(1).outE()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).outE())));
tests.add(Pair.with("g.V(4).bothE()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).bothE())));
tests.add(Pair.with("g.V(4).inE()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).inE())));
tests.add(Pair.with("g.V(11).property(weight).element()", (Graph g, AbstractGremlinTest instance) -> Stream.of((Edge) g.E(instance.convertToEdgeId("josh", "created", "lop")).next().property("weight").element())));
tests.add(Pair.with("g.V(4).next().iterators().edge(Direction.BOTH)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).next().iterators().edgeIterator(Direction.BOTH))));
tests.add(Pair.with("g.V(1).next().iterators().edge(Direction.OUT)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).next().iterators().edgeIterator(Direction.OUT))));
tests.add(Pair.with("g.V(4).next().iterators().edge(Direction.IN)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).next().iterators().edgeIterator(Direction.IN))));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, AbstractGremlinTest, Stream<Edge>> streamGetter;
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(swg, this).allMatch(e -> {
atLeastOne.set(true);
return e instanceof StrategyWrappedEdge;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class VertexShouldBeWrappedTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, AbstractGremlinTest, Stream<Vertex>>>> tests = new ArrayList<>();
tests.add(Pair.with("g.V()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V())));
tests.add(Pair.with("g.iterators().vertexIterator()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.iterators().vertexIterator())));
tests.add(Pair.with("g.iterators().vertexIterator(1)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.iterators().vertexIterator(1))));
tests.add(Pair.with("g.V(1)", (Graph g, AbstractGremlinTest instance) -> Stream.of(g.V(instance.convertToVertexId("marko")).next())));
tests.add(Pair.with("g.V(1).outE().inV()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).outE().inV())));
tests.add(Pair.with("g.V(4).bothE().bothV()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).bothE().bothV())));
tests.add(Pair.with("g.V(4).inE().outV()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).inE().outV())));
tests.add(Pair.with("g.V(1).out()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).out())));
tests.add(Pair.with("g.V(4).iterators().vertices(Direction.BOTH)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).next().iterators().vertexIterator(Direction.BOTH))));
tests.add(Pair.with("g.V(1).iterators().vertices(Direction.OUT)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).next().iterators().vertexIterator(Direction.OUT))));
tests.add(Pair.with("g.V(4).iterators().vertices(Direction.IN)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).next().iterators().vertexIterator(Direction.IN))));
tests.add(Pair.with("g.V(4).iterators().vertices(Direction.BOTH, \"created\")", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).next().iterators().vertexIterator(Direction.BOTH, "created"))));
tests.add(Pair.with("g.E(11).iterators().vertices(Direction.IN)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.E(instance.convertToEdgeId("josh", "created", "lop")).next().iterators().vertexIterator(Direction.IN))));
tests.add(Pair.with("g.E(11).iterators().vertices(Direction.OUT)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.E(instance.convertToEdgeId("josh", "created", "lop")).next().iterators().vertexIterator(Direction.OUT))));
tests.add(Pair.with("g.E(11).iterators().vertices(Direction.BOTH)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.E(instance.convertToEdgeId("josh", "created", "lop")).next().iterators().vertexIterator(Direction.BOTH))));
tests.add(Pair.with("g.V(1).iterators().properties(name).next().element()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).next().iterators().propertyIterator("name").next().element())));
tests.add(Pair.with("g.V(1).outE().otherV()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).outE().otherV())));
tests.add(Pair.with("g.V(4).inE().otherV()", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("josh")).inE().otherV())));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, AbstractGremlinTest, Stream<Vertex>> streamGetter;
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(swg, this).allMatch(v -> {
atLeastOne.set(true);
return v instanceof StrategyWrappedVertex;
}));
assertTrue(atLeastOne.get());
}
}
@RunWith(Parameterized.class)
public static class GraphShouldBeWrappedTest extends AbstractGremlinTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
final List<Pair<String, BiFunction<Graph, AbstractGremlinTest, Stream<Graph>>>> tests = new ArrayList<>();
tests.add(Pair.with("g.V(1).graph()", (Graph g, AbstractGremlinTest instance) -> Stream.of(g.V(instance.convertToVertexId("marko")).next().graph())));
tests.add(Pair.with("g.V(1).iterators().edgeIterator(BOTH).map(Edge::graph)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).next().iterators().edgeIterator(Direction.BOTH)).map(Edge::graph)));
tests.add(Pair.with("g.V(1).iterators().propertyIterator().map(Edge::graph)", (Graph g, AbstractGremlinTest instance) -> StreamFactory.stream(g.V(instance.convertToVertexId("marko")).next().iterators().propertyIterator()).map(VertexProperty::graph)));
return tests.stream().map(d -> {
final Object[] o = new Object[2];
o[0] = d.getValue0();
o[1] = d.getValue1();
return o;
}).collect(Collectors.toList());
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public BiFunction<Graph, AbstractGremlinTest, Stream<Graph>> streamGetter;
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldWrap() {
final StrategyWrappedGraph swg = new StrategyWrappedGraph(g);
swg.getStrategy().setGraphStrategy(GraphStrategy.DefaultGraphStrategy.INSTANCE);
final AtomicBoolean atLeastOne = new AtomicBoolean(false);
assertTrue(streamGetter.apply(swg, this).allMatch(v -> {
atLeastOne.set(true);
return v instanceof StrategyWrappedGraph;
}));
assertTrue(atLeastOne.get());
}
}
} |
package org.hibernate.ogm.datastore.impl;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metamodel.source.MetadataImplementor;
import org.hibernate.ogm.datastore.spi.DatastoreProvider;
import org.hibernate.ogm.util.impl.Log;
import org.hibernate.ogm.util.impl.LoggerFactory;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.classloading.spi.ClassLoadingException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
import java.util.Arrays;
import java.util.Map;
/**
* Loads the appropriate {@link DatastoreProvider}. Driven by the {@link #DATASTORE_PROVIDER}
* property which can receive
* <ul>
* <li>a {@code DatastoreProvider} instance</li>
* <li>a {@code DatastoreProvider} class</li>
* <li>a string representing the {@code DatastoreProvider} class</li>
* <li>a string reprenseting one of the datastore provider shortcuts</li>
* </ul>
*
* If the property is not set, Infinispan is used by default.
*
* @author Emmanuel Bernard <emmanuel@hibernate.org>
* @author Davide D'Alto <davide@hibernate.org>
*/
public final class DatastoreProviderInitiator implements SessionFactoryServiceInitiator<DatastoreProvider> {
public static final String DATASTORE_PROVIDER = "hibernate.ogm.datastore.provider";
public static final DatastoreProviderInitiator INSTANCE = new DatastoreProviderInitiator();
private static final Log log = LoggerFactory.make();
private static final String DEFAULT_DATASTORE_PROVIDER_CLASS = "org.hibernate.ogm.datastore.infinispan.impl.InfinispanDatastoreProvider";
@Override
public Class<DatastoreProvider> getServiceInitiated() {
return DatastoreProvider.class;
}
@Override
public DatastoreProvider initiateService(SessionFactoryImplementor sessionFactory, Configuration configuration, ServiceRegistryImplementor registry) {
DatastoreProvider datastoreProvider = createDatastoreProvider( configuration.getProperties(), registry );
log.useDatastoreProvider( datastoreProvider.getClass().getName() );
return datastoreProvider;
}
@Override
public DatastoreProvider initiateService(SessionFactoryImplementor sessionFactory, MetadataImplementor metadata, ServiceRegistryImplementor registry) {
throw new UnsupportedOperationException( "Cannot create " + DatastoreProvider.class.getName() + " service using metadata" );
}
private DatastoreProvider createDatastoreProvider(Map<?, ?> configuration, ServiceRegistryImplementor registry) {
Object datastoreProviderProperty = configuration.get( DATASTORE_PROVIDER );
if ( datastoreProviderProperty == null ) {
return defaultDatastoreProvider( registry );
}
else if ( datastoreProviderProperty instanceof DatastoreProvider ) {
return (DatastoreProvider) datastoreProviderProperty;
}
else if ( datastoreProviderProperty instanceof String ) {
return createDatastore( registry, (String) datastoreProviderProperty );
}
else if ( datastoreProviderProperty instanceof Class<?> ) {
return create( (Class<?>) datastoreProviderProperty );
}
throw log.unknownDatastoreManagerType( datastoreProviderProperty.getClass().getName() );
}
private DatastoreProvider createDatastore(ServiceRegistryImplementor registry, String managerProperty) {
Class<?> dataStoreProviderClass = findDataStoreProviderClass( registry, managerProperty );
return create( dataStoreProviderClass );
}
private DatastoreProvider create(Class<?> datastoreProviderClass) {
try {
validate( datastoreProviderClass );
return (DatastoreProvider) datastoreProviderClass.newInstance();
}
catch (InstantiationException e) {
throw log.unableToInstantiateDatastoreManager( datastoreProviderClass.getName(), e );
}
catch (IllegalAccessException e) {
throw log.unableToInstantiateDatastoreManager( datastoreProviderClass.getName(), e );
}
}
private DatastoreProvider defaultDatastoreProvider(ServiceRegistryImplementor registry) {
try {
ClassLoaderService service = registry.getService( ClassLoaderService.class );
Class<?> datastoreProviderClass = service.classForName( DEFAULT_DATASTORE_PROVIDER_CLASS );
return (DatastoreProvider) datastoreProviderClass.newInstance();
}
catch (ClassLoadingException e) {
throw log.noDatastoreConfigured();
}
catch (InstantiationException e) {
throw log.unableToInstantiateDatastoreManager( DEFAULT_DATASTORE_PROVIDER_CLASS, e );
}
catch (IllegalAccessException e) {
throw log.unableToInstantiateDatastoreManager( DEFAULT_DATASTORE_PROVIDER_CLASS, e );
}
}
private void validate(Class<?> datastoreProviderClass) {
if ( !( DatastoreProvider.class.isAssignableFrom( datastoreProviderClass ) ) ) {
throw log.notADatastoreManager( datastoreProviderClass.getName() );
}
}
private Class<?> findDataStoreProviderClass(ServiceRegistryImplementor registry, final String managerPropertyValue) {
try {
String datastoreProviderClassName = dataStoreProviderClassName( managerPropertyValue );
return registry.getService( ClassLoaderService.class ).classForName( datastoreProviderClassName );
}
catch (Exception e) {
throw log.datastoreClassCannotBeFound( managerPropertyValue, Arrays.toString( AvailableDatastoreProvider.values() ) );
}
}
private String dataStoreProviderClassName(final String managerPropertyValue) {
if ( isValidShortcut( managerPropertyValue ) ) {
return AvailableDatastoreProvider.valueOf( managerPropertyValue.toUpperCase() ).getDatastoreProviderClassName();
}
else {
return managerPropertyValue;
}
}
private boolean isValidShortcut(String shortcut) {
for ( AvailableDatastoreProvider provider : AvailableDatastoreProvider.values() ) {
if ( provider.name().equalsIgnoreCase( shortcut ) ) {
return true;
}
}
return false;
}
} |
package com.servinglynk.hmis.warehouse.listener;
import java.util.UUID;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import com.servinglynk.hmis.warehouse.common.MQDateUtil;
import com.servinglynk.hmis.warehouse.model.AMQEvent;
import com.servinglynk.hmis.warehouse.model.ClientMetaDataModel;
import com.servinglynk.hmis.warehouse.model.JSONObjectMapper;
@Component
public class SurveyResponseListener extends BaseListener {
@JmsListener(destination="survey.submissions")
public void listeneQueue(String eventString) {
System.out.println("inside survey.submissions listener");
JSONObjectMapper mapper = new JSONObjectMapper();
try {
AMQEvent event = mapper.readValue(eventString, AMQEvent.class);
ClientMetaDataModel model = new ClientMetaDataModel();
model.setAdditionalInfo(mapper.writeValueAsString(event.getPayload()));
if(event.getPayload().get("dedupClientId")!=null) model.setClientDedupId(UUID.fromString(event.getPayload().get("dedupClientId").toString()));
if(event.getPayload().get("clientId")!=null) model.setClientId(UUID.fromString(event.getPayload().get("clientId").toString()));
if(event.getPayload().get("submissionDate")!=null) model.setDate(MQDateUtil.stringToDateTime(event.getPayload().get("submissionDate").toString()));
if(event.getPayload().get("submissionId")!=null) model.setMetaDataIdentifier(UUID.fromString(event.getPayload().get("submissionId").toString()));
if(event.getPayload().get("projectGroupCode")!=null) model.setProjectGroupCode(event.getPayload().get("projectGroupCode").toString());
model.setType("surveySubmissions");
if(event.getPayload().get("userId")!=null) model.setUserId(UUID.fromString(event.getPayload().get("userId").toString()));
if(Boolean.parseBoolean(event.getPayload().get("deleted").toString())) {
serviceFactory.getClientMetaDataService().deleteClientMetaData(model);
}else {
serviceFactory.getClientMetaDataService().createClientMetaData(model);
}
}catch (Exception e) {
e.printStackTrace();
}
}
} |
package rocks.inspectit.ui.rcp.ci.view;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.part.ViewPart;
import rocks.inspectit.shared.cs.ci.Environment;
import rocks.inspectit.shared.cs.ci.Profile;
import rocks.inspectit.ui.rcp.InspectIT;
import rocks.inspectit.ui.rcp.ci.job.OpenEnvironmentJob;
import rocks.inspectit.ui.rcp.ci.job.OpenProfileJob;
import rocks.inspectit.ui.rcp.ci.listener.IEnvironmentChangeListener;
import rocks.inspectit.ui.rcp.ci.listener.IProfileChangeListener;
import rocks.inspectit.ui.rcp.model.ci.EnvironmentLeaf;
import rocks.inspectit.ui.rcp.model.ci.ProfileLeaf;
import rocks.inspectit.ui.rcp.provider.IEnvironmentProvider;
import rocks.inspectit.ui.rcp.provider.IProfileProvider;
import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition;
import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition.OnlineStatus;
import rocks.inspectit.ui.rcp.view.IRefreshableView;
/**
* {@link ViewPart} displaying {@link Profile}s and {@link Environment}s.
*
* @author Ivan Senic, Alexander Wert
*
*/
public class InstrumentationManagerViewPart extends ViewPart implements IRefreshableView {
/**
* View id.
*/
public static final String VIEW_ID = "rocks.inspectit.ui.rcp.ci.view.instrumentationManager";
/**
* View instance.
*/
private AbstractTableBasedManagerView managerView;
/**
* {@inheritDoc}
*/
@Override
public void createPartControl(Composite parent) {
managerView = new InstrumentationManagerView(getSite());
managerView.createControls(parent, false);
getSite().setSelectionProvider(managerView.getSelectionProviderAdapter());
}
/**
* {@inheritDoc}
*/
@Override
public void setFocus() {
managerView.setFocus();
}
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
managerView.dispose();
super.dispose();
}
/**
* {@inheritDoc}
*/
@Override
public void refresh() {
managerView.refresh();
}
/**
* {@inheritDoc}
*/
@Override
public boolean canRefresh() {
return managerView.canRefresh();
}
/**
* View displaying {@link Profile}s and {@link Environment}s.
*
* @author Ivan Senic, Alexander Wert
*
*/
private static class InstrumentationManagerView extends AbstractTableBasedManagerView implements IProfileChangeListener, IEnvironmentChangeListener {
/**
* Menu to be bounded.
*/
private static final String MENU_ID = "rocks.inspectit.ui.rcp.ci.view.instrumentationManager.table";
/**
* Input list of profiles.
*/
private List<IProfileProvider> profileLeafs = new ArrayList<>(0);
/**
* Input list of environments.
*/
private List<IEnvironmentProvider> environmentLeafs = new ArrayList<>(0);
/**
* Button for environment selection.
*/
private Button environmentSelection;
/**
* Button for profile selection.
*/
private Button profileSelection;
/**
* Default constructor.
*
* @param workbenchPartSite
* The {@link IWorkbenchPartSite} the view is showed in.
*/
InstrumentationManagerView(IWorkbenchPartSite workbenchPartSite) {
super(workbenchPartSite);
InspectIT.getDefault().getInspectITConfigurationInterfaceManager().addProfileChangeListener(this);
InspectIT.getDefault().getInspectITConfigurationInterfaceManager().addEnvironmentChangeListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void createControls(Composite parent, boolean multiSelection) {
super.createControls(parent, multiSelection);
}
/**
* {@inheritDoc}
*/
@Override
protected void createHeadClient(Form form) {
Composite headClient = new Composite(form.getHead(), SWT.NONE);
GridLayout gl = new GridLayout(3, false);
gl.marginHeight = 0;
gl.marginWidth = 0;
headClient.setLayout(gl);
new Label(headClient, SWT.NONE).setText("Show:");
environmentSelection = new Button(headClient, SWT.RADIO);
environmentSelection.setText("Environments");
environmentSelection.setSelection(true);
profileSelection = new Button(headClient, SWT.RADIO);
profileSelection.setText("Profiles");
SelectionAdapter listener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (null != displayedCmrRepositoryDefinition) {
selectionProviderAdapter.setSelection(new StructuredSelection(displayedCmrRepositoryDefinition));
}
performUpdate(false);
}
};
environmentSelection.addSelectionListener(listener);
profileSelection.addSelectionListener(listener);
form.setHeadClient(headClient);
}
/**
* {@inheritDoc}
*/
@Override
protected void createTableColumns(TableViewer tableViewer) {
if (isShowEnvironments()) {
// columns when environments are displayed
TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Environment");
viewerColumn.getColumn().setWidth(150);
viewerColumn.getColumn().setToolTipText("Environment name.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Updated");
viewerColumn.getColumn().setWidth(80);
viewerColumn.getColumn().setToolTipText("The date and time when the environment was last time updated.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Profiles");
viewerColumn.getColumn().setWidth(60);
viewerColumn.getColumn().setToolTipText("Number of linked profiles in the Environment.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Description");
viewerColumn.getColumn().setWidth(150);
viewerColumn.getColumn().setToolTipText("Environment description.");
} else if (isShowProfiles()) {
// columns when profiles are displayed
TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Profile");
viewerColumn.getColumn().setWidth(150);
viewerColumn.getColumn().setToolTipText("Profile name.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Updated");
viewerColumn.getColumn().setWidth(80);
viewerColumn.getColumn().setToolTipText("The date and time when the profile was last time updated.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Active");
viewerColumn.getColumn().setWidth(40);
viewerColumn.getColumn()
.setToolTipText("If profile is active or not, note that deactivated profile will not be considered during the instrumentation even if it's a part of an Environment.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Default");
viewerColumn.getColumn().setWidth(40);
viewerColumn.getColumn().setToolTipText("If profile is default or not, note that default profile will be added to any new created Environment.");
TableViewerColumn typeColumn = new TableViewerColumn(tableViewer, SWT.NONE);
typeColumn.getColumn().setMoveable(true);
typeColumn.getColumn().setResizable(true);
typeColumn.getColumn().setText("Type");
typeColumn.getColumn().setWidth(40);
typeColumn.getColumn().setToolTipText("Type of data profile is holding.");
viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
viewerColumn.getColumn().setMoveable(true);
viewerColumn.getColumn().setResizable(true);
viewerColumn.getColumn().setText("Description");
viewerColumn.getColumn().setWidth(250);
viewerColumn.getColumn().setToolTipText("Profile description.");
}
tableViewer.setLabelProvider(getLabelProvider());
ViewerComparator comparator = getViewerComparator();
if (null != comparator) {
tableViewer.setComparator(getViewerComparator());
}
}
/**
* {@inheritDoc}
*/
@Override
protected IBaseLabelProvider getLabelProvider() {
if (isShowEnvironments()) {
return new EnvironmentLabelProvider();
} else if (isShowProfiles()) {
return new ProfileLabelProvider();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected IDoubleClickListener getDoubleClickListener() {
return new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty()) {
Object selected = ((StructuredSelection) selection).getFirstElement();
if (selected instanceof IProfileProvider) {
// open profile job
IProfileProvider profileProvider = (IProfileProvider) selected;
new OpenProfileJob(profileProvider.getCmrRepositoryDefinition(), profileProvider.getProfile().getId(), getWorkbenchSite().getPage()).schedule();
} else if (selected instanceof IEnvironmentProvider) {
IEnvironmentProvider environmentProvider = (IEnvironmentProvider) selected;
new OpenEnvironmentJob(environmentProvider.getCmrRepositoryDefinition(), environmentProvider.getEnvironment().getId(), getWorkbenchSite().getPage()).schedule();
}
}
}
};
}
/**
* {@inheritDoc}
*/
@Override
public void profileCreated(Profile profile, CmrRepositoryDefinition repositoryDefinition) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
ProfileLeaf profileLeaf = new ProfileLeaf(profile, repositoryDefinition);
profileLeafs.add(profileLeaf);
showProfiles(false);
}
/**
* {@inheritDoc}
*/
@Override
public void profileUpdated(Profile profile, CmrRepositoryDefinition repositoryDefinition, boolean onlyProperties) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
for (Iterator<IProfileProvider> it = profileLeafs.iterator(); it.hasNext();) {
IProfileProvider provider = it.next();
if (Objects.equals(profile.getId(), provider.getProfile().getId())) {
it.remove();
profileLeafs.add(new ProfileLeaf(profile, provider.getCmrRepositoryDefinition()));
performUpdate(false);
break;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void profileDeleted(Profile profile, CmrRepositoryDefinition repositoryDefinition) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
for (Iterator<IProfileProvider> it = profileLeafs.iterator(); it.hasNext();) {
IProfileProvider provider = it.next();
if (Objects.equals(profile.getId(), provider.getProfile().getId())) {
it.remove();
performUpdate(false);
break;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void environmentCreated(Environment environment, CmrRepositoryDefinition repositoryDefinition) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
EnvironmentLeaf environmentLeaf = new EnvironmentLeaf(environment, repositoryDefinition);
environmentLeafs.add(environmentLeaf);
showEnvironments(false);
}
/**
* {@inheritDoc}
*/
@Override
public void environmentUpdated(Environment environment, CmrRepositoryDefinition repositoryDefinition) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
for (Iterator<IEnvironmentProvider> it = environmentLeafs.iterator(); it.hasNext();) {
IEnvironmentProvider provider = it.next();
if (Objects.equals(environment.getId(), provider.getEnvironment().getId())) {
it.remove();
environmentLeafs.add(new EnvironmentLeaf(environment, repositoryDefinition));
performUpdate(false);
break;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void environmentDeleted(Environment environment, CmrRepositoryDefinition repositoryDefinition) {
if (!Objects.equals(repositoryDefinition, displayedCmrRepositoryDefinition)) {
return;
}
for (Iterator<IEnvironmentProvider> it = environmentLeafs.iterator(); it.hasNext();) {
IEnvironmentProvider provider = it.next();
if (Objects.equals(environment.getId(), provider.getEnvironment().getId())) {
it.remove();
performUpdate(false);
break;
}
}
}
/**
* @return Are environments displayed.
*/
private boolean isShowEnvironments() {
return environmentSelection.getSelection();
}
/**
* @return Are profiles displayed.
*/
private boolean isShowProfiles() {
return profileSelection.getSelection();
}
/**
* Makes the view show the environments.
*
* @param update
* If update of the input should be made.
*/
public void showEnvironments(boolean update) {
if (!isShowEnvironments()) {
environmentSelection.setSelection(true);
profileSelection.setSelection(false);
}
performUpdate(update);
}
/**
* Makes the view show the profiles.
*
* @param update
* If update of the input should be made.
*/
public void showProfiles(boolean update) {
if (!isShowProfiles()) {
profileSelection.setSelection(true);
environmentSelection.setSelection(false);
}
performUpdate(update);
}
/**
* {@inheritDoc}
*/
@Override
protected String getMenuId() {
return MENU_ID;
};
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
InspectIT.getDefault().getInspectITConfigurationInterfaceManager().removeProfileChangeListener(this);
InspectIT.getDefault().getInspectITConfigurationInterfaceManager().removeEnvironmentChangeListener(this);
super.dispose();
}
/**
* {@inheritDoc}
*/
@Override
protected boolean matchesContentType(Object object) {
return (object instanceof IProfileProvider) || (object instanceof IEnvironmentProvider);
}
/**
* {@inheritDoc}
*/
@Override
protected void updateContent() {
// reset lists
profileLeafs = new ArrayList<>();
environmentLeafs = new ArrayList<>();
if ((null != displayedCmrRepositoryDefinition) && (displayedCmrRepositoryDefinition.getOnlineStatus() == OnlineStatus.ONLINE)) {
// profiles
List<Profile> profiles = displayedCmrRepositoryDefinition.getConfigurationInterfaceService().getAllProfiles();
for (Profile profile : profiles) {
profileLeafs.add(new ProfileLeaf(profile, displayedCmrRepositoryDefinition));
}
// environment
Collection<Environment> environments = displayedCmrRepositoryDefinition.getConfigurationInterfaceService().getAllEnvironments();
for (Environment environment : environments) {
environmentLeafs.add(new EnvironmentLeaf(environment, displayedCmrRepositoryDefinition));
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected List<?> getTableInput() {
if (isShowEnvironments()) {
return environmentLeafs;
} else if (isShowProfiles()) {
return profileLeafs;
}
return null;
}
}
} |
package com.io7m.jcanephora.documentation;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Functions for retrieving the documentation.
*/
public final class CDocumentation
{
public static URI getDocumentationXMLLocation()
{
try {
final URL url =
CDocumentation.class
.getResource("/com/io7m/jcanephora/documentation/documentation.xml");
assert url != null;
final URI uri = url.toURI();
assert uri != null;
return uri;
} catch (final URISyntaxException e) {
throw new AssertionError(e);
}
}
} |
package test;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.EndSystem;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Monitor;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.StartSystem;
import test.testing.MonitoringGroupValue;
import test.testing.TestEnvironment;
import test.threadedTest.Data;
/**
* Tests multiple recording ids in one recording group.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
public class MultiRecIdTest {
/**
* Defines the maximum allocation count for part 1.
*/
private static final int MAX_ALLOC1 = 10;
/**
* Defines the maximum allocation count for part 2.
*/
private static final int MAX_ALLOC2 = 20;
/**
* Stores the size of a data object.
*/
private static long dataSize = -1;
/**
* The number of bytes read in summary.
*/
private static long fileRead = -1;
/**
* Prevents this class from being instantiated from outside.
*
* @since 1.00
*/
protected MultiRecIdTest() {
}
/**
* Individual part to be recorded for id1.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
@Monitor(id = AnnotationId.ID_MULTI_1)
private static class Part1 {
/**
* Stores the data.
*/
@SuppressWarnings("unused")
private Data data;
/**
* Executes this part.
*
* @since 1.00
*/
public void execute() {
for (int i = 0; i < MAX_ALLOC1; i++) {
data = new Data();
if (i % 50 == 0) {
System.gc();
}
}
}
}
/**
* Individual part to be recorded for id2.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
@Monitor(id = AnnotationId.ID_MULTI_2)
private static class Part2 {
/**
* Stores the data.
*/
@SuppressWarnings("unused")
private Data data;
/**
* Executes this part.
*
* @since 1.00
*/
public void execute() {
for (int i = 0; i < MAX_ALLOC2; i++) {
data = new Data();
if (i % 50 == 0) {
System.gc();
}
}
}
}
/**
* Common part.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
@Monitor(id = {AnnotationId.ID_MULTI_1, AnnotationId.ID_MULTI_2 })
private static class Part3 {
/**
* Executes this part.
*
* @since 1.00
*/
public void execute() {
File file = new File("src/test/MultiRecIdTest.java");
try {
URL url = file.toURI().toURL();
fileRead = TestUtils.read(url.openStream());
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
}
/**
* Starts the test.
*
* @param args ignored
*
* @since 1.00
*/
@StartSystem
@EndSystem(invoke = "asserts")
public static void main(String[] args) {
// avoid explicit class loading
dataSize = TestEnvironment.getObjectSize(new Data());
// do tests
new Part1().execute();
new Part2().execute();
new Part3().execute();
}
/**
* The automated tests using assert statements. This method is called
* by SPASS-meter at end of monitoring upon the <code>EndSystem</code>
* annotation.
*
* @since 1.00
*/
public static void asserts() {
// own allocation + file + URL in part 3
TestEnvironment.assertGreater(AnnotationId.ID_MULTI_1,
MonitoringGroupValue.ALLOCATED_MEMORY, dataSize * MAX_ALLOC1);
// own allocation + file + URL in part 3
TestEnvironment.assertGreater(AnnotationId.ID_MULTI_2,
MonitoringGroupValue.ALLOCATED_MEMORY, dataSize * MAX_ALLOC2);
TestEnvironment.assertEquals(AnnotationId.ID_MULTI_1,
MonitoringGroupValue.FILE_READ, fileRead);
TestEnvironment.success(AnnotationId.ID_INDIRECT);
}
} |
package it.polimi.ingsw.client.cli;
import it.polimi.ingsw.client.GameController;
import it.polimi.ingsw.client.View;
import it.polimi.ingsw.game.GameMap;
import it.polimi.ingsw.game.card.object.ObjectCardBuilder;
import it.polimi.ingsw.game.common.GameInfo;
import it.polimi.ingsw.game.common.PlayerInfo;
import it.polimi.ingsw.game.common.ViewCommand;
import java.awt.Point;
import java.util.List;
import java.util.Set;
/**
* @author Alain Carlucci (alain.carlucci@mail.polimi.it)
* @since May 10, 2015
*/
public class CLIView extends View {
private static void banner() {
IO.write("*******************************************************************************");
IO.write("*******************************************************************************");
IO.write("*** ______ _____ _____ _____ ______ ***");
IO.write("*** | ____| / ____| / ____| /\\ | __ \\ | ____| ***");
IO.write("*** | |__ | (___ | | / \\ | |__) | | |__ ***");
IO.write("*** | __| \\___ \\ | | / /\\ \\ | ___/ | __| ***");
IO.write("*** | |____ ____) | | |____ / ____ \\ | | | |____ ***");
IO.write("*** |______| |_____/ \\_____| /_/ \\_\\ |_| |______| ***");
IO.write("*** ___ ___ ___ __ __ _____ _ _ ___ _ _ ___ ___ _ _ ___ ***");
IO.write("*** | __| _ \\/ _ \\| \\/ | |_ _| || | __| /_\\ | | |_ _| __| \\| / __| ***");
IO.write("*** | _|| / (_) | |\\/| | | | | __ | _| / _ \\| |__ | || _|| .` \\__ \\ ***");
IO.write("*** |_| |_|_\\\\___/|_| |_| |_| |_||_|___| /_/ \\_\\____|___|___|_|\\_|___/ ***");
IO.write("*** ___ _ _ ___ _ _ _____ ___ ___ ___ ___ _ ___ ___ ***");
IO.write("*** |_ _|| \\| | / _ \\ | | | ||_ _|| __|| _ \\ / __|| _ \\ /_\\ / __|| __| ***");
IO.write("*** | | | .` | | (_) || |_| | | | | _| | / \\__ \\| _
IO.write("*** |___||_|\\_| \\___/ \\___/ |_| |___||_|_\\ |___/|_| /_/ \\_\\\\___||___| ***");
IO.write("*** ***");
IO.write("*** Command line client by Michele Albanese & Alain Carlucci ***");
IO.write("*******************************************************************************");
IO.write("*******************************************************************************");
IO.write("");
}
private GameMap mMap;
private final GameController mController;
private GameInfo mContainer;
/** The constructor
* @param c Game Controller
*/
public CLIView(GameController c) {
super(c);
mController = c;
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#startup()
*/
@Override
public void startup() {
CLIView.banner();
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#run()
*/
@Override
public void run() {
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#askConnectionType(java.lang.String[])
*/
@Override
public int askConnectionType(String[] params) {
IO.write("Which connection do you want to use?");
return IO.askInAList(params, false);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#askUsername(java.lang.String)
*/
@Override
public String askUsername(String message) {
String name;
IO.write(message);
name = IO.readString().trim();
return name;
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#askMap(java.lang.String[])
*/
@Override
public Integer askMap(String[] mapList) {
IO.write("Choose a map:");
return IO.askInAList(mapList, false);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#askHost()
*/
@Override
public String askHost() {
IO.write("Type the hostname");
return IO.readString();
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#askView()
*/
@Override
public Integer askView( String[] viewList ) {
IO.write("Which view do you want to use?");
return IO.askInAList(viewList, false);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#showError(java.lang.String)
*/
@Override
public void showError(String string) {
IO.write("ERROR: " + string);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#updateLoginTime(int)
*/
@Override
public void updateLoginTime(int i) {
IO.write("Remaining time: " + i);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#updateLoginStat(int)
*/
@Override
public void updateLoginStat(int i) {
IO.write("Players online: " + i);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#switchToMainScreen(it.polimi.ingsw.game.network.GameStartInfo)
*/
@Override
public void switchToMainScreen(GameInfo container) {
mContainer = container;
mMap = container.getMap();
CLIMapRenderer.renderMap(mMap, null, null);
IO.write("Game is started! Good luck!");
IO.write("Your role is: " + (container.isHuman()?"HUMAN":"ALIEN"));
IO.write(String.format("%d players in game:", container.getPlayersList().length));
for(PlayerInfo e : container.getPlayersList())
IO.write("-> " + e.getUsername());
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#close()
*/
@Override
public void close() {
// EMPTY
}
/** Handle a map view
* @param c ViewCommand
* @param canGoBack True if user can go back
* @return True if the command is handled successfully
*/
private boolean handleEnableMapView(ViewCommand c, boolean canGoBack) {
Point newPos = null;
Point curPos = null;
int maxMoves = 0;
Set<Point> enabledCells = null;
if(c.getArgs().length > 0) {
if(c.getArgs()[0] instanceof Point)
curPos = (Point) c.getArgs()[0];
if(c.getArgs().length == 2)
maxMoves = (int) c.getArgs()[1];
}
if(maxMoves != 0)
enabledCells = mController.getMap().getCellsWithMaxDistance(curPos, maxMoves, mContainer.isHuman());
CLIMapRenderer.renderMap(mMap, curPos, enabledCells);
IO.write("Choose a position on the map" + (canGoBack?" (or type - to go back)":""));
do {
newPos = IO.askMapPos(canGoBack);
// up in the menu
if(newPos == null)
return false;
if( (enabledCells == null && mMap.isWithinBounds(newPos)) || (enabledCells != null && enabledCells.contains(newPos)))
break;
IO.write("Invalid position");
} while(true);
mController.onMapPositionChosen(newPos);
return true;
}
/** Handle a ChooseObjectCard command
* @param c ViewCommand
* @param canGoBack True if user can go back
* @return True if the command is handled successfully
*/
private boolean handleChooseObjectCard(ViewCommand c, boolean canGoBack) {
if(c.getArgs().length > 0 && c.getArgs() instanceof String[]) {
String[] objs = (String[]) c.getArgs();
IO.write("Which card do you want to use?" + (canGoBack?" (or type - to go back)":""));
Integer choice = IO.askInAList(objs, canGoBack);
if(choice == null)
return false;
mController.sendChosenObjectCard(choice);
return true;
} else
IO.write("ERROR: " + c.getArgs().length);
return false;
}
/** Handle a DiscardObjectCard Command
* @param c ViewCommand
* @param canGoBack True if user can go back
* @return True if the command is handled successfully
*/
private boolean handleDiscardObjectCard(ViewCommand c, boolean canGoBack) {
if(c.getArgs().length > 0 && c.getArgs() instanceof String[]) {
String[] objs = (String[]) c.getArgs();
IO.write("Which card do you want to discard?" + (canGoBack?" (or type - to go back)":""));
Integer i = IO.askInAList(objs, canGoBack);
if(i == null)
return false;
mController.sendDiscardObjectCard(i);
return true;
} else
IO.write("ERROR: " + c.getArgs().length);
return false;
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#handleCommand(java.util.List)
*/
@Override
protected void handleCommand(List<ViewCommand> cmd) {
ViewCommand c;
boolean loopMenu = true;
while(loopMenu) {
if(cmd.size() > 1) {
IO.write("What do you want to do now?");
int choice = IO.askInAList(cmd, false);
c = cmd.get(choice);
} else if(cmd.size() == 1) {
loopMenu = false;
c = cmd.get(0);
} else
return;
switch(c.getOpcode()) {
case CMD_ENABLEMAPVIEW:
if(handleEnableMapView(c, loopMenu)) //loopMenu == false if this is the only choice
loopMenu = false;
break;
case CMD_CHOOSEOBJECTCARD:
if(handleChooseObjectCard(c, loopMenu))
loopMenu = false;
break;
case CMD_ATTACK:
mController.attack();
loopMenu = false;
break;
case CMD_DISCARDOBJECTCARD:
if(handleDiscardObjectCard(c, loopMenu))
loopMenu = false;
break;
case CMD_DRAWDANGEROUSCARD:
mController.drawDangerousCard();
loopMenu = false;
break;
case CMD_ENDTURN:
mController.endTurn();
loopMenu = false;
break;
}
}
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#showInfo(java.lang.String, java.lang.String)
*/
@Override
public void showInfo(String user, String message) {
if(user != null)
IO.write("["+ user + "] " + message);
else
IO.write("--INFO-- " + message);
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#showNoiseInSector(java.lang.String, java.awt.Point)
*/
@Override
public void showNoiseInSector(String user, Point p) {
showInfo(user, "NOISE IN SECTOR " + mMap.pointToString(p));
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#onMyTurn()
*/
@Override
public void onMyTurn() {
showInfo(null, "It's your turn!");
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#onOtherTurn(java.lang.String)
*/
@Override
public void onOtherTurn(String username) {
showInfo(null, "It's " + username + "'s turn!");
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#showEnding(java.util.ArrayList, java.util.ArrayList)
*/
@Override
public void showEnding(List<Integer> winnerList, List<Integer> loserList) {
IO.write("*******************");
IO.write("** GAME OVER **");
IO.write("*******************\n");
if(winnerList.isEmpty())
IO.write("Nobody won this game.");
else {
IO.write("==== Winners ====");
for(Integer i : winnerList)
IO.write(" -> " + mContainer.getPlayersList()[i].getUsername());
}
if(loserList.isEmpty())
IO.write("Nobody lost this game.");
else {
IO.write("==== Losers ====");
for(Integer i : loserList)
IO.write(" -> " + mContainer.getPlayersList()[i].getUsername());
}
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#notifyObjectCardListChange(java.util.ArrayList)
*/
@Override
public void notifyObjectCardListChange(List<Integer> listOfCards) {
StringBuilder cards = new StringBuilder();
cards.append("Your object cards: ");
for(int i = 0;i < listOfCards.size(); i++) {
cards.append((i == 0? "[ " : "| "));
cards.append(ObjectCardBuilder.idToString(listOfCards.get(i)));
cards.append(" ");
}
if(listOfCards.size() == 0)
cards.append("[ YOU HAVE NO OBJECT CARDS ]");
else
cards.append("]");
IO.write(cards.toString());
}
/* (non-Javadoc)
* @see it.polimi.ingsw.client.View#updatePlayersInfoDisplay(it.polimi.ingsw.game.common.PlayerInfo, int)
*/
@Override
public void updatePlayerInfoDisplay(PlayerInfo info, int idPlayer) {
// TODO Guarda la GUI come reference per questo!
}
} |
package com.annimon.jecp;
/**
*
* @author aNNiMON
*/
public interface JecpGraphics {
public void drawLine(int x1, int y1, int x2, int y2);
public void drawRect(int x, int y, int width, int height);
public void fillRect(int x, int y, int width, int height);
public void setColor(int color);
} |
package org.flymine.ontology;
import java.util.Iterator;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.Restriction;
import com.hp.hpl.jena.ontology.HasValueRestriction;
import com.hp.hpl.jena.ontology.MaxCardinalityRestriction;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import org.flymine.metadata.FieldDescriptor;
import org.flymine.metadata.ClassDescriptor;
import org.flymine.metadata.Model;
import org.flymine.util.StringUtil;
import org.flymine.util.TypeUtil;
/**
* General purpose ontology methods.
*
* @author Andrew Varley
* @author Richard Smith
*/
public class OntologyUtil
{
/**
* the XML namespace
*/
public static final String XSD_NAMESPACE = "http://www.w3.org/2001/XMLSchema
/**
* OWL namespace.
*/
public static final String OWL_NAMESPACE = "http://www.w3.org/2002/07/owl
/**
* RDF namespace.
*/
public static final String RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns
/**
* RDFS namespace
*/
public static final String RDFS_NAMESPACE = "http://www.w3.org/2000/01/rdf-schema
private OntologyUtil() {
}
/**
* Generate a name for a property in OntModel, this takes the form:
* <namespace>#<classname>__<fieldname>.
* @param fld field to create property name for
* @return the new property name
*/
public static String generatePropertyName(FieldDescriptor fld) {
ClassDescriptor cld = fld.getClassDescriptor();
return cld.getModel().getNameSpace()
+ TypeUtil.unqualifiedName(cld.getName()) + "__" + fld.getName();
}
/**
* Generate a name for a property in OntModel, this takes the form:
* <namespace>#<classname>__<propertyname>.
* @param prop property to generate name for
* @param domain the domain of this property
* @return the new property name
*/
public static String generatePropertyName(OntProperty prop, Resource domain) {
String propName = prop.getLocalName();
if (propName.indexOf("__") > 0) {
propName = propName.substring(propName.indexOf("__") + 2);
}
return domain.getLocalName() + "__" + propName;
}
/**
* Generate a name for a property given namespace, clasname and property name strings
* <namespace>#<classname>__<propertyname>.
* @param ns namespace
* @param domain the domain name of this property
* @param prop the property name
* @return the new property name
*/
public static String generatePropertyName(String ns, String domain, String prop) {
return correctNamespace(ns) + domain + "__" + prop;
}
/**
* Strip <classname>_ from the beginning of a property name, if not present then
* return name as is.
* @param prop property to generate field name for
* @param domain the domain of this property
* @return the new field name
*/
public static String generateFieldName(OntProperty prop, OntResource domain) {
String name = prop.getLocalName();
if (name.indexOf("__") > 0) {
String start = name.substring(0, name.indexOf("__"));
if (start.equals(domain.getLocalName())) {
return name.substring(name.indexOf("__") + 2);
}
}
return name;
}
/**
* Return an XML datatype given a java string describing a java type.
* @param javaType string describing a fully qualified java type.
* @return a string describing and XML data type
*/
public static String javaToXmlType(String javaType) {
if (javaType.equals("java.lang.String")) {
return OntologyUtil.XSD_NAMESPACE + "string";
} else if (javaType.equals("java.lang.Integer") || javaType.equals("int")) {
return OntologyUtil.XSD_NAMESPACE + "integer";
} else if (javaType.equals("java.lang.Short") || javaType.equals("short")) {
return OntologyUtil.XSD_NAMESPACE + "short";
} else if (javaType.equals("java.lang.Long") || javaType.equals("long")) {
return OntologyUtil.XSD_NAMESPACE + "long";
} else if (javaType.equals("java.lang.Double") || javaType.equals("double")) {
return OntologyUtil.XSD_NAMESPACE + "double";
} else if (javaType.equals("java.lang.Float") || javaType.equals("float")) {
return OntologyUtil.XSD_NAMESPACE + "float";
} else if (javaType.equals("java.lang.Boolean") || javaType.equals("boolean")) {
return OntologyUtil.XSD_NAMESPACE + "boolean";
} else if (javaType.equals("java.lang.Byte") || javaType.equals("byte")) {
return OntologyUtil.XSD_NAMESPACE + "byte";
} else if (javaType.equals("java.net.URL")) {
return OntologyUtil.XSD_NAMESPACE + "anyURI";
} else if (javaType.equals("java.util.Date")) {
return (OntologyUtil.XSD_NAMESPACE + "dateTime");
} else if (javaType.equals("java.math.BigDecimal")) {
return (OntologyUtil.XSD_NAMESPACE + "bigDecimal");
} else {
throw new IllegalArgumentException("Unrecognised Java type: " + javaType);
}
}
public static String xmlToJavaType(String xmlType) throws IllegalArgumentException {
if (xmlType.equals("string") || xmlType.equals("normalizedString")
|| xmlType.equals("language") || xmlType.equals("Name") || xmlType.equals("NCName")) {
return "java.lang.String";
} else if (xmlType.equals("positiveInteger") || xmlType.equals("negativeInteger")
|| xmlType.equals("int") || xmlType.equals("nonNegativeInteger")
|| xmlType.equals("unsignedInt") || xmlType.equals("integer")
|| xmlType.equals("nonPositiveInteger")) {
return "java.lang.Integer";
} else if (xmlType.equals("short") || xmlType.equals("unsignedShort")) {
return "java.lang.Short";
} else if (xmlType.equals("long") || xmlType.equals("unsignedLong")) {
return "java.lang.Long";
} else if (xmlType.equals("byte") || xmlType.equals("unsignedByte")) {
return "java.lang.Byte";
} else if (xmlType.equals("float") || xmlType.equals("decimal")) {
return "java.lang.Float";
} else if (xmlType.equals("double")) {
return "java.lang.Double";
} else if (xmlType.equals("boolean")) {
return "java.lang.Boolean";
} else if (xmlType.equals("anyURI")) {
return "java.net.URL";
} else if (xmlType.equals("dateTime")) {
return "java.util.Date";
} else if (xmlType.equals("bigDecimal")) {
return "java.math.BigDecimal";
} else {
throw new IllegalArgumentException("Unrecognised XML data type: " + xmlType);
}
}
/**
* Return true if there is a maxCardinalityRestriction of 1 on this property for
* given domain (note that properties can have more than one domain).
* @param model the Ontolgoy model
* @param prop the property to check for cardinality restriction
* @param domain the specific domain of the restriction
* @return true if maxCardinality restriction 1 exists
*/
public static boolean hasMaxCardinalityOne(OntModel model, OntProperty prop,
OntResource domain) {
Iterator iter = model.listRestrictions();
while (iter.hasNext()) {
Restriction res = (Restriction) iter.next();
if (res.hasSubClass(domain) && res.onProperty(prop)
&& res.isMaxCardinalityRestriction()) {
return true;
}
}
return false;
}
/**
* For the given OntClass get a set of subclasses with a hasValue restriction
* on a particular DatatypeProperty. May have to follow ObjectProperties to
* other classes to find the restricted DatatypeProperty. srcCls may be from a
* different OntModel, use this class to find properties, look in given model for
* subclasses. If srcCls is from given model then this is no different.
* @param model the ontology model to search for subclasses in
* @param srcCls the OntClass to find restricted subclasses for
* @return a set of subclasses with a hasValue Restriction
*/
public static Set findRestrictedSubclasses(OntModel model, OntClass srcCls) {
return findRestrictedSubclasses(model, srcCls, null);
}
/**
* For the given OntClass get a set of subclasses with a hasValue restriction
* on a particular DatatypeProperty. May have to follow ObjectProperties to
* other classes to find the restricted DatatypeProperty, if so method is recursed
* but retains original subclass in 'top' parameter. srcCls may be from a different
* OntModel, use this class to find properties, look in given model for subclasses.
* If srcCls is from given model then this is no different.
* @param model the ontology model to search for subclasses in
* @param srcCls the OntClass to find restricted subclasses for
* @param top if nested call made to this method, the highest level subclass found,
* null on first call.
* @return a set of subclasses with a hasValue Restriction
*/
protected static Set findRestrictedSubclasses(OntModel model, OntClass srcCls, OntClass top) {
OntClass tgtCls = model.getOntClass(srcCls.getURI());
Set subclasses = new HashSet();
ExtendedIterator i = tgtCls.listSubClasses();
while (i.hasNext()) {
OntClass subcls = (OntClass) i.next();
ExtendedIterator j = subcls.listSuperClasses(true);
while (j.hasNext()) {
OntResource tmp = (OntResource) j.next();
Restriction res = null;
if (tmp.canAs(Restriction.class)) {
res = (Restriction) tmp.as(Restriction.class);
}
if (res != null && res.isHasValueRestriction()) {
ExtendedIterator propIter = srcCls.listDeclaredProperties(false);
while (propIter.hasNext()) {
OntProperty prop = (OntProperty) propIter.next();
if (res.onProperty(prop) && isDatatypeProperty(prop)) {
if (top != null && !top.isAnon()) {
subclasses.add(top);
} else if (!subcls.isAnon()) {
subclasses.add(subcls);
}
} else if (res.onProperty(prop) && isObjectProperty(prop)) {
OntResource range = prop.getRange();
if (range.canAs(OntClass.class)
&& (range.getNameSpace().equals(srcCls.getNameSpace())
|| range.getNameSpace().equals(tgtCls.getNameSpace()))) {
if (top != null) {
subclasses.addAll(findRestrictedSubclasses(model,
range.asClass(), top));
} else {
subclasses.addAll(findRestrictedSubclasses(model,
range.asClass(), subcls));
}
}
}
}
propIter.close();
}
}
j.close();
}
i.close();
return subclasses;
}
/**
* Create a map of class URI -> restricted subclass URIs
* @param model the model to process
* @return restricted subclass map
*/
public static Map getRestrictedSubclassMap(OntModel model) {
Set restrictions = new HashSet();
ExtendedIterator resIter = model.listRestrictions();
while (resIter.hasNext()) {
Restriction res = (Restriction) resIter.next();
if (res.isHasValueRestriction()) {
restrictions.add(res);
}
}
resIter.close();
Set hasValueClasses = new HashSet();
ExtendedIterator clsIter = model.listClasses();
while (clsIter.hasNext()) {
OntClass cls = (OntClass) clsIter.next();
if (!cls.isAnon()) {
ExtendedIterator superIter = cls.listSuperClasses(true); // direct
boolean added = false;
while (superIter.hasNext() && !added) {
if (restrictions.contains((Resource) superIter.next())) {
hasValueClasses.add(cls);
added = true;
}
}
superIter.close();
}
}
clsIter.close();
Set candidates = new HashSet();
Iterator candIter = hasValueClasses.iterator();
while (candIter.hasNext()) {
OntClass cls = (OntClass) candIter.next();
ExtendedIterator superIter = cls.listSuperClasses(true); // direct
while (superIter.hasNext()) {
Resource candidate = (Resource) superIter.next();
if (!candidate.isAnon() && candidate.canAs(OntClass.class)) {
candidates.add((OntClass) candidate.as(OntClass.class));
}
}
superIter.close();
}
Map classesMap = new HashMap();
Iterator i = candidates.iterator();
while (i.hasNext()) {
OntClass cls = (OntClass) i.next();
Set subs = OntologyUtil.findRestrictedSubclasses(model, cls);
if (subs.size() > 0) {
classesMap.put(cls, subs);
}
}
return classesMap;
}
/**
* Use model to build a map from class URI to all possible SubclassRestriction templates
* (where a template is defined as a SubclassRestriction with null values for
* each path expression.
* @param model the model to examine
* @param classesMap restricted subclass map
* @return a map of class URI to possible SubclassRestriction templates
*/
public static Map getRestrictionSubclassTemplateMap(OntModel model, Map classesMap) {
Map srMap = new HashMap();
Iterator i = classesMap.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
OntClass cls = (OntClass) e.getKey();
Iterator j = ((Set) e.getValue()).iterator();
Set srs = new TreeSet(new SubclassRestrictionComparator());
while (j.hasNext()) {
OntClass sub = (OntClass) j.next();
// no values in SubclassRestrictions so any that operate on same paths
// will be .equals()
srs.add(createSubclassRestriction(model, sub, cls.getLocalName(), null, false));
srMap.put(cls.getURI(), srs);
}
}
return srMap;
}
/**
* Build a map from SubclassRetriction objects (with values filled in) to
* URI of restricted subclass that this defines.
* @param model the ontology model to process
* @param classesMap restricted subclass map
* @return map from SubclassRestriction to class URI
*/
public static Map getRestrictionSubclassMap(OntModel model, Map classesMap) {
// create a map of SubclassRestriction objects to restricted subclass URIs
Map restrictionMap = new HashMap();
Iterator i = classesMap.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
OntClass cls = (OntClass) e.getKey();
Iterator j = ((Set) e.getValue()).iterator();
while (j.hasNext()) {
OntClass sub = (OntClass) j.next();
SubclassRestriction sr = createSubclassRestriction(model, sub,
cls.getLocalName(), null, true);
if (sr.hasRestrictions()) {
restrictionMap.put(sr, sub.getURI());
}
}
}
return restrictionMap;
}
/**
* Examine ontology model to create a SubclassRestriction object describing reference/attribute
* values that defined the given restriced subclass. Recurses to follow nested retrictions.
* @param model the model to process
* @param cls a restricted subclass to create description of
* @param path expression descriping path from superclass to current class
* @param sr partially created SubclassRestriction (when recursing) null initially
* @param values if true fill in values of attributes, otherwise just create template
* @return a description of the given restricted subclass
*/
protected static SubclassRestriction createSubclassRestriction(OntModel model, OntClass cls,
String path, SubclassRestriction sr, boolean values) {
if (sr == null) {
sr = new SubclassRestriction();
}
ExtendedIterator i = model.listRestrictions();
while (i.hasNext()) {
Restriction res = (Restriction) i.next();
if (res.hasSubClass(cls, true) && res.isHasValueRestriction()) {
ExtendedIterator j = cls.listDeclaredProperties(true);
while (j.hasNext()) {
OntProperty prop = (OntProperty) j.next();
if (res.onProperty(prop)) {
if (prop.getLocalName().indexOf("__") == -1) {
throw new IllegalArgumentException("Attribute name '"
+ prop.getLocalName()
+ "' is not of form "
+ "'className__propertyName'");
}
String newPath = path + "." + prop.getLocalName().split("__")[1];
if (isDatatypeProperty(prop)) {
// add path/value restriction to SubclassRestriction
RDFNode node = ((HasValueRestriction) res.as(HasValueRestriction.class))
.getHasValue();
sr.addRestriction(newPath, values ? ((Literal) node.as(Literal.class))
.getValue() : null);
} else if (isObjectProperty(prop)) {
OntResource range = prop.getRange();
if (range.canAs(OntClass.class)) {
RDFNode node = ((HasValueRestriction) res
.as(HasValueRestriction.class)).getHasValue();
OntClass hv = (OntClass) node.as(OntClass.class);
createSubclassRestriction(model, hv, newPath, sr, values);
}
}
}
}
j.close();
}
}
i.close();
return sr;
}
/**
* Prepare format of OWL properties for generation of a FlyMine model:
* a) change names of properties to be <domain>__<property>.
* b) if multiple ranges that inherit from one another choose correct one
* @param model the model to alter proerties in
* @param ns the namespace within model that we are interested in
* @throws Exception if property has invalid range
*/
public static void reorganiseProperties(OntModel model, String ns) throws Exception {
// get set of all properties, excluding those defined as owl:inverseOf
Set props = new HashSet();
Iterator propIter = model.listOntProperties();
while (propIter.hasNext()) {
OntProperty prop = (OntProperty) propIter.next();
if (prop.getNameSpace().equals(ns) && prop.getInverseOf() == null) {
props.add(prop);
}
}
propIter = props.iterator();
while (propIter.hasNext()) {
OntProperty prop = (OntProperty) propIter.next();
OntProperty newProp = null;
String newPropName = ns + generatePropertyName(prop, prop.getDomain());
if (newPropName.equals(prop.getURI())) {
newProp = prop;
prop.setRange(pickRange(prop));
} else {
newProp = renameProperty(prop, prop.getDomain(), model, ns);
prop.remove();
}
}
// propIter = props.iterator();
// while (propIter.hasNext()) {
// OntProperty prop = (OntProperty) propIter.next();
// OntProperty newProp = renameProperty(prop, prop.getDomain(), model, ns);
// if (!newProp.getURI().equals(prop.getURI())) {
// prop.remove();
}
/**
* Change the name of a property to be <domainName>__<propertyName> and
* update any references to the property (e.g. Restrictions) with respect
* to change. Apply property (recurse) to any direct subclasses of domain.
* @param prop the property to change name of
* @param domain the domain of the property
* @param model parent OntModel
* @param ns namespace to create property name in
* @return the renamed property
* @throws Exception if property has invalid range
*/
protected static OntProperty renameProperty(OntProperty prop, OntResource domain,
OntModel model, String ns) throws Exception {
OntProperty newProp;
if (isObjectProperty(prop)) {
newProp = model.createObjectProperty(ns + generatePropertyName(prop, domain));
} else {
newProp = model.createDatatypeProperty(ns + generatePropertyName(prop, domain));
}
newProp.setDomain(domain);
if (prop.getInverseOf() != null) {
newProp.setRange(prop.getInverseOf().getDomain());
} else {
newProp.setRange(pickRange(prop));
}
transferEquivalenceStatements(prop, newProp, model);
Iterator labelIter = prop.listLabels(null);
while (labelIter.hasNext()) {
newProp.addLabel(((Literal) labelIter.next()).getString(), null);
}
// deal with restrictions on property
Set restrictions = new HashSet();
Iterator r = ((OntClass) prop.getDomain().as(OntClass.class)).listSuperClasses(true);
while (r.hasNext()) {
OntResource res = (OntResource) r.next();
if (res.canAs(Restriction.class)
&& ((Restriction) res.as(Restriction.class)).onProperty(prop)) {
restrictions.add((Restriction) res.as(Restriction.class));
}
}
((ExtendedIterator) r).close();
r = restrictions.iterator();
while (r.hasNext()) {
Restriction res = (Restriction) r.next();
// if just changing name of property just set onProperty
if (domain.equals(prop.getDomain())) {
res.setOnProperty(newProp);
} else if (res.isMaxCardinalityRestriction()
&& !hasMaxCardinalityOne(model, newProp, domain)) {
Restriction newRes = model.createMaxCardinalityRestriction(null, newProp,
((MaxCardinalityRestriction) res.as(MaxCardinalityRestriction.class))
.getMaxCardinality());
((OntClass) domain.as(OntClass.class)).addSuperClass(newRes);
}
}
// apply property to direct subclasses
//if (domain.canAs(OntClass.class)) {
// Iterator subIter = ((OntClass) domain.as(OntClass.class)).listSubClasses(true);
// while (subIter.hasNext()) {
// newProp.addSubProperty(renameProperty(newProp, (OntResource) subIter.next(),
// model, ns));
return newProp;
}
/**
* Return true if the given OntProperty has more than one defined domain.
* @param prop the OntProperty to examine
* @return true if prop has more than one domain
*/
public static boolean hasMultipleDomains(OntProperty prop) {
Iterator i = prop.listDomain();
i.next();
return i.hasNext();
}
/**
* Return true if the given OntProperty has more than one defined range.
* @param prop the OntProperty to examine
* @return true if prop has more than one range
*/
public static boolean hasMultipleRanges(OntProperty prop) {
Iterator i = prop.listRange();
i.next();
return i.hasNext();
}
/**
* If property has multiple ranges that inherit from one another return the highest
* in inheritance hierarchy. If ranges do not all inherit from one another,
* throw an Exception.
* @param prop property to examine
* @return the chosen range
* @throws Exception if ranges are invalid
*/
public static Resource pickRange(OntProperty prop) throws Exception {
if (hasMultipleRanges(prop)) {
OntClass cls = null;
ExtendedIterator i = prop.listRange();
while (i.hasNext()) {
RDFNode node = (RDFNode) i.next();
if (node instanceof Resource && ((Resource) node).canAs(OntClass.class)) {
OntClass current = (OntClass) node.as(OntClass.class);
if (cls == null) {
cls = current;
} else if (current.hasSubClass(cls, false)) {
cls = current;
} else if (!(current.equals(cls)) && !(cls.hasSubClass(current, false))) {
throw new Exception("Property (" + prop.getURI()
+ ") has ranges that are not compatible.");
}
} else {
throw new Exception("Property (" + prop.getURI() + ") has more than one range");
}
}
i.close();
return cls;
}
return prop.getRange();
}
/**
* Move equivalence statements from one property to another, removes statements
* from original property.
* @param prop proprty to transfer statements from
* @param newProp target property to transfer statements to
* @param model the parent OntModel
*/
protected static void transferEquivalenceStatements(OntProperty prop, OntProperty
newProp, OntModel model) {
List statements = new ArrayList();
Iterator i = model.listStatements();
while (i.hasNext()) {
Statement stmt = (Statement) i.next();
if (!stmt.getSubject().isAnon() && stmt.getSubject().getURI().equals(prop.getURI())
&& stmt.getPredicate().getURI().equals(OWL_NAMESPACE + "equivalentProperty")) {
statements.add(model.createStatement(newProp, stmt.getPredicate(),
stmt.getObject()));
}
}
model.add(statements);
}
/**
* Build a map of resources in source namespaces to the equivalent resources
* in target namespace.
* @param model an OWL model specifying mapping
* @return mappings between source and target namespaces
*/
public static Map buildEquivalenceMap(OntModel model) {
return buildEquivalenceMap(model, null);
}
/**
* Build a map of resource URIs in source namespaces to equivalent resources
* in target namespace if defined in model. Only include equivalence to srcNs
* if parameter is not null.
* @param model an OWL model specifying mapping
* @param srcNs only include statements in this namespace, can be null
* @return mappings between source and target namespaces
*/
public static Map buildEquivalenceMap(OntModel model, String srcNs) {
Map equivMap = new HashMap();
Iterator stmtIter = model.listStatements();
while (stmtIter.hasNext()) {
Statement stmt = (Statement) stmtIter.next();
if (stmt.getPredicate().getLocalName().equals("equivalentClass")
|| stmt.getPredicate().getLocalName().equals("equivalentProperty")
|| stmt.getPredicate().getLocalName().equals("sameAs")) {
Resource res = stmt.getResource();
if (srcNs == null) {
equivMap.put(res.getURI(), stmt.getSubject().getURI());
} else if (res.getNameSpace().equals(srcNs)) {
equivMap.put(res.getURI(), stmt.getSubject().getURI());
}
// uncomment this code for mapping one source class to more than one target
// if (equivMap.containsKey(res.getURI())) {
// Object obj = equivMap.get(res.getURI());
// if (!(obj instanceof HashSet)) {
// obj = new HashSet();
// ((Set) obj).add(equivMap.get(res.getURI()));
// equivMap.put(res.getURI(), obj);
// ((Set) obj).add(stmt.getSubject().getURI());
}
}
return equivMap;
}
/**
* Test whether a OntProperty is a datatype property - if type of property
* is not owl:DatatypeProperty checks if object is a literal or a Resource
* that is an xml datatype.
* @param prop the property in question
* @return true if is a DatatypeProperty
*/
public static boolean isDatatypeProperty(Property prop) {
if (prop instanceof OntProperty && ((OntProperty) prop).isDatatypeProperty()) {
return true;
}
Statement stmt = (Statement) getStatementsFor((OntModel) prop.getModel(), prop,
RDFS_NAMESPACE + "range").iterator().next();
if (stmt.getObject() instanceof Literal) {
return true;
} else if (stmt.getObject() instanceof Resource) {
Resource res = (Resource) stmt.getObject();
if (res.getNameSpace().equals(XSD_NAMESPACE)) {
return true;
}
}
return false;
}
/**
* Test whether a given property is an object property. If type of property
* is not owl:ObjectProperty establishes whether it is a DatatypeProperty.
* @param prop the property in question
* @return true if this is an ObejctProperty
*/
public static boolean isObjectProperty(Property prop) {
if (prop instanceof OntProperty && ((OntProperty) prop).isObjectProperty()) {
return true;
}
return !isDatatypeProperty(prop);
}
/**
* Return a set of jena rdf statement objects from model for given subject and predicate.
* @param model the OntModel to search for statements
* @param subject subject of the desired statements
* @param predicate predicate of the desired statements
* @return a set of Statement objects
*/
public static Set getStatementsFor(OntModel model, Resource subject, String predicate) {
Set statements = new HashSet();
Iterator stmtIter = model.listStatements();
while (stmtIter.hasNext()) {
Statement stmt = (Statement) stmtIter.next();
if (stmt.getSubject().equals(subject)
&& stmt.getPredicate().getURI().equals(predicate)) {
statements.add(stmt);
}
}
return statements;
}
/**
* Return the namespace portion of URI string (i.e. everything before a #).
* @param uri a uri string
* @return the namespace or original uri if no # present
*/
public static String getNamespaceFromURI(String uri) {
if (uri.indexOf('
return uri.substring(0, uri.indexOf('
}
return uri;
}
/**
* Return the fragment portion of a URI string (i.e. everything after a #).
* @param uri a uri string
* @return the fragment or original uri if no # present
*/
public static String getFragmentFromURI(String uri) {
if (uri.indexOf('
return uri.substring(uri.indexOf('
}
return uri;
}
/**
* If a given namespace uri does not end in a '#' add one, rmoving trailing '/' if present.
* @param ns the namespace uri
* @return the corrected namespace
*/
public static String correctNamespace(String ns) {
if (ns.indexOf('
return ns.substring(0, ns.indexOf('
} else if (ns.endsWith("/")) {
return ns.substring(0, ns.length() - 1) + "
} else {
return ns + "
}
}
/**
* Return a valid resource given a resource name fragment, currently just replaces
* spaces with underscores.
* @param fragment fragment part of a resource name uri
* @return a valid resource name fragment
*/
public static String validResourceName(String fragment) {
return fragment.replace(' ', '_');
}
/**
* Generate a package qualified class name within the specified model from a space separated
* list of namespace qualified names
*
* @param classNames the list of namepace qualified names
* @param model the relevant model
* @return the package qualified names
*/
public static String generateClassNames(String classNames, Model model) {
if (classNames == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (Iterator i = StringUtil.tokenize(classNames).iterator(); i.hasNext();) {
sb.append(model.getPackageName() + "." + getFragmentFromURI((String) i.next()) + " ");
}
return sb.toString().trim();
}
} |
package com.kii.iotcloud;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Pair;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import com.google.gson.JsonParseException;
import com.kii.iotcloud.command.Action;
import com.kii.iotcloud.command.ActionResult;
import com.kii.iotcloud.command.Command;
import com.kii.iotcloud.exception.IoTCloudException;
import com.kii.iotcloud.exception.IoTCloudRestException;
import com.kii.iotcloud.exception.StoredIoTCloudAPIInstanceNotFoundException;
import com.kii.iotcloud.exception.UnsupportedActionException;
import com.kii.iotcloud.exception.UnsupportedSchemaException;
import com.kii.iotcloud.internal.GsonRepository;
import com.kii.iotcloud.internal.http.IoTRestClient;
import com.kii.iotcloud.internal.http.IoTRestRequest;
import com.kii.iotcloud.schema.Schema;
import com.kii.iotcloud.trigger.Predicate;
import com.kii.iotcloud.trigger.Trigger;
import com.kii.iotcloud.internal.utils.JsonUtils;
import com.kii.iotcloud.internal.utils.Path;
import com.squareup.okhttp.MediaType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class operates an IoT device that is specified by {@link #onboard(String, String, String, JSONObject)} method.
*/
public class IoTCloudAPI implements Parcelable {
private static final String SHARED_PREFERENCES_KEY_INSTANCE = "IoTCloudAPI_INSTANCE";
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
private static final MediaType MEDIA_TYPE_INSTALLATION_CREATION_REQUEST = MediaType.parse("application/vnd.kii.InstallationCreationRequest+json");
private static final MediaType MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST = MediaType.parse("application/vnd.kii.OnboardingWithThingIDByOwner+json");
private static final MediaType MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST = MediaType.parse("application/vnd.kii.OnboardingWithVendorThingIDByOwner+json");
private static Context context;
private final String tag;
private final String appID;
private final String appKey;
private final String baseUrl;
private final Owner owner;
private Target target;
private final Map<Pair<String, Integer>, Schema> schemas = new HashMap<Pair<String, Integer>, Schema>();
private final IoTRestClient restClient;
private String installationID;
public static IoTCloudAPI loadFromStoredInstance(@NonNull Context context) throws StoredIoTCloudAPIInstanceNotFoundException {
return loadFromStoredInstance(context, null);
}
public static IoTCloudAPI loadFromStoredInstance(@NonNull Context context, String tag) throws StoredIoTCloudAPIInstanceNotFoundException {
IoTCloudAPI.context = context.getApplicationContext();
SharedPreferences preferences = getSharedPreferences();
String serializedJson = preferences.getString(getSharedPreferencesKey(tag), null);
if (serializedJson != null) {
return GsonRepository.gson().fromJson(serializedJson, IoTCloudAPI.class);
}
throw new StoredIoTCloudAPIInstanceNotFoundException(tag);
}
private static void saveInstance(IoTCloudAPI instance) {
SharedPreferences preferences = getSharedPreferences();
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getSharedPreferencesKey(instance.tag), GsonRepository.gson().toJson(instance));
editor.apply();
}
}
private static String getSharedPreferencesKey(String tag) {
return SHARED_PREFERENCES_KEY_INSTANCE + (tag == null ? "" : "_" +tag);
}
IoTCloudAPI(
@Nullable Context context,
@Nullable String tag,
@NonNull String appID,
@NonNull String appKey,
@NonNull String baseUrl,
@NonNull Owner owner,
@Nullable Target target,
@NonNull List<Schema> schemas,
String installationID) {
// Parameters are checked by IoTCloudAPIBuilder
if (context != null) {
IoTCloudAPI.context = context.getApplicationContext();
}
this.tag = tag;
this.appID = appID;
this.appKey = appKey;
this.baseUrl = baseUrl;
this.owner = owner;
this.target = target;
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.installationID = installationID;
this.restClient = new IoTRestClient();
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String vendorThingID,
@NonNull String thingPassword,
@Nullable String thingType,
@Nullable JSONObject thingProperties)
throws IoTCloudException {
if (this.onboarded()) {
throw new IllegalStateException("This instance is already onboarded.");
}
if (TextUtils.isEmpty(vendorThingID)) {
throw new IllegalArgumentException("vendorThingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("vendorThingID", vendorThingID);
requestBody.put("thingPassword", thingPassword);
if (thingType != null) {
requestBody.put("thingType", thingType);
}
if (thingProperties != null && thingProperties.length() > 0) {
requestBody.put("thingProperties", thingProperties);
}
requestBody.put("owner", this.owner.getID().toString());
} catch (JSONException e) {
}
return this.onboard(MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST, requestBody);
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String thingID,
@NonNull String thingPassword) throws
IoTCloudException {
if (this.onboarded()) {
throw new IllegalStateException("This instance is already onboarded.");
}
if (TextUtils.isEmpty(thingID)) {
throw new IllegalArgumentException("thingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("thingID", thingID);
requestBody.put("thingPassword", thingPassword);
requestBody.put("owner", this.owner.getID().toString());
} catch (JSONException e) {
}
return this.onboard(MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST, requestBody);
}
private Target onboard(MediaType contentType, JSONObject requestBody) throws IoTCloudException {
String path = MessageFormat.format("/iot-api/apps/{0}/onboardings", this.appID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, contentType, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String thingID = responseBody.optString("thingID", null);
String accessToken = responseBody.optString("accessToken", null);
this.target = new Target(new TypedID(TypedID.Types.THING, thingID), accessToken);
saveInstance(this);
return this.target;
}
/**
* Checks whether on boarding is done.
* @return true if done, otherwise false.
*/
public boolean onboarded()
{
return this.target != null;
}
/**
* Install push notification to receive notification from IoT Cloud.
* IoT Cloud will send notification when the Target replies to the Command.
* Application can receive the notification and check the result of Command
* fired by Application or registered Trigger.
* After installation is done Installation ID is managed in this class.
* @param deviceToken for GCM, specify token obtained by
* InstanceID.getToken().
* for JPUSH, specify id obtained by
* JPushInterface.getUdid().
* @param pushBackend Specify backend to use.
* @return Installation ID used in IoT Cloud.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public String installPush(
@Nullable String deviceToken,
@NonNull PushBackend pushBackend
) throws IoTCloudException {
if (pushBackend == null) {
throw new IllegalArgumentException("pushBackend is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations", this.appID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
try {
if (!TextUtils.isEmpty(deviceToken)) {
requestBody.put("installationRegistrationID", deviceToken);
}
requestBody.put("deviceType", pushBackend.getDeviceType());
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_INSTALLATION_CREATION_REQUEST, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
this.installationID = responseBody.optString("installationID", null);
saveInstance(this);
return this.installationID;
}
/**
* Get installationID if the push is already installed.
* null will be returned if the push installation has not been done.
* @return Installation ID used in IoT Cloud.
*/
@Nullable
public String getInstallationID() {
return this.installationID;
}
void setInstallationID(String installationID) {
this.installationID = installationID;
}
/**
* Uninstall push notification.
* After done, notification from IoT Cloud won't be notified.
* @param installationID installation ID returned from
* {@link #installPush(String, PushBackend)}
* if null is specified, value obtained by
* {@link #getInstallationID()} is used.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public void uninstallPush(@NonNull String installationID) throws IoTCloudException {
if (installationID == null) {
throw new IllegalArgumentException("installationID is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations/{1}", this.appID, installationID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
}
/**
* Post new command to IoT Cloud.
* Command will be delivered to specified target and result will be notified
* through push notification.
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Actions to be executed.
* @return Created Command instance. At this time, Command is delivered to
* the target Asynchronously and may not finished. Actual Result will be
* delivered through push notification or you can check the latest status
* of the command by calling {@link #getCommand}.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Command postNewCommand(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions) throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
Command command = new Command(schemaName, schemaVersion, this.owner.getID(), actions);
JSONObject requestBody = JsonUtils.newJson(GsonRepository.gson(schema).toJson(command));
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String commandID = responseBody.optString("commandID", null);
return this.getCommand(commandID);
}
/**
* Get specified command.
* @param commandID ID of the command to obtain. ID is present in the
* instance returned by {@link #postNewCommand}
* and can be obtained by {@link Command#getCommandID}
*
* @return Command instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Command getCommand(
@NonNull String commandID)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(commandID)) {
throw new IllegalArgumentException("commandID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands/{2}", this.appID, this.target.getID().toString(), commandID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
String schemaName = responseBody.optString("schema", null);
int schemaVersion = responseBody.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
return this.deserialize(schema, responseBody, Command.class);
}
/**
* List Commands in the specified Target.
* @param bestEffortLimit Maximum number of the Commands in the response.
* if the value is <= 0, default limit internally
* defined is applied.
* Meaning of 'bestEffort' is if the specified limit
* is greater than default limit, default limit is
* applied.
* @param paginationKey Used to get the next page of previously obtained.
* If there is further page to obtain, this method
* returns paginationKey as the 2nd element of pair.
* Applying this key to the argument results continue
* to get the result from the next page.
* @return 1st Element is Commands belongs to the Target. 2nd element is
* paginationKey if there is next page to be obtained.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
public Pair<List<Command>, String> listCommands (
int bestEffortLimit,
@Nullable String paginationKey)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/commands", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray commandArray = responseBody.optJSONArray("commands");
List<Command> commands = new ArrayList<Command>();
if (commandArray != null) {
for (int i = 0; i < commandArray.length(); i++) {
JSONObject commandJson = commandArray.optJSONObject(i);
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
commands.add(this.deserialize(schema, commandJson, Command.class));
}
}
return new Pair<List<Command>, String>(commands, nextPaginationKey);
}
/**
* Post new Trigger to IoT Cloud.
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Specify actions included in the Command is fired by the
* trigger.
* @param predicate Specify when the Trigger fires command.
* @return Instance of the Trigger registered in IoT Cloud.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger postNewTrigger(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions,
@NonNull Predicate predicate)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, this.target.getID(), this.owner.getID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String triggerID = responseBody.optString("triggerID", null);
return this.getTrigger(triggerID);
}
/**
* Get specified Trigger.
* @param triggerID ID of the Trigger to get.
* @return Trigger instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Trigger getTrigger(
@NonNull String triggerID)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, this.target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
JSONObject commandObject = responseBody.optJSONObject("command");
String schemaName = commandObject.optString("schema", null);
int schemaVersion = commandObject.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
return this.deserialize(schema, responseBody, Trigger.class);
}
@NonNull
@WorkerThread
public Trigger patchTrigger(
@NonNull String triggerID,
@NonNull String schemaName,
int schemaVersion,
@Nullable List<Action> actions,
@Nullable Predicate predicate) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, this.target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, this.target.getID(), this.owner.getID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PATCH, headers, MEDIA_TYPE_JSON, requestBody);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Enable/Disable registered Trigger
* If its already enabled(/disabled),
* this method won't throw Exception and behave as succeeded.
* @param triggerID ID of the Trigger to be enabled(/disabled).
* @param enable specify whether enable of disable the Trigger.
* @return Updated Trigger Instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger enableTrigger(
@NonNull String triggerID,
boolean enable)
throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}/{3}", this.appID, this.target.getID().toString(), triggerID, (enable ? "enable" : "disable"));
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Delete the specified Trigger.
* @param triggerID ID of the Trigger to be deleted.
* @return Deleted Trigger Instance.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger deleteTrigger(
@NonNull String triggerID) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
Trigger trigger = this.getTrigger(triggerID);
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers/{2}", this.appID, target.getID().toString(), triggerID);
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
return trigger;
}
/**
* List Triggers belongs to the specified Target.
* @param bestEffortLimit limit the maximum number of the Triggers in the
* Response. It ensures numbers in
* response is equals to or less than specified number.
* But doesn't ensures number of the Triggers
* in the response is equal to specified value.<br>
* If the specified value <= 0, Default size of the limit
* is applied by IoT Cloud.
* @param paginationKey If specified obtain rest of the items.
* @return first is list of the Triggers and second is paginationKey returned
* by IoT Cloud. paginationKey is null when there is next page to be obtained.
* Obtained paginationKey can be used to get the rest of the items stored
* in the target.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Pair<List<Trigger>, String> listTriggers(
int bestEffortLimit,
@Nullable String paginationKey) throws
IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/triggers", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray triggerArray = responseBody.optJSONArray("triggers");
List<Trigger> triggers = new ArrayList<Trigger>();
if (triggerArray != null) {
for (int i = 0; i < triggerArray.length(); i++) {
JSONObject triggerJson = triggerArray.optJSONObject(i);
JSONObject commandJson = triggerJson.optJSONObject("command");
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
triggers.add(this.deserialize(schema, triggerJson, Trigger.class));
}
}
return new Pair<List<Trigger>, String>(triggers, nextPaginationKey);
}
/**
* Get the State of specified Target.
* State will be serialized with Gson library.
* @param classOfS Specify class of the State.
* @param <S> State class.
* @return Instance of Target State.
* @throws IoTCloudException Thrown when failed to connect IoT Cloud Server.
* @throws IoTCloudRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public <S extends TargetState> S getTargetState(
@NonNull Class<S> classOfS) throws IoTCloudException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (classOfS == null) {
throw new IllegalArgumentException("classOfS is null");
}
String path = MessageFormat.format("/iot-api/apps/{0}/targets/{1}/states", this.appID, this.target.getID().toString());
String url = Path.combine(this.baseUrl, path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
S ret = GsonRepository.gson().fromJson(responseBody.toString(), classOfS);
return ret;
}
/**
* Get AppID
* @return
*/
public String getAppID() {
return this.appID;
}
/**
* Get AppKey
* @return
*/
public String getAppKey() {
return this.appKey;
}
/**
* Get base URL
* @return
*/
public String getBaseUrl() {
return this.baseUrl;
}
/**
*
* @return
*/
public List<Schema> getSchemas() {
return new ArrayList<Schema>(this.schemas.values());
}
/**
* Get owner who uses the IoTCloudAPI.
* @return
*/
public Owner getOwner() {
return this.owner;
}
/**
* Get target thing that is operated by the IoTCloudAPI.
* @return
*/
public Target getTarget() {
return this.target;
}
void setTarget(Target target) {
this.target = target;
saveInstance(this);
}
private Schema getSchema(String schemaName, int schemaVersion) {
return this.schemas.get(new Pair<String, Integer>(schemaName, schemaVersion));
}
private Action generateAction(String schemaName, int schemaVersion, String actionName, JSONObject actionParameters) throws IoTCloudException {
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
Class<? extends Action> actionClass = schema.getActionClass(actionName);
if (actionClass == null) {
throw new UnsupportedActionException(schemaName, schemaVersion, actionName);
}
String json = actionParameters == null ? "{}" : actionParameters.toString();
return this.deserialize(schema, json, actionClass);
}
private ActionResult generateActionResult(String schemaName, int schemaVersion, String actionName, JSONObject actionResult) throws IoTCloudException {
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
Class<? extends ActionResult> actionResultClass = schema.getActionResultClass(actionName);
if (actionResultClass == null) {
throw new UnsupportedActionException(schemaName, schemaVersion, actionName);
}
String json = actionResult == null ? "{}" : actionResult.toString();
return this.deserialize(schema, json, actionResultClass);
}
private Map<String, String> newHeader() {
Map<String, String> headers = new HashMap<String, String>();
if (!TextUtils.isEmpty(this.appID)) {
headers.put("X-Kii-AppID", this.appID);
}
if (!TextUtils.isEmpty(this.appKey)) {
headers.put("X-Kii-AppKey", this.appKey);
}
if (this.owner != null && !TextUtils.isEmpty(this.owner.getAccessToken())) {
headers.put("Authorization", "Bearer " + this.owner.getAccessToken());
}
return headers;
}
private <T> T deserialize(Schema schema, JSONObject json, Class<T> clazz) throws IoTCloudException {
return this.deserialize(schema, json.toString(), clazz);
}
private <T> T deserialize(Schema schema, String json, Class<T> clazz) throws IoTCloudException {
try {
return GsonRepository.gson(schema).fromJson(json, clazz);
} catch (JsonParseException e) {
if (e.getCause() instanceof IoTCloudException) {
throw (IoTCloudException)e.getCause();
}
throw e;
}
}
private static SharedPreferences getSharedPreferences() {
if (context != null) {
return context.getSharedPreferences("com.kii.iotcloud.preferences", Context.MODE_PRIVATE);
}
return null;
}
// Implementation of Parcelable
protected IoTCloudAPI(Parcel in) {
this.tag = in.readString();
this.appID = in.readString();
this.appKey = in.readString();
this.baseUrl = in.readString();
this.owner = in.readParcelable(Owner.class.getClassLoader());
this.target = in.readParcelable(Target.class.getClassLoader());
ArrayList<Schema> schemas = in.createTypedArrayList(Schema.CREATOR);
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.restClient = new IoTRestClient();
this.installationID = in.readString();
}
public static final Creator<IoTCloudAPI> CREATOR = new Creator<IoTCloudAPI>() {
@Override
public IoTCloudAPI createFromParcel(Parcel in) {
return new IoTCloudAPI(in);
}
@Override
public IoTCloudAPI[] newArray(int size) {
return new IoTCloudAPI[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.tag);
dest.writeString(this.appID);
dest.writeString(this.appKey);
dest.writeString(this.baseUrl);
dest.writeParcelable(this.owner, flags);
dest.writeParcelable(this.target, flags);
dest.writeTypedList(new ArrayList<Schema>(this.schemas.values()));
dest.writeString(this.installationID);
}
} |
package samples;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Program {
public static void main(String[] args) throws InterruptedException
{
QiClient qiclient = null;
QiType evtType = null;
QiStream evtStream = null;
try{
String server = "https://qi-data.osisoft.com:3380";
qiclient = new QiClient( server);
// TODO retract when provisioning is complete
//System.out.println("Creating a tenant named " + tenantId);
//qiclient.CreateTenant(tenantId);
// create properties for double Value, DateTime Timstamp, string Units
System.out.println("Creating a Qi type for WaveData instances");
QiType intType = new QiType();
intType.setId("intType");
intType.setQiTypeCode(QiTypeCode.Int32);
QiType doubleType = new QiType();
doubleType.setId("doubleType");
doubleType.setQiTypeCode(QiTypeCode.Double);
QiTypeProperty orderProperty = new QiTypeProperty();
orderProperty.setId("Order");
orderProperty.setQiType(intType);
orderProperty.setIsKey(true);
QiTypeProperty tauProperty = new QiTypeProperty();
tauProperty.setId("Tau");
tauProperty.setQiType(doubleType);
QiTypeProperty radiansProperty = new QiTypeProperty();
radiansProperty.setId("Radians");
radiansProperty.setQiType(doubleType);
QiTypeProperty sinProperty = new QiTypeProperty();
sinProperty.setId("Sin");
sinProperty.setQiType(doubleType);
QiTypeProperty cosProperty = new QiTypeProperty();
cosProperty.setId("Cos");
cosProperty.setQiType(doubleType);
QiTypeProperty tanProperty = new QiTypeProperty();
tanProperty.setId("Tan");
tanProperty.setQiType(doubleType);
QiTypeProperty sinhProperty = new QiTypeProperty();
sinhProperty.setId("Sinh");
sinhProperty.setQiType(doubleType);
QiTypeProperty coshProperty = new QiTypeProperty();
coshProperty.setId("cosh");
coshProperty.setQiType(doubleType);
QiTypeProperty tanhProperty = new QiTypeProperty();
tanhProperty.setId("Tanh");
tanhProperty.setQiType(doubleType);
// Create a QiType for our WaveData class; the metadata proeprties are the ones we just created
QiType type = new QiType();
type.setName("WaveDataJ");
type.setId("WaveDataTypeJ");
type.setDescription("This is a sample stream for storing WaveData type events");
QiTypeProperty[] props = {orderProperty, tauProperty, radiansProperty, sinProperty, cosProperty, tanProperty, sinhProperty, coshProperty, tanhProperty};
type.setProperties(props);
// create the type in the Qi Service
String evtTypeString = qiclient.CreateType(type);
evtType = qiclient.mGson.fromJson(evtTypeString, QiType.class);
//create a stream named evtStreamJ
System.out.println("Creating a stream in this tenant for simple event measurements");
QiStream stream = new QiStream("evtStreamJ",evtType.getId());
String evtStreamString = qiclient.CreateStream(stream);
evtStream = qiclient.mGson.fromJson(evtStreamString, QiStream.class);
System.out.println("Artificially generating 100 events and inserting them into the Qi Service");
// How to insert a single event
WaveData evt = WaveData.next(1, 2.0, 0);
qiclient.CreateEvent(evtStream.getId(), qiclient.mGson.toJson(evt));
List<WaveData> events = new ArrayList<WaveData>();
// how to insert an a collection of events
for (int i = 2; i < 200; i+=2)
{
evt = WaveData.next(1, 2.0, i);
events.add(evt);
Thread.sleep(400);
}
qiclient.CreateEvents(evtStream.getId(), qiclient.mGson.toJson(events));
Thread.sleep(2000);
System.out.println("Retrieving the inserted events");
System.out.println("==============================");
String jCollection = qiclient.GetWindowValues(evtStream.getId(), "0", "198");
Type listType = new TypeToken<ArrayList<WaveData>>() {
}.getType();
ArrayList<WaveData> foundEvents = qiclient.mGson.fromJson(jCollection, listType);
DumpEvents(foundEvents);
System.out.println();
System.out.println("Updating values");
// take the first value inserted and update
evt = foundEvents.get(0);
evt = WaveData.next(1, 4.0, 0);
qiclient.updateValue(evtStream.getId(), qiclient.mGson.toJson(evt));
// update the remaining events (same span, multiplier, order)
List<WaveData> newEvents = new ArrayList<WaveData>();
for (WaveData evnt : events)
{
WaveData newEvt = WaveData.next(1, 4.0, evnt.getOrder());
newEvents.add(newEvt);
Thread.sleep(500);
}
qiclient.updateValues(evtStream.getId(),qiclient.mGson.toJson(events));
Thread.sleep(2000);
// check the results
System.out.println("Retrieving the updated values");
System.out.println("=============================");
jCollection = qiclient.GetWindowValues("evtStreamJ", "0", "198");
foundEvents = qiclient.mGson.fromJson(jCollection, listType);
DumpEvents(foundEvents);
// illustrate how stream behaviors modify retrieval
// First, pull three items back with GetRangeValues for range values between events.
// The default behavior is continuous, so ExactOrCalculated should bring back interpolated values
System.out.println();
System.out.println("Retrieving three events without a stream behavior");
jCollection = qiclient.getRangeValues("evtStreamJ", "1", 0, 3, false, QiBoundaryType.ExactOrCalculated);
foundEvents = qiclient.mGson.fromJson(jCollection, listType);
DumpEvents(foundEvents);
// now, create a stream behavior with Discrete and attach it to the existing stream
QiStreamBehavior behavior = new QiStreamBehavior();
behavior.setId("evtStreamStepLeading") ;
behavior.setMode(QiStreamMode.StepwiseContinuousLeading);
String behaviorString = qiclient.CreateBehavior(behavior);
behavior = qiclient.mGson.fromJson(behaviorString, QiStreamBehavior.class);
// update the stream to include this behavior
//evtStream.setBehaviorId("evtStreamStepLeading") ;
evtStream.setBehaviorId(behavior.getId()) ;
qiclient.UpdateStream("evtStreamJ", evtStream);
// repeat the retrieval
System.out.println();
System.out.println("Retrieving three events with a stepwise stream behavior in effect -- compare to last retrieval");
jCollection = qiclient.getRangeValues("evtStreamJ", "1", 0, 3, false, QiBoundaryType.ExactOrCalculated);
foundEvents = qiclient.mGson.fromJson(jCollection, listType);
DumpEvents(foundEvents);
System.out.println();
System.out.println("Deleting events");
qiclient.removeValue(evtStream.getId(), "0");
// remove the first value -- index is the timestamp of the event
qiclient.removeWindowValues(evtStream.getId(), "1", "198");
Thread.sleep(2000);
System.out.println("Checking for events");
System.out.println("===================");
jCollection = qiclient.GetWindowValues(evtStream.getId(), "0", "198");
Type listType1 = new TypeToken<ArrayList<WaveData>>() {
}.getType();
// List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
foundEvents = qiclient.mGson.fromJson(jCollection, listType1);
DumpEvents(foundEvents);
}catch(QiError qiEx){
System.out.println("QiError Msg: " + qiEx.getQiErrorMessage());
System.out.println("HttpStatusCode: "+ qiEx.getHttpStatusCode());
System.out.println("errorMessage: "+ qiEx.getMessage());
} catch(Exception e){
e.printStackTrace();
}
finally {
try
{
qiclient.deleteStream("evtStreamJ");
qiclient.DeleteBehavior("evtStreamStepLeading");
qiclient.deleteType("WaveDataTypeJ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private static void DumpEvents(ArrayList<WaveData> foundEvents) {
System.out.println("Found " +foundEvents.size() + " events, writing");
for( WaveData evnt : foundEvents)
{
System.out.println(evnt.toString());
}
}
} |
package net.xpece.android.support.preference;
import android.annotation.TargetApi;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ImageView;
import android.widget.SeekBar;
/**
* @author Eugen on 7. 12. 2015.
*/
public class XpSeekBarPreferenceDialogFragment extends XpPreferenceDialogFragment
implements View.OnKeyListener {
private SeekBar mSeekBar;
public static XpSeekBarPreferenceDialogFragment newInstance(String key) {
XpSeekBarPreferenceDialogFragment fragment = new XpSeekBarPreferenceDialogFragment();
Bundle b = new Bundle(1);
b.putString("key", key);
fragment.setArguments(b);
return fragment;
}
public XpSeekBarPreferenceDialogFragment() {
}
public SeekBarDialogPreference getSeekBarDialogPreference() {
return (SeekBarDialogPreference) getPreference();
}
protected static SeekBar getSeekBar(View dialogView) {
return (SeekBar) dialogView.findViewById(R.id.seekbar);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
// Show the icon next to seek bar.
builder.setIcon(null);
}
@Override
protected void onBindDialogView(final View view) {
super.onBindDialogView(view);
SeekBarDialogPreference preference = getSeekBarDialogPreference();
boolean hasTitle = false; //hasDialogTitle();
final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon);
final Drawable icon = preference.getDialogIcon();
if (icon != null && !hasTitle) {
iconView.setImageDrawable(icon);
iconView.setVisibility(View.VISIBLE);
} else {
iconView.setVisibility(View.GONE);
iconView.setImageDrawable(null);
}
mSeekBar = getSeekBar(view);
final int max = preference.getMax();
final int min = preference.getMin();
final int progress = preference.getProgress();
mSeekBar.setMax(max - min);
mSeekBar.setProgress(progress - min);
mKeyProgressIncrement = mSeekBar.getKeyProgressIncrement();
mSeekBar.setOnKeyListener(this);
setupAccessibilityDelegate(progress, max, min);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setupAccessibilityDelegate(final int progress, final int max, final int min) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mSeekBar.setAccessibilityDelegate(new View.AccessibilityDelegate() {
@Override
public void onInitializeAccessibilityEvent(final View host, final AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setContentDescription(progress + "");
}
@Override
public void onInitializeAccessibilityNodeInfo(final View host, final AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(host, info);
// info.setText(progress + "");
}
});
}
}
private boolean hasDialogTitle() {
android.support.v7.preference.DialogPreference preference = getPreference();
CharSequence dialogTitle = preference.getDialogTitle();
if (dialogTitle == null) dialogTitle = preference.getTitle();
return !TextUtils.isEmpty(dialogTitle);
}
private int mKeyProgressIncrement;
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_UP) {
final int step = mKeyProgressIncrement;
if (keyCode == KeyEvent.KEYCODE_PLUS || keyCode == KeyEvent.KEYCODE_EQUALS) {
mSeekBar.setProgress(mSeekBar.getProgress() + step);
return true;
}
if (keyCode == KeyEvent.KEYCODE_MINUS) {
mSeekBar.setProgress(mSeekBar.getProgress() - step);
return true;
}
}
return false;
}
@Override
public void onDestroyView() {
mSeekBar.setOnKeyListener(null);
super.onDestroyView();
}
@Override
public void onDialogClosed(final boolean positiveResult) {
SeekBarDialogPreference preference = getSeekBarDialogPreference();
if (positiveResult) {
int progress = mSeekBar.getProgress() + preference.getMin();
if (preference.callChangeListener(progress)) {
preference.setProgress(progress);
}
}
}
} |
package sample.javafx;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import java.util.concurrent.ExecutionException;
public class MainController {
@FXML
public void startTask() throws ExecutionException, InterruptedException {
System.out.println("Main Thread = " + Thread.currentThread().getName());
Task<String> task = new Task<String>() {
@Override
protected String call() throws Exception {
this.updateMessage("foo");
System.out.println(Thread.currentThread().getName());
return "hoge";
}
};
task.setOnSucceeded(e -> {
System.out.println("succeeded thread = " + Thread.currentThread().getName());
});
Thread thread = new Thread(task);
System.out.println("begin thread");
thread.start();
String result = task.get();
System.out.println("end thread. result=" + result);
}
@FXML
public void startService() {
Service<String> service = new Service<String>() {
@Override
protected Task<String> createTask() {
return new Task<String>() {
@Override
protected String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return "fuga";
}
};
}
};
System.out.println("start service");
service.start();
service.setOnSucceeded(e -> {
System.out.println("value=" + service.getValue());
System.out.println("thread = " + Thread.currentThread().getName());
});
}
} |
package com.matthewtamlin.java_compiler_utilities.element_util;
import com.google.common.collect.ImmutableSet;
import com.google.testing.compile.JavaFileObjects;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import javax.lang.model.element.Element;
import javax.tools.JavaFileObject;
import java.io.File;
import java.lang.annotation.Annotation;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Automated tests for the {@link ElementUtil} class.
*/
@RunWith(JUnit4.class)
public class TestElementUtil {
private static final File NORMAL_JAVA_FILE = new File("src/test/java/com/matthewtamlin/" +
"java_compiler_utilities/element_util/NormalJavaFile.java");
private static final File EMPTY_JAVA_FILE = new File("src/test/java/com/matthewtamlin/" +
"java_compiler_utilities/element_util/EmptyJavaFile.java");
private JavaFileObject normalJavaFileObject;
private JavaFileObject emptyJavaFileObject;
@Before
public void setup() throws MalformedURLException {
assertThat("Normal Java file does not exist.", NORMAL_JAVA_FILE.exists(), is(true));
assertThat("Empty Java file does not exist.", EMPTY_JAVA_FILE.exists(), is(true));
normalJavaFileObject = JavaFileObjects.forResource(NORMAL_JAVA_FILE.toURI().toURL());
emptyJavaFileObject = JavaFileObjects.forResource(EMPTY_JAVA_FILE.toURI().toURL());
assertThat("Normal Java file object does not exist.", normalJavaFileObject, is(notNullValue()));
assertThat("Empty Java file object does not exist.", emptyJavaFileObject, is(notNullValue()));
}
@Test(expected = IllegalArgumentException.class)
public void testGetRootElements_nullFile() throws CompilerMissingException {
ElementUtil.getRootElements(null);
}
@Test
public void testGetRootElements_normalJavaFile() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getRootElements(normalJavaFileObject);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("Incorrect elements returned.", toElementNames(elements), is(getRootElementNames()));
}
@Test
public void testGetRootElements_emptyJavaFile() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getRootElements(emptyJavaFileObject);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test(expected = IllegalArgumentException.class)
public void testGetTaggedElements_nullFile() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
ElementUtil.getTaggedElements(null, tags);
}
@Test(expected = IllegalArgumentException.class)
public void testGetTaggedElements_nullTags() throws CompilerMissingException {
ElementUtil.getTaggedElements(normalJavaFileObject, null);
}
@Test(expected = IllegalArgumentException.class)
public void testGetTaggedElements_tagsContainsNull() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
tags.add(null);
ElementUtil.getTaggedElements(normalJavaFileObject, tags);
}
@Test
public void testGetTaggedElements_normalJavaFile_noTags() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
final Set<Element> elements = ElementUtil.getTaggedElements(normalJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test
public void testGetTaggedElements_normalJavaFile_tag1() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
final Set<Element> elements = ElementUtil.getTaggedElements(normalJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("Incorrect elements returned.", toElementNames(elements), is(getTag1ElementNames()));
}
@Test
public void testGetTaggedElements_normalJavaFile_bothTags() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
tags.add(Tag2.class);
final Set<Element> elements = ElementUtil.getTaggedElements(normalJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("Incorrect elements returned.", toElementNames(elements), is(getBothTagsElementNames()));
}
@Test
public void testGetTaggedElements_emptyJavaFile_noTags() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
final Set<Element> elements = ElementUtil.getTaggedElements(emptyJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test
public void testGetTaggedElements_emptyJavaFile_tag1() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
final Set<Element> elements = ElementUtil.getTaggedElements(emptyJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test
public void testGetTaggedElements_emptyJavaFile_bothTags() throws CompilerMissingException {
final Set<Class<? extends Annotation>> tags = new HashSet<>();
tags.add(Tag1.class);
tags.add(Tag2.class);
final Set<Element> elements = ElementUtil.getTaggedElements(emptyJavaFileObject, tags);
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test(expected = IllegalArgumentException.class)
public void testGetElementsById_nullFile() throws CompilerMissingException {
ElementUtil.getElementsById(null, "something");
}
@Test(expected = IllegalArgumentException.class)
public void testGetElementsById_nullId() throws CompilerMissingException {
ElementUtil.getElementsById(normalJavaFileObject, null);
}
@Test
public void testGetElementsById_normalFile_noElementsFoundForId() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getElementsById(normalJavaFileObject, "nothing");
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test
public void testGetElementsById_normalFile_oneElementFoundForId() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getElementsById(normalJavaFileObject, "1");
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("Incorrect elements returned.", toElementNames(elements), is(getId1ElementNames()));
}
@Test
public void testGetElementsById_normalFile_multipleElementsFoundForId() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getElementsById(normalJavaFileObject, "2");
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("Incorrect elements returned.", toElementNames(elements), is(getId2ElementNames()));
}
@Test
public void testGetElementsById_emptyFile() throws CompilerMissingException {
final Set<Element> elements = ElementUtil.getElementsById(emptyJavaFileObject, "2");
assertThat("Returned collection should never be null.", elements, is(notNullValue()));
assertThat("No elements should have been returned.", elements.isEmpty(), is(true));
}
@Test(expected = IllegalArgumentException.class)
public void testGetUniqueElementById_nullFile() throws CompilerMissingException {
ElementUtil.getUniqueElementById(null, "1");
}
@Test(expected = IllegalArgumentException.class)
public void testGetUniqueElementById_nullId() throws CompilerMissingException {
ElementUtil.getUniqueElementById(normalJavaFileObject, null);
}
@Test(expected = UniqueElementNotFoundException.class)
public void testGetUniqueElementById_idNotFound() throws CompilerMissingException {
ElementUtil.getUniqueElementById(emptyJavaFileObject, "anything");
}
@Test
public void testGetUniqueElementById_idFoundOnce() throws CompilerMissingException {
final Element element = ElementUtil.getUniqueElementById(normalJavaFileObject, "1");
assertThat("Returned element should never be null.", element, is(notNullValue()));
final String elementName = element.getSimpleName().toString();
final String expectedElementName = getId1ElementNames().iterator().next();
assertThat("Incorrect element returned.", elementName, is(expectedElementName));
}
@Test(expected = UniqueElementNotFoundException.class)
public void testGetUniqueElementById_idFoundTwice() throws CompilerMissingException {
ElementUtil.getUniqueElementById(normalJavaFileObject, "2");
}
private Set<String> toElementNames(Set<Element> elements) {
final Set<String> names = new HashSet<>();
for (final Element e : elements) {
names.add(e.getSimpleName().toString());
}
return ImmutableSet.copyOf(names);
}
private Set<String> getRootElementNames() {
return ImmutableSet.of(
"NormalJavaFile",
"DefaultClassWithTag1",
"DefaultClassWithTag2",
"DefaultClassWithoutTag");
}
private Set<String> getTag1ElementNames() {
return ImmutableSet.of(
"constantWithTag1",
"fieldWithTag1",
"methodWithTag1",
"innerClassWithTag1",
"parameterWithTag1",
"DefaultClassWithTag1");
}
private Set<String> getTag2ElementNames() {
return ImmutableSet.of(
"constantWithTag2",
"fieldWithTag2",
"methodWithTag2",
"innerClassWithTag2",
"parameterWithTag2",
"DefaultClassWithTag2");
}
private Set<String> getBothTagsElementNames() {
final Set<String> combinedNames = new HashSet<>();
combinedNames.addAll(getTag1ElementNames());
combinedNames.addAll(getTag2ElementNames());
return ImmutableSet.copyOf(combinedNames);
}
public Set<String> getId1ElementNames() {
return ImmutableSet.of("methodWithId1");
}
public Set<String> getId2ElementNames() {
return ImmutableSet.of("methodWithId2", "fieldWithId2");
}
} |
package org.cache2k.benchmark.jmh;
/**
* Configured main class, delegates to runner variant class.
*
* @author Jens Wilke
*/
public class Main {
public static void main(String[] args) throws Exception {
if (args.length > 0 && "jmh".equals(args[0])) {
String[] a2 = new String[args.length-1];
System.arraycopy(args, 1, a2, 0, a2.length);
org.openjdk.jmh.Main.main(a2);
return;
}
Class c = Class.forName(Main.class.getPackage().getName() + "." + args[0]);
Common r = (Common) c.getConstructor().newInstance();
r.setArguments(args);
r.run();
}
} |
package org.subethamail.smtp.server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.subethamail.smtp.MessageHandlerFactory;
import org.subethamail.smtp.MessageListener;
import org.subethamail.smtp.Version;
/**
* Main SMTPServer class. Construct this object, set the
* hostName, port, and bind address if you wish to override the
* defaults, and call start().
*
* This class starts opens a ServerSocket and creates a new
* instance of the ConnectionHandler class when a new connection
* comes in. The ConnectionHandler then parses the incoming SMTP
* stream and hands off the processing to the CommandHandler which
* will execute the appropriate SMTP command class.
*
* This class also manages a watchdog thread which will timeout
* stale connections.
*
* There are two ways of using this server. The first is to
* construct with a MessageHandlerFactory. This provides the
* lowest-level and most flexible access. The second way is
* to construct with a collection of MessageListeners. This
* is a higher, and sometimes more convenient level of abstraction.
*
* In neither case is the SMTP server (this library) responsible
* for deciding what recipients to accept or what to do with the
* incoming data. That is left to you.
*
* @author Jon Stevens
* @author Ian McFarland <ian@neo.com>
* @author Jeff Schnitzer
*/
@SuppressWarnings("serial")
public class SMTPServer implements Runnable
{
private static Log log = LogFactory.getLog(SMTPServer.class);
private InetAddress bindAddress = null; // default to all interfaces
private int port = 25; // default to 25
private String hostName; // defaults to a lookup of the local address
private int backlog = 50;
private MessageHandlerFactory messageHandlerFactory;
private CommandHandler commandHandler;
private ServerSocket serverSocket;
private boolean go = true;
private Thread serverThread;
private Watchdog watchdog;
private ThreadGroup connectionHanderGroup;
/**
* set a hard limit on the maximum number of connections this server will accept
* once we reach this limit, the server will gracefully reject new connections.
* Default is 1000.
*/
private int maxConnections = 1000;
/**
* The timeout for waiting for data on a connection is one minute: 1000 * 60 * 1
*/
private int connectionTimeout = 1000 * 60 * 1;
/**
* The maximal number of recipients that this server accepts per message delivery request.
*/
private int maxRecipients = 1000;
/**
* The primary constructor.
*/
public SMTPServer(MessageHandlerFactory handlerFactory)
{
this.messageHandlerFactory = handlerFactory;
try
{
this.hostName = InetAddress.getLocalHost().getCanonicalHostName();
}
catch (UnknownHostException e)
{
this.hostName = "localhost";
}
this.commandHandler = new CommandHandler();
this.connectionHanderGroup = new ThreadGroup(SMTPServer.class.getName() + " ConnectionHandler Group");
}
/**
* A convenience constructor that splits the smtp data among multiple listeners
* (and multiple recipients).
*/
public SMTPServer(Collection<MessageListener> listeners)
{
this(new MessageListenerAdapter(listeners));
}
/** @return the host name that will be reported to SMTP clients */
public String getHostName()
{
return this.hostName;
}
/** The host name that will be reported to SMTP clients */
public void setHostName(String hostName)
{
this.hostName = hostName;
}
/** null means all interfaces */
public InetAddress getBindAddress()
{
return this.bindAddress;
}
/** null means all interfaces */
public void setBindAddress(InetAddress bindAddress)
{
this.bindAddress = bindAddress;
}
public int getPort()
{
return this.port;
}
public void setPort(int port)
{
this.port = port;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*
* @return the backlog
*/
public int getBacklog()
{
return this.backlog;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*/
public void setBacklog(int backlog)
{
this.backlog = backlog;
}
/**
* Call this method to get things rolling after instantiating the
* SMTPServer.
*/
public synchronized void start()
{
if (this.serverThread != null)
throw new IllegalStateException("SMTPServer already started");
// Create our server socket here.
try
{
this.serverSocket = createServerSocket();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
this.serverThread = new Thread(this, SMTPServer.class.getName());
// daemon threads do not keep the program from quitting;
// user threads keep the program from quitting.
// We want the serverThread to keep the program from quitting
// this.serverThread.setDaemon(true);
// Now call the serverThread.run() method
this.serverThread.start();
this.watchdog = new Watchdog(this);
// We do not want the watchdog to keep the program from quitting
this.watchdog.setDaemon(true);
this.watchdog.start();
}
/**
* Shut things down gracefully.
*/
public synchronized void stop()
{
// don't accept any more connections
this.go = false;
// kill the listening thread
this.serverThread = null;
// stop the watchdog
if (this.watchdog != null)
{
this.watchdog.quit();
this.watchdog = null;
}
// if the serverSocket is not null, force a socket close for good measure
try
{
if (this.serverSocket != null && !this.serverSocket.isClosed())
this.serverSocket.close();
}
catch (IOException e)
{
}
}
/**
* Override this method if you want to create your own server sockets.
* You must return a bound ServerSocket instance
*
* @throws IOException
*/
protected ServerSocket createServerSocket()
throws IOException
{
InetSocketAddress isa;
if (this.bindAddress == null)
{
isa = new InetSocketAddress(this.port);
}
else
{
isa = new InetSocketAddress(this.bindAddress, this.port);
}
ServerSocket serverSocket = new ServerSocket();
// http://java.sun.com/j2se/1.5.0/docs/api/java/net/ServerSocket.html#setReuseAddress(boolean)
serverSocket.setReuseAddress(true);
serverSocket.bind(isa, this.backlog);
return serverSocket;
}
/**
* This method is called by this thread when it starts up.
*/
public void run()
{
while (this.go)
{
try
{
ConnectionHandler connectionHandler = new ConnectionHandler(this, this.serverSocket.accept());
connectionHandler.start();
}
catch (IOException ioe)
{
if (this.go)
log.error("Error accepting connections", ioe);
}
}
try
{
if (this.serverSocket != null && !this.serverSocket.isClosed())
this.serverSocket.close();
log.info("SMTP Server socket shut down.");
}
catch (IOException e)
{
log.error("Failed to close server socket.", e);
}
this.serverSocket = null;
}
public String getName()
{
return "SubEthaSMTP";
}
public String getNameVersion()
{
return getName() + " " + Version.getSpecification();
}
/**
* All smtp data is eventually routed through the handlers.
*/
public MessageHandlerFactory getMessageHandlerFactory()
{
return this.messageHandlerFactory;
}
/**
* The CommandHandler manages handling the SMTP commands
* such as QUIT, MAIL, RCPT, DATA, etc.
*
* @return An instance of CommandHandler
*/
public CommandHandler getCommandHandler()
{
return this.commandHandler;
}
protected ThreadGroup getConnectionGroup()
{
return this.connectionHanderGroup;
}
public int getNumberOfConnections()
{
return this.connectionHanderGroup.activeCount();
}
public boolean hasTooManyConnections()
{
return (getNumberOfConnections() >= maxConnections);
}
public int getMaxConnections()
{
return this.maxConnections;
}
public void setMaxConnections(int maxConnections)
{
this.maxConnections = maxConnections;
}
public int getConnectionTimeout()
{
return this.connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout)
{
this.connectionTimeout = connectionTimeout;
}
public int getMaxRecipients()
{
return this.maxRecipients;
}
public void setMaxRecipients(int maxRecipients)
{
this.maxRecipients = maxRecipients;
}
/**
* A watchdog thread that makes sure that connections don't go stale. It
* prevents someone from opening up MAX_CONNECTIONS to the server and
* holding onto them for more than 1 minute.
*/
private class Watchdog extends Thread
{
private SMTPServer server;
private Thread[] groupThreads = new Thread[maxConnections];
private boolean run = true;
public Watchdog(SMTPServer server)
{
super(Watchdog.class.getName());
this.server = server;
setPriority(Thread.MAX_PRIORITY / 3);
}
public void quit()
{
this.run = false;
}
public void run()
{
while (this.run)
{
ThreadGroup connectionGroup = this.server.getConnectionGroup();
connectionGroup.enumerate(this.groupThreads);
for (int i=0; i<connectionGroup.activeCount(); i++)
{
ConnectionHandler aThread = ((ConnectionHandler)this.groupThreads[i]);
if (aThread != null)
{
// one minute timeout
long lastActiveTime = aThread.getLastActiveTime() + (this.server.connectionTimeout);
if (lastActiveTime < System.currentTimeMillis())
{
try
{
aThread.timeout();
}
catch (IOException ioe)
{
log.debug("Lost connection to client during timeout");
}
}
}
}
try
{
// go to sleep for 10 seconds.
sleep(1000 * 10);
}
catch (InterruptedException e)
{
// ignore
}
}
}
}
} |
package org.subethamail.smtp.server;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.common.ThreadModel;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.integration.jmx.IoServiceManager;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.MessageHandlerFactory;
import org.subethamail.smtp.MessageListener;
import org.subethamail.smtp.Version;
@SuppressWarnings("serial")
public class SMTPServer
{
private static Logger log = LoggerFactory.getLogger(SMTPServer.class);
public final static Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
/**
* default to all interfaces
*/
private InetAddress bindAddress = null;
/**
* default to 25
*/
private int port = 25;
/**
* defaults to a lookup of the local address
*/
private String hostName;
/**
* defaults to 5000
*/
private int backlog = 5000;
private MessageHandlerFactory messageHandlerFactory;
private CommandHandler commandHandler;
private SocketAcceptor acceptor;
private ExecutorService executor;
private ExecutorService acceptorThreadPool;
private SocketAcceptorConfig config;
private IoServiceManager serviceManager;
private ObjectName jmxName;
private ConnectionHandler handler;
private SMTPCodecDecoder codecDecoder;
private boolean go = false;
/**
* set a hard limit on the maximum number of connections this server will accept
* once we reach this limit, the server will gracefully reject new connections.
* Default is 1000.
*/
private int maxConnections = 1000;
/**
* The timeout for waiting for data on a connection is one minute: 1000 * 60 * 1
*/
private int connectionTimeout = 1000 * 60 * 1;
/**
* The maximal number of recipients that this server accepts per message delivery request.
*/
private int maxRecipients = 1000;
/**
* 4 megs by default. The server will buffer incoming messages to disk
* when they hit this limit in the DATA received.
*/
protected final static int DEFAULT_DATA_DEFERRED_SIZE = 1024*1024*4;
private int dataDeferredSize = DEFAULT_DATA_DEFERRED_SIZE;
/**
* The primary constructor.
*/
public SMTPServer(MessageHandlerFactory handlerFactory)
{
this.messageHandlerFactory = handlerFactory;
try
{
this.hostName = InetAddress.getLocalHost().getCanonicalHostName();
}
catch (UnknownHostException e)
{
this.hostName = "localhost";
}
this.commandHandler = new CommandHandler();
initService();
}
/**
* A convenience constructor that splits the smtp data among multiple listeners
* (and multiple recipients).
*/
public SMTPServer(Collection<MessageListener> listeners)
{
this(new MessageListenerAdapter(listeners));
}
/**
* Starts the JMX service with a polling interval default of 1000ms.
*
* @throws InstanceAlreadyExistsException
* @throws MBeanRegistrationException
* @throws NotCompliantMBeanException
*/
public void startJMXService()
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
startJMXService(1000);
}
/**
* Start the JMX service.
*
* @param pollingInterval
* @throws InstanceAlreadyExistsException
* @throws MBeanRegistrationException
* @throws NotCompliantMBeanException
*/
public void startJMXService(int pollingInterval)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
serviceManager.startCollectingStats(pollingInterval);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(serviceManager, jmxName);
}
/**
* Stop the JMX service.
*
* @throws InstanceNotFoundException
* @throws MBeanRegistrationException
*/
public void stopJMXService() throws InstanceNotFoundException, MBeanRegistrationException
{
serviceManager.stopCollectingStats();
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.unregisterMBean(jmxName);
}
/**
* Initializes the runtime service.
*/
private void initService()
{
try
{
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptorThreadPool = Executors.newCachedThreadPool();
acceptor =
new SocketAcceptor(Runtime.getRuntime().availableProcessors() + 1, acceptorThreadPool);
// JMX instrumentation
serviceManager = new IoServiceManager(acceptor);
jmxName = new ObjectName("subethasmtp.mina.server:type=IoServiceManager");
config = new SocketAcceptorConfig();
config.setThreadModel(ThreadModel.MANUAL);
((SocketAcceptorConfig)config).setReuseAddress(true);
DefaultIoFilterChainBuilder chain = config.getFilterChain();
if (log.isTraceEnabled())
chain.addLast("logger", new LoggingFilter());
SMTPCodecFactory codecFactory = new SMTPCodecFactory(DEFAULT_CHARSET, getDataDeferredSize());
codecDecoder = (SMTPCodecDecoder) codecFactory.getDecoder();
chain.addLast("codec", new ProtocolCodecFilter(codecFactory));
executor = Executors.newCachedThreadPool(new ThreadFactory() {
int sequence;
public Thread newThread(Runnable r)
{
sequence += 1;
return new Thread(r, "SubEthaSMTP Thread "+sequence);
}
});
chain.addLast("threadPool", new ExecutorFilter(executor));
handler = new ConnectionHandler(this);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
/**
* Call this method to get things rolling after instantiating the
* SMTPServer.
*/
public synchronized void start()
{
if (go == true)
throw new RuntimeException("SMTPServer is already started.");
InetSocketAddress isa;
if (this.bindAddress == null)
{
isa = new InetSocketAddress(this.port);
}
else
{
isa = new InetSocketAddress(this.bindAddress, this.port);
}
((SocketAcceptorConfig)config).setBacklog(getBacklog());
try
{
acceptor.bind(isa, handler, config);
go = true;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Shut things down gracefully.
*/
public synchronized void stop()
{
try
{
log.info("SMTP Server socket shut down.");
try { acceptor.unbindAll(); } catch (Exception e) { }
try { executor.shutdown(); } catch (Exception e) { }
try { acceptorThreadPool.shutdown(); } catch (Exception e) { }
}
finally
{
go = false;
}
}
/** @return the host name that will be reported to SMTP clients */
public String getHostName()
{
if (this.hostName == null)
return "localhost";
else
return this.hostName;
}
/** The host name that will be reported to SMTP clients */
public void setHostName(String hostName)
{
this.hostName = hostName;
}
/** null means all interfaces */
public InetAddress getBindAddress()
{
return this.bindAddress;
}
/**
* null means all interfaces
*/
public void setBindAddress(InetAddress bindAddress)
{
this.bindAddress = bindAddress;
}
/**
* get the port the server is running on.
*/
public int getPort()
{
return this.port;
}
/**
* set the port the server is running on.
* @param port
*/
public void setPort(int port)
{
this.port = port;
}
/**
* Is the server running after start() has been called?
*/
public synchronized boolean isRunning()
{
return this.go;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*
* @return the backlog
*/
public int getBacklog()
{
return this.backlog;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*/
public void setBacklog(int backlog)
{
this.backlog = backlog;
}
/**
* The name of the server software.
*/
public String getName()
{
return "SubEthaSMTP";
}
/**
* The name + version of the server software.
*/
public String getNameVersion()
{
return getName() + " " + Version.getSpecification();
}
/**
* All smtp data is eventually routed through the handlers.
*/
public MessageHandlerFactory getMessageHandlerFactory()
{
return this.messageHandlerFactory;
}
/**
* The CommandHandler manages handling the SMTP commands
* such as QUIT, MAIL, RCPT, DATA, etc.
*
* @return An instance of CommandHandler
*/
public CommandHandler getCommandHandler()
{
return this.commandHandler;
}
/**
* Number of connections in the handler.
*/
public int getNumberOfConnections()
{
return handler.getNumberOfConnections();
}
/**
* Are we over the maximum amount of connections ?
*/
public boolean hasTooManyConnections()
{
return (this.maxConnections > -1 &&
getNumberOfConnections() >= this.maxConnections);
}
/**
* What is the maximum amount of connections?
*/
public int getMaxConnections()
{
return this.maxConnections;
}
/**
* Set's the maximum number of connections this server instance will
* accept. If set to -1 then limit is ignored.
*
* @param maxConnections
*/
public void setMaxConnections(int maxConnections)
{
this.maxConnections = maxConnections;
}
/**
* What is the connection timeout?
*/
public int getConnectionTimeout()
{
return this.connectionTimeout;
}
/**
* Set the connection timeout.
*/
public void setConnectionTimeout(int connectionTimeout)
{
this.connectionTimeout = connectionTimeout;
}
/**
* What is the maximum number of recipients for a single message ?
*/
public int getMaxRecipients()
{
return this.maxRecipients;
}
/**
* Set the maximum number of recipients for a single message.
* If set to -1 then limit is ignored.
*/
public void setMaxRecipients(int maxRecipients)
{
this.maxRecipients = maxRecipients;
}
/**
* Get the maximum size in bytes of a single message before it is
* dumped to a temporary file.
*/
public int getDataDeferredSize()
{
return dataDeferredSize;
}
/**
* Set the maximum size in bytes of a single message before it is
* dumped to a temporary file. Argument must be a positive power
* of two in order to follow the expanding algorithm of
* {@link org.apache.mina.common.ByteBuffer} to prevent unnecessary
* memory consumption.
*/
public void setDataDeferredSize(int dataDeferredSize)
{
if (isPowerOfTwo(dataDeferredSize))
{
this.dataDeferredSize = dataDeferredSize;
if (codecDecoder != null)
codecDecoder.setDataDeferredSize(dataDeferredSize);
}
else
throw new IllegalArgumentException(
"Argument dataDeferredSize must be a positive power of two");
}
/**
* Sets the receive buffer size.
*/
public void setReceiveBufferSize(int receiveBufferSize)
{
handler.setReceiveBufferSize(receiveBufferSize);
}
/**
* Demonstration : if x is a power of 2, it can't share any bit with x-1. So
* x & (x-1) should be equal to 0. To get rid of negative values, we check
* that x is higher than 1 (0 and 1 being of course unacceptable values
* for a buffer length).
*
* @param x the number to test
* @return true if x is a power of two
*/
protected boolean isPowerOfTwo(int x)
{
return (x > 1) && (x & (x-1)) == 0;
}
} |
package com.sun.star.filter.config.tools.split;
import java.lang.*;
import java.util.*;
import java.io.*;
import com.sun.star.filter.config.tools.utils.*;
/**
* Can split one xml file into its different xml fragments.
*
*
*/
public class Splitter
{
// const
// member
/** contains all real member of this instance.
* That make it easy to initialize an instance
* of this class inside a multi-threaded environment. */
private SplitterData m_aDataSet;
// interface
/** initialize a new instance of this class with all
* needed resources.
*
* @param aDataSet
* contains all needed parameters for this instance
* as a complete set, which can be filled outside.
*/
public Splitter(SplitterData aDataSet)
{
m_aDataSet = aDataSet;
}
// interface
/** generate xml fragments for all cache items.
*
* @throw [java.lang.Exception]
* if anything will fail inside during
* this operation runs.
*/
public synchronized void split()
throws java.lang.Exception
{
createDirectoryStructures();
// use some statistic values to check if all cache items
// will be transformed realy.
int nTypes = m_aDataSet.m_aCache.getItemCount(Cache.E_TYPE );
int nFilters = m_aDataSet.m_aCache.getItemCount(Cache.E_FILTER );
int nDetectServices = m_aDataSet.m_aCache.getItemCount(Cache.E_DETECTSERVICE );
int nFrameLoaders = m_aDataSet.m_aCache.getItemCount(Cache.E_FRAMELOADER );
int nContentHandlers = m_aDataSet.m_aCache.getItemCount(Cache.E_CONTENTHANDLER);
// generate all type fragments
m_aDataSet.m_aDebug.setGlobalInfo("generate type fragments ...");
java.util.Vector lNames = m_aDataSet.m_aCache.getItemNames(Cache.E_TYPE);
java.util.Enumeration it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_TYPE, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirTypes);
nTypes -= lNames.size();
// generate filter fragments for the writer module
m_aDataSet.m_aDebug.setGlobalInfo("generate filter fragments ...");
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module writer ...");
java.util.HashMap rRequestedProps = new java.util.HashMap();
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.text.TextDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSWriter);
nFilters -= lNames.size();
// generate filter fragments for the writer/web module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module writer/web ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.text.WebDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSWeb);
nFilters -= lNames.size();
// generate filter fragments for the writer/global module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module writer/global ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.text.GlobalDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSGlobal);
nFilters -= lNames.size();
// generate filter fragments for the calc module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module calc ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.sheet.SpreadsheetDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSCalc);
nFilters -= lNames.size();
// generate filter fragments for the draw module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module draw ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.drawing.DrawingDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSDraw);
nFilters -= lNames.size();
// generate filter fragments for the impress module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module impress ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.presentation.PresentationDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSImpress);
nFilters -= lNames.size();
// generate filter fragments for the chart module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module chart ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.chart2.ChartDocument");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSChart);
nFilters -= lNames.size();
// generate filter fragments for the math module
m_aDataSet.m_aDebug.setGlobalInfo("\tfor module math ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "com.sun.star.formula.FormulaProperties");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleSMath);
nFilters -= lNames.size();
// generate fragments for 3rdParty or unspecified (may graphics) filters!
m_aDataSet.m_aDebug.setGlobalInfo("\tfor unknown modules ...");
rRequestedProps.put(Cache.PROPNAME_DOCUMENTSERVICE, "");
lNames = m_aDataSet.m_aCache.getMatchedItemNames(Cache.E_FILTER, rRequestedProps);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FILTER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirModuleOthers);
nFilters -= lNames.size();
// generate all detect service fragments
m_aDataSet.m_aDebug.setGlobalInfo("generate detect service fragments ...");
lNames = m_aDataSet.m_aCache.getItemNames(Cache.E_DETECTSERVICE);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_DETECTSERVICE, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirDetectServices);
nDetectServices -= lNames.size();
// generate all frame loader fragments
m_aDataSet.m_aDebug.setGlobalInfo("generate frame loader fragments ...");
lNames = m_aDataSet.m_aCache.getItemNames(Cache.E_FRAMELOADER);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_FRAMELOADER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirFrameLoaders);
nFrameLoaders -= lNames.size();
// generate all content handler fragments
m_aDataSet.m_aDebug.setGlobalInfo("generate content handler fragments ...");
lNames = m_aDataSet.m_aCache.getItemNames(Cache.E_CONTENTHANDLER);
it = lNames.elements();
while(it.hasMoreElements())
generateXMLFragment(Cache.E_CONTENTHANDLER, (java.lang.String)it.nextElement(), m_aDataSet.m_aFragmentDirContentHandlers);
nContentHandlers -= lNames.size();
// check if all cache items was handled
if (
(nTypes != 0) ||
(nFilters != 0) ||
(nDetectServices != 0) ||
(nFrameLoaders != 0) ||
(nContentHandlers != 0)
)
{
java.lang.StringBuffer sStatistic = new java.lang.StringBuffer(256);
sStatistic.append("some cache items seems to be not transformed:\n");
sStatistic.append(nTypes +" unhandled types\n" );
sStatistic.append(nFilters +" unhandled filters\n" );
sStatistic.append(nDetectServices +" unhandled detect services\n");
sStatistic.append(nFrameLoaders +" unhandled frame loader\n" );
sStatistic.append(nContentHandlers+" unhandled content handler\n");
throw new java.lang.Exception(sStatistic.toString());
}
}
/** generate a xml fragment file from the specified cache item.
*
* @param eItemType
* specify, which sub container of the cache must be used
* to locate the right item.
*
* @param sItemName
* the name of the cache item inside the specified sub container.
*
* @param aOutDir
* output directory.
*
* @throw [java.lang.Exception]
* if the fragment file already exists or could not be created
* successfully.
*/
private void generateXMLFragment(int eItemType,
java.lang.String sItemName,
java.io.File aOutDir )
throws java.lang.Exception
{
java.lang.String sFileName = FileHelper.convertName2FileName(sItemName);
java.lang.String sXML = m_aDataSet.m_aCache.getItemAsXML(eItemType, sItemName, m_aDataSet.m_nFormat);
java.io.File aFile = new java.io.File(aOutDir, sFileName+m_aDataSet.m_sFragmentExtension);
if (aFile.exists())
throw new java.lang.Exception("fragment["+eItemType+", \""+sItemName+"\"] file named \""+aFile.getPath()+"\" already exists.");
java.io.FileOutputStream aStream = new java.io.FileOutputStream(aFile);
java.io.OutputStreamWriter aWriter = new java.io.OutputStreamWriter(aStream, m_aDataSet.m_sEncoding);
aWriter.write(sXML, 0, sXML.length());
aWriter.flush();
aWriter.close();
m_aDataSet.m_aDebug.setDetailedInfo("fragment["+eItemType+", \""+sItemName+"\"] => \""+aFile.getPath()+"\" ... OK");
}
/** create all needed directory structures.
*
* First it try to clear old structures and
* create new ones afterwards.
*
* @throw [java.lang.Exception]
* if some of the needed structures
* could not be created successfully.
*/
private void createDirectoryStructures()
throws java.lang.Exception
{
m_aDataSet.m_aDebug.setGlobalInfo("create needed directory structures ...");
// delete simple files only; no directories!
// Because this tool may run inside
// a cvs environment its not a godd idea to do so.
boolean bFilesOnly = false;
FileHelper.makeDirectoryEmpty(m_aDataSet.m_aOutDir, bFilesOnly);
if (
(!m_aDataSet.m_aFragmentDirTypes.exists() && !m_aDataSet.m_aFragmentDirTypes.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirFilters.exists() && !m_aDataSet.m_aFragmentDirFilters.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirDetectServices.exists() && !m_aDataSet.m_aFragmentDirDetectServices.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirFrameLoaders.exists() && !m_aDataSet.m_aFragmentDirFrameLoaders.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirContentHandlers.exists() && !m_aDataSet.m_aFragmentDirContentHandlers.mkdir()) ||
(!m_aDataSet.m_aFragmentDirModuleSWriter.exists() && !m_aDataSet.m_aFragmentDirModuleSWriter.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSWeb.exists() && !m_aDataSet.m_aFragmentDirModuleSWeb.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSGlobal.exists() && !m_aDataSet.m_aFragmentDirModuleSGlobal.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSCalc.exists() && !m_aDataSet.m_aFragmentDirModuleSCalc.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSDraw.exists() && !m_aDataSet.m_aFragmentDirModuleSDraw.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSImpress.exists() && !m_aDataSet.m_aFragmentDirModuleSImpress.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSMath.exists() && !m_aDataSet.m_aFragmentDirModuleSMath.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleSChart.exists() && !m_aDataSet.m_aFragmentDirModuleSChart.mkdir() ) ||
(!m_aDataSet.m_aFragmentDirModuleOthers.exists() && !m_aDataSet.m_aFragmentDirModuleOthers.mkdir() )
)
{
throw new java.lang.Exception("some directory structures does not exists and could not be created successfully.");
}
}
} |
package org.apache.maven.integrationtests;
import junit.framework.TestCase;
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
public class MavenIT0090Test
extends TestCase /*extends AbstractMavenIntegrationTest*/
{
/**
* Test that ensures that envars are interpolated correctly into plugin
* configurations.
*/
public void testit0090()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/it0090" );
Verifier verifier = new Verifier( testDir.getAbsolutePath(), true );
Map envVars = new HashMap();
envVars.put( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
verifier.executeGoal( "test", envVars );
verifier.assertFilePresent( "target/mojo-generated.properties" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
System.out.println( "it0090 PASS" );
}
} |
import gov.nih.nci.cagrid.cananolab.client.CaNanoLabServiceClient;
import gov.nih.nci.cagrid.cqlquery.Association;
import gov.nih.nci.cagrid.cqlquery.Attribute;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.Predicate;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import gov.nih.nci.cananolab.domain.agentmaterial.OtherFunctionalizingEntity;
import gov.nih.nci.cananolab.domain.common.Author;
import gov.nih.nci.cananolab.domain.common.Condition;
import gov.nih.nci.cananolab.domain.common.Datum;
import gov.nih.nci.cananolab.domain.common.ExperimentConfig;
import gov.nih.nci.cananolab.domain.common.File;
import gov.nih.nci.cananolab.domain.common.Finding;
import gov.nih.nci.cananolab.domain.common.Instrument;
import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.common.Organization;
import gov.nih.nci.cananolab.domain.common.PointOfContact;
import gov.nih.nci.cananolab.domain.common.Protocol;
import gov.nih.nci.cananolab.domain.common.Publication;
import gov.nih.nci.cananolab.domain.common.Technique;
import gov.nih.nci.cananolab.domain.linkage.OtherChemicalAssociation;
import gov.nih.nci.cananolab.domain.nanomaterial.OtherNanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.ActivationMethod;
import gov.nih.nci.cananolab.domain.particle.AssociatedElement;
import gov.nih.nci.cananolab.domain.particle.Characterization;
import gov.nih.nci.cananolab.domain.particle.ChemicalAssociation;
import gov.nih.nci.cananolab.domain.particle.ComposingElement;
import gov.nih.nci.cananolab.domain.particle.Function;
import gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity;
import gov.nih.nci.cananolab.domain.particle.NanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.Sample;
import gov.nih.nci.cananolab.domain.particle.SampleComposition;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
public class GridClientTest {
CaNanoLabServiceClient gridClient;
StringBuilder builder= new StringBuilder();
private static Logger logger = Logger.getLogger(GridClientTest.class);
public GridClientTest(CaNanoLabServiceClient gridClient) {
this.gridClient = gridClient;
}
public void testComposingElement(String id) {
// "6062106"
System.out.println("Testing ComposingElement with id=" + id);
builder.append("Testing ComposingElement with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.ComposingElement");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.ComposingElement");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
ComposingElement ce = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
ce = (ComposingElement) obj;
System.out.println("ComposingElement: id=" + ce.getId()
+ "\tDesc=" + ce.getDescription() + "\tName="
+ ce.getName());
builder.append("ComposingElement: id=" + ce.getId()
+ "\tDesc=" + ce.getDescription() + "\tName="
+ ce.getName() + "\n");
// TODO add CQL for functions by composing element id
loadInherentFunctionsForComposingElement(ce);
}
} catch (Exception e) {
System.out.println("Exception getting ComposingElement for id="
+ id + ": " + e);
builder.append("Exception getting ComposingElement for id="
+ id + ": " + e + "\n");
}
}
public void testSampleComposition(String id) {
// "6160390"
System.out.println("Testing SampleComposition with id=" + id);
builder.append("Testing SampleComposition with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.SampleComposition");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.SampleComposition");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
SampleComposition sc = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
sc = (SampleComposition) obj;
System.out.println("SampleComposition : id=" + sc.getId());
builder.append("SampleComposition : id=" + sc.getId());
}
} catch (Exception e) {
System.out.println("Exception getting SampleComposition for id="
+ id + ": " + e);
builder.append("Exception getting SampleComposition for id="
+ id + ": " + e + "\n");
}
}
public void testGetAllCharacterizationByCQLQuery() {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.Characterization");
/*
* Attribute attribute = new Attribute(); attribute.setName("id");
* attribute.setPredicate(Predicate.EQUAL_TO);
* attribute.setValue("10846210"); target.setAttribute(attribute);
*/
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Characterization");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Characterization chara = null;
System.out
.println("Testing GetAllCharacterizationByCQLQuery, for every characterization test \n"
+ "GetFinding, GetProtocol, GetExperimentConfigs, and Characterization.");
builder.append("Testing GetAllCharacterizationByCQLQuery, for every characterization test \n"
+ "GetFinding, GetProtocol, GetExperimentConfigs, and Characterization." + "\n");
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
chara = (Characterization) obj;
if (chara != null) {
testGetFindingsByCharacterizationId(chara.getId()
.toString());
testGetProtocolByCharacterizationId(chara.getId()
.toString());
testGetExperimentConfigsByCharacterizationId(chara.getId()
.toString());
testCharacterization(chara.getId().toString());
}
}
} catch (Exception e) {
System.out
.println("Exception getting all Characterization by CQLQuery: "
+ e);
builder.append("Exception getting all Characterization by CQLQuery: "
+ e + "\n");
}
}
public void testProtocol(String id) {
System.out.println("Test Protocol with id=" + id);
builder.append("Test Protocol with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Protocol");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Protocol");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Protocol p = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
p = (Protocol) obj;
System.out.println("Protocol: id=" + p.getId() + "\tName="
+ p.getName() + "\tAbbreviation=" + p.getAbbreviation()
+ "\tType=" + p.getType() + "\tVersion="
+ p.getVersion());
builder.append("Protocol: id=" + p.getId() + "\tName="
+ p.getName() + "\tAbbreviation=" + p.getAbbreviation()
+ "\tType=" + p.getType() + "\tVersion="
+ p.getVersion() + "\n");
// add function for get protocol file by protocol id
testGetFileByProtocolId(p.getId().toString());
}
} catch (Exception e) {
System.out.println("Exception getting Protocol for id=" + id + ": "
+ e);
builder.append("Exception getting Protocol for id=" + id + ": "
+ e + "\n");
}
}
public void testGetAllProtocolsByCQLQuery() {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Protocol");
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Protocol");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Protocol p = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
p = (Protocol) obj;
System.out.println("Protocol: id=" + p.getId() + "\tName="
+ p.getName() + "\tAbbreviation=" + p.getAbbreviation()
+ "\tType=" + p.getType() + "\tVersion="
+ p.getVersion());
builder.append("Protocol: id=" + p.getId() + "\tName="
+ p.getName() + "\tAbbreviation=" + p.getAbbreviation()
+ "\tType=" + p.getType() + "\tVersion="
+ p.getVersion() + "\n");
// add function for get protocol file by protocol id
testGetFileByProtocolId(p.getId().toString());
}
} catch (Exception e) {
System.out.println("Exception getting all protocols: " + e);
builder.append("Exception getting all protocols: " + e + "\n");
}
}
public void testChemicalAssociation(String id) {
// "8847369"
System.out.println("Test ChemicalAssociation with id=" + id);
builder.append("Test ChemicalAssociation with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.ChemicalAssociation");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.ChemicalAssociation");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
ChemicalAssociation ca = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
ca = (ChemicalAssociation) obj;
System.out.println("ChemicalAssociation Desc: "
+ ca.getDescription() + ", id: " + ca.getId());
builder.append("ChemicalAssociation Desc: "
+ ca.getDescription() + ", id: " + ca.getId() + "\n");
}
} catch (Exception e) {
System.out.println("Exception getting ChemicalAssociation for id="
+ id + ": " + e);
builder.append("Exception getting ChemicalAssociation for id="
+ id + ": " + e + "\n");
}
}
public void testPublication(String id) {
// "8847369"
System.out.println("Test Publication with id=" + id);
builder.append("Test Publication with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Publication");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Publication");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Publication p = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
p = (Publication) obj;
System.out.println("Publication: id=" + p.getId() + "\tName="
+ p.getName() + "\tDesc=" + p.getDescription()
+ "\tTitle=" + p.getTitle());
builder.append("Publication: id=" + p.getId() + "\tName="
+ p.getName() + "\tDesc=" + p.getDescription()
+ "\tTitle=" + p.getTitle() + "\n");
// TODO add CQL for authors and keywords by publication
loadAuthorsForPublication(p);
Collection<Author> authorCollection = p.getAuthorCollection();
for (java.util.Iterator<Author> itr = authorCollection
.iterator(); itr.hasNext();) {
Author a = itr.next();
System.out.println("Author First Name=" + a.getFirstName()
+ "\tLast Name=" + a.getLastName());
builder.append("Author First Name=" + a.getFirstName()
+ "\tLast Name=" + a.getLastName() + "\n");
}
loadKeywordsForPublication(p);
Collection<Keyword> keywordCollection = p
.getKeywordCollection();
for (java.util.Iterator<Keyword> itr = keywordCollection
.iterator(); itr.hasNext();) {
Keyword k = itr.next();
System.out.println("Keyword Name=" + k.getName() + "\tId="
+ k.getId());
builder.append("Keyword Name=" + k.getName() + "\tId="
+ k.getId() + "\n");
}
}
} catch (Exception e) {
System.out.println("Exception getting Publication for id=" + id
+ ": " + e);
builder.append("Exception getting Publication for id=" + id
+ ": " + e + "\n");
}
}
private void loadAuthorsForPublication(Publication publication) {
CQLQuery query = new CQLQuery();
builder.append("Test get AuthorsForPublication id=" + publication.getId() + "\n");
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Author");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Publication");
association.setRoleName("publicationCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(publication.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Author");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Author author = null;
publication.setAuthorCollection(new HashSet<Author>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
author = (Author) obj;
System.out.println("Author id=" + author.getId() + "\tName=" + author.getFirstName() +
" " + author.getLastName());
builder.append("Author id=" + author.getId() + "\tName=" + author.getFirstName() +
" " + author.getLastName() + "\n");
publication.getAuthorCollection().add(author);
}
} catch (Exception e) {
System.out.println("Exception getting Authors for Publication id="
+ publication.getId() + ": " + e);
builder.append("Exception getting Authors for Publication id="
+ publication.getId() + ": " + e + "\n");
}
}
private void loadKeywordsForPublication(Publication publication) {
// load keywords for a file
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Keyword");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.File");
association.setRoleName("fileCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(publication.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Keyword");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Set<Keyword> keywords = new HashSet<Keyword>();
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Keyword keyword = (Keyword) obj;
builder.append("Keyword id=" +keyword.getId() + "\tName=" + keyword.getName() + "\n");
keywords.add(keyword);
}
publication.setKeywordCollection(keywords);
} catch (Exception e) {
System.out.println("Exception getting keyword for publication: "
+ e);
builder.append("Exception getting keyword for publication: "
+ e + "\n");
}
}
public void testActivationMethod(String id) {
// "3833872"
System.out.println("Testing ActivationMethod with id=" + id);
builder.append("Testing ActivationMethod with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.ActivationMethod");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.ActivationMethod");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
ActivationMethod am = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
am = (ActivationMethod) obj;
System.out.println("Activation Effect: id=" + am.getId()
+ "\tActivationEffect=" + am.getActivationEffect()
+ ", Type=" + am.getType());
builder.append("Activation Effect: id=" + am.getId()
+ "\tActivationEffect=" + am.getActivationEffect()
+ ", Type=" + am.getType() + "\n");
}
} catch (Exception e) {
System.out.println("Exception getting ActivationMethod for id="
+ id + ": " + e);
builder.append("Exception getting ActivationMethod for id="
+ id + ": " + e + "\n");
}
}
public void testNanomaterialEntity(String id) {
// "6160399"
System.out.println("Testing NanoMaterialEntity with id=" + id);
builder.append("Testing NanoMaterialEntity with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.NanomaterialEntity");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.NanomaterialEntity");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
NanomaterialEntity nanoEntity = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
nanoEntity = (NanomaterialEntity) obj;
System.out.println("NanoMaterial entity: id="
+ nanoEntity.getId() + "\tDesc="
+ nanoEntity.getDescription() + "\tCreatedBy="
+ nanoEntity.getCreatedBy());
builder.append("NanoMaterial entity: id="
+ nanoEntity.getId() + "\tDesc="
+ nanoEntity.getDescription() + "\tCreatedBy="
+ nanoEntity.getCreatedBy() + "\n");
}
} catch (Exception e) {
System.out.println("Exception getting NanomaterialEntity for id="
+ id + ": " + e);
builder.append("Exception getting NanomaterialEntity for id="
+ id + ": " + e + "\n");
}
}
public void testSample(String id) {
System.out.println("Testing Sample with id=" + id);
builder.append("Testing Sample with id=" + id + "\n");
// "3735553"
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.particle.Sample");
Attribute attribute = new Attribute();
/*
* attribute.setName("name"); attribute.setPredicate(Predicate.LIKE);
* attribute.setValue("NCL-23-1"); //"20917507"); //NCL-23-1
*/
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Sample");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Sample sample = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
sample = (Sample) obj;
System.out.println("Sample: Name=" + sample.getName() + ", id="
+ sample.getId());
builder.append("Sample: Name=" + sample.getName() + ", id="
+ sample.getId() + "\n");
//testGetPublicationsBySampleId(id);
testGetKeywordsBySampleId(id);
testGetOtherPointOfContactsBySampleId(id);
testGetPrimaryPointOfContactBySampleId(id);
}
} catch (Exception e) {
System.out.println("Exception getting Sample for id=" + id + ": "
+ e);
builder.append("Exception getting Sample for id=" + id + ": "
+ e + "\n");
}
}
public void testFunction(String id) {
// "10944705"
System.out.println("Testing Function with id=" + id);
builder.append("Testing Function with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.particle.Function");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Function");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Function fe = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
fe = (Function) obj;
System.out.println("Function: desc=" + fe.getDescription()
+ "\tId=" + fe.getId());
builder.append("Function: desc=" + fe.getDescription()
+ "\tId=" + fe.getId() + "\n");
}
} catch (Exception e) {
System.out.println("Exception getting Function for id=" + id + ": "
+ e);
builder.append("Exception getting Function for id=" + id + ": "
+ e + "\n");
}
}
public void testFunctionalizingEntity(String id) {
// "6225945"
System.out.println("Testing FunctionalizingEntity with id=" + id);
builder.append("Testing FunctionalizingEntity with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
FunctionalizingEntity fe = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
fe = (FunctionalizingEntity) obj;
System.out.println("FunctionalizingEntity: name="
+ fe.getName() + "\tId=" + fe.getId());
builder.append("FunctionalizingEntity: name="
+ fe.getName() + "\tId=" + fe.getId() + "\n");
}
} catch (Exception e) {
System.out
.println("Exception getting FunctionalizaingEntity for id="
+ id + ": " + e);
builder.append("Exception getting FunctionalizaingEntity for id="
+ id + ": " + e + "\n");
}
}
public void testCharacterization(String id) {
// "10977286"
System.out.println("Testing characterization with id=" + id);
builder.append("Testing characterization with id=" + id + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.Characterization");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
target.setAttribute(attribute);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Characterization");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Characterization chara = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
chara = (Characterization) obj;
System.out.println("characterization: id=" + chara.getId()
+ "\tDesignMethodDesc: "
+ chara.getDesignMethodsDescription());
builder.append("characterization: id=" + chara.getId()
+ "\tDesignMethodDesc: "
+ chara.getDesignMethodsDescription() + "\n");
}
} catch (Exception e) {
System.out.println("Exception getting Characterization for id="
+ id + ": " + e);
builder.append("Exception getting Characterization for id="
+ id + ": " + e + "\n");
}
}
public void testGetKeywordsBySampleId(String sampleId) {
// String sampleId = "20917507";
System.out.println("Testing getKeyworkdsBySampleId: " + sampleId);
builder.append("Testing getKeyworkdsBySampleId: " + sampleId);
try {
Keyword[] keywords = gridClient.getKeywordsBySampleId(sampleId);
if (keywords != null) {
for (Keyword keyword : keywords) {
if (keyword != null) {
System.out.println("Keyword name: " + keyword.getName()
+ "\tId: " + keyword.getId());
builder.append("Keyword name: " + keyword.getName()
+ "\tId: " + keyword.getId() + "\n");
}
}
}
} catch (Exception e) {
System.out
.println("Exception getting KeywordsBySampleId for sampleId="
+ sampleId + ": " + e);
builder.append("Exception getting KeywordsBySampleId for sampleId="
+ sampleId + ": " + e + "\n");
}
System.out
.println("Finished printing getKeyworkdsBySampleId results for sampleId: "
+ sampleId);
builder.append("Finished printing getKeyworkdsBySampleId results for sampleId: "
+ sampleId + "\n");
}
public void testGetPrimaryPointOfContactBySampleId(String sampleId) {
// String sampleId = "20917507";
System.out.println("Testing getPrimaryPointOfContactBySampleId : "
+ sampleId);
builder.append("Testing getPrimaryPointOfContactBySampleId : "
+ sampleId + "\n");
try {
PointOfContact contact = gridClient
.getPrimaryPointOfContactBySampleId(sampleId);
if (contact != null) {
System.out.println("primary contact name: "
+ contact.getFirstName() + "\t" + contact.getLastName()
+ "\tId: " + contact.getId() + "\tPhone: "
+ contact.getPhone() + "\tRole: " + contact.getRole()
+ "\tEmail: " + contact.getEmail());
builder.append("primary contact name: "
+ contact.getFirstName() + "\t" + contact.getLastName()
+ "\tId: " + contact.getId() + "\tPhone: "
+ contact.getPhone() + "\tRole: " + contact.getRole()
+ "\tEmail: " + contact.getEmail() + "\n");
// TODO add CQL for organization by POC id
System.out
.println("Getting Organization for point of contact id="
+ contact.getId());
builder.append("Getting Organization for point of contact id="
+ contact.getId() + "\n");
loadOrganizationForPointOfContact(contact);
}
} catch (Exception e) {
System.out
.println("Exception getting PrimaryPointOfContactBySampleId for sampleId="
+ sampleId + ": " + e);
builder.append("Exception getting PrimaryPointOfContactBySampleId for sampleId="
+ sampleId + ": " + e + "\n");
}
System.out
.println("Finished printing getPrimaryPointOfContactBySampleId results for sampleId: "
+ sampleId );
}
private void loadOrganizationForPointOfContact(PointOfContact poc) {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Organization");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.common.PointOfContact");
association.setRoleName("pointOfContactCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(poc.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Organization");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Organization org = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
org = (Organization) obj;
if (org != null) {
System.out.println("Organization: id=" + org.getId()
+ "\tName=" + org.getName() + "\tAddress="
+ org.getStreetAddress1() + " " + org.getCity()
+ " " + org.getState() + " " + org.getPostalCode());
builder.append("Organization: id=" + org.getId()
+ "\tName=" + org.getName() + "\tAddress="
+ org.getStreetAddress1() + " " + org.getCity()
+ " " + org.getState() + " " + org.getPostalCode() + "\n");
}
}
poc.setOrganization(org);
} catch (Exception e) {
System.out
.println("Exception getting organization for point of contact id="
+ poc.getId() + ": " + e);
builder.append("Exception getting organization for point of contact id="
+ poc.getId() + ": " + e + "\n");
}
}
public void testGetOtherPointOfContactsBySampleId(String sampleId) {
// String sampleId = "3735553";
System.out.println("Testing getOtherPointOfContactsBySampleId : "
+ sampleId);
builder.append("Testing getOtherPointOfContactsBySampleId : "
+ sampleId + "\n");
try {
PointOfContact[] contacts = gridClient
.getOtherPointOfContactsBySampleId(sampleId);
if (contacts != null) {
for (PointOfContact contact : contacts) {
if (contact != null) {
System.out.println("primary contact name: "
+ contact.getFirstName() + "\t"
+ contact.getLastName() + "\tId: "
+ contact.getId() + "\tPhone: "
+ contact.getPhone() + "\tRole: "
+ contact.getRole() + "\tEmail: "
+ contact.getEmail());
builder.append("primary contact name: "
+ contact.getFirstName() + "\t"
+ contact.getLastName() + "\tId: "
+ contact.getId() + "\tPhone: "
+ contact.getPhone() + "\tRole: "
+ contact.getRole() + "\tEmail: "
+ contact.getEmail() + "\n");
// TODO add CQL for organization by POC id
System.out
.println("Getting Organization for other point of contact id="
+ contact.getId());
builder.append("Getting Organization for other point of contact id="
+ contact.getId() + "\n");
loadOrganizationForPointOfContact(contact);
}
}
}
} catch (Exception e) {
System.out
.println("Exception getting OtherPointOfContactsBySampleId for sampleId="
+ sampleId + ": " + e);
builder.append("Exception getting OtherPointOfContactsBySampleId for sampleId="
+ sampleId + ": " + e + "\n");
}
System.out
.println("Finished printing getPrimaryPointOfContactBySampleId results for sampleId: "
+ sampleId);
}
public void testGetExperimentConfigsByCharacterizationId(String charId) {
System.out
.println("Testing testGetExperimentConfigsByCharacterizationId : "
+ charId);
builder.append("Testing testGetExperimentConfigsByCharacterizationId : "
+ charId + "\n");
try {
ExperimentConfig[] experimentConfigs = gridClient
.getExperimentConfigsByCharacterizationId(charId);
if (experimentConfigs != null) {
for (ExperimentConfig exp : experimentConfigs) {
if (exp != null) {
System.out.println("ExperimentConfig Id: "
+ exp.getId() + "\tDesc: "
+ exp.getDescription());
builder.append("ExperimentConfig Id: "
+ exp.getId() + "\tDesc: "
+ exp.getDescription() + "\n");
// TODO add CQL for instruments and technique by
// experiment
// config id
loadTechniqueForConfig(exp);
loadInstrumentsForConfig(exp);
}
}
}
} catch (Exception e) {
System.out
.println("Exception getting ExperimentConfigsByCharacterizationId for charid="
+ charId + ": " + e);
builder.append("Exception getting ExperimentConfigsByCharacterizationId for charid="
+ charId + ": " + e + "\n");
}
System.out
.println("Finished printing testGetExperimentConfigsByCharacterizationId results for charId: "
+ charId);
}
private void loadTechniqueForConfig(ExperimentConfig config) {
System.out.println("getting Technique for Config id=" + config.getId());
builder.append("getting Technique for Config id=" + config.getId() + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Technique");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.common.ExperimentConfig");
association.setRoleName("experimentConfigCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(config.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Technique");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Technique technique = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
technique = (Technique) obj;
if (technique != null) {
System.out.println("Technique id=" + technique.getId()
+ "\tAbbreviation=" + technique.getAbbreviation()
+ "\tType=" + technique.getType());
builder.append("Technique id=" + technique.getId()
+ "\tAbbreviation=" + technique.getAbbreviation()
+ "\tType=" + technique.getType() + "\n");
}
}
config.setTechnique(technique);
} catch (Exception e) {
System.out
.println("Exception getting Technique for ExperimentConfig id="
+ config.getId() + ": " + e);
builder.append("Exception getting Technique for ExperimentConfig id="
+ config.getId() + ": " + e + "\n");
}
}
private void loadInstrumentsForConfig(ExperimentConfig config) {
System.out.println("Getting Instruments for Config id="
+ config.getId());
builder.append("Getting Instruments for Config id="
+ config.getId() + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Instrument");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.common.ExperimentConfig");
association.setRoleName("experimentConfigCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(config.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Instrument");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
config.setInstrumentCollection(new HashSet<Instrument>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Instrument instrument = (Instrument) obj;
config.getInstrumentCollection().add(instrument);
if (instrument != null) {
System.out.println("Instrument id=" + instrument.getId()
+ "\tType=" + instrument.getType() + "\tModelName="
+ instrument.getModelName() + "\tManufacturer="
+ instrument.getManufacturer());
builder.append("Instrument id=" + instrument.getId()
+ "\tType=" + instrument.getType() + "\tModelName="
+ instrument.getModelName() + "\tManufacturer="
+ instrument.getManufacturer() + "\n");
}
}
} catch (Exception e) {
System.out
.println("Exception getting Instrument for ExperimentConfig id="
+ config.getId() + ": " + e);
builder.append("Exception getting Instrument for ExperimentConfig id="
+ config.getId() + ": " + e + "\n");
}
}
public void testGetFindingsByCharacterizationId(String charId) {
// String charId = "3932251";
System.out.println("Testing testGetFindingsByCharacterizationId : "
+ charId);
builder.append("Testing testGetFindingsByCharacterizationId : "
+ charId + "\n");
try {
Finding[] findings = gridClient
.getFindingsByCharacterizationId(charId);
if (findings != null) {
for (Finding f : findings) {
if (f != null) {
System.out.println("Finding Id: " + f.getId()
+ "\tCreatedBy: " + f.getCreatedBy());
builder.append("Finding Id: " + f.getId()
+ "\tCreatedBy: " + f.getCreatedBy() + "\n");
// TODO add CQL for data and files by finding id, and
// conditions by datum id
loadDataForFinding(f);
loadFilesForFinding(f);
}
}
}
} catch (Exception e) {
System.out
.println("Exception getting FindingsByCharacterizationId for charid="
+ charId + ": " + e);
builder.append("Exception getting FindingsByCharacterizationId for charid="
+ charId + ": " + e + "\n");
}
System.out
.println("Finished printing testGetFindingsByCharacterizationId results for charId: "
+ charId);
}
private void loadDataForFinding(Finding finding) {
System.out.println("Getting Data for Finding id=" + finding.getId());
builder.append("Getting Data for Finding id=" + finding.getId() + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Datum");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Finding");
association.setRoleName("finding");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(finding.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Datum");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
finding.setDatumCollection(new HashSet<Datum>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Datum datum = (Datum) obj;
if (datum != null) {
System.out.println("Datum id=" + datum.getId() + "\tName="
+ datum.getName() + "\tValueType="
+ datum.getValueType() + "\tValueUnit="
+ datum.getValueUnit() + "\tValue="
+ datum.getValue());
builder.append("Datum id=" + datum.getId() + "\tName="
+ datum.getName() + "\tValueType="
+ datum.getValueType() + "\tValueUnit="
+ datum.getValueUnit() + "\tValue="
+ datum.getValue() + "\n");
loadConditionsForDatum(datum);
finding.getDatumCollection().add(datum);
}
}
} catch (Exception e) {
System.out.println("Exception getting Data for Finding id="
+ finding.getId() + ": " + e);
builder.append("Exception getting Data for Finding id="
+ finding.getId() + ": " + e + "\n");
}
}
private void loadConditionsForDatum(Datum datum) {
System.out.println("Getting Condition for Datum id=" + datum.getId());
builder.append("Getting Condition for Datum id=" + datum.getId() + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Condition");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Datum");
association.setRoleName("datumCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(datum.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Condition");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
datum.setConditionCollection(new HashSet<Condition>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Condition condition = (Condition) obj;
if (condition != null) {
System.out.println("Condition id=" + condition.getId()
+ "\tName=" + condition.getName() + "\tProperty="
+ condition.getProperty() + "\tValue="
+ condition.getValue() + "\tValueType="
+ condition.getValueType() + "\tValueUnit="
+ condition.getValueUnit());
builder.append("Condition id=" + condition.getId()
+ "\tName=" + condition.getName() + "\tProperty="
+ condition.getProperty() + "\tValue="
+ condition.getValue() + "\tValueType="
+ condition.getValueType() + "\tValueUnit="
+ condition.getValueUnit() + "\n");
}
datum.getConditionCollection().add(condition);
}
} catch (Exception e) {
System.out.println("Exception getting Conditions for Datum id="
+ datum.getId() + ": " + e);
builder.append("Exception getting Conditions for Datum id="
+ datum.getId() + ": " + e + "\n");
}
}
private void loadFilesForFinding(Finding finding) {
System.out.println("Getting Files for Finding id=" + finding.getId());
builder.append("Getting Files for Finding id=" + finding.getId() + "\n");
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.File");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Finding");
association.setRoleName("findingCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(finding.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.File");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
finding.setFileCollection(new HashSet<File>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
File file = (File) obj;
if (file != null) {
System.out.println("File id=" + file.getId() + "\tName="
+ file.getName() + "\tDesc="
+ file.getDescription() + "\tTitle="
+ file.getTitle() + "\tUri=" + file.getUri());
builder.append("File id=" + file.getId() + "\tName="
+ file.getName() + "\tDesc="
+ file.getDescription() + "\tTitle="
+ file.getTitle() + "\tUri=" + file.getUri() + "\n");
}
finding.getFileCollection().add(file);
}
} catch (Exception e) {
System.out.println("Exception getting Files for Finding id="
+ finding.getId() + ": " + e);
builder.append("Exception getting Files for Finding id="
+ finding.getId() + ": " + e + "\n");
}
}
public void testGetProtocolByCharacterizationId(String charId) {
// String charId = "21867791";
System.out.println("Testing testGetProtocolByCharacterizationId : "
+ charId);
builder.append("Testing testGetProtocolByCharacterizationId : "
+ charId + "\n");
try {
Protocol p = gridClient.getProtocolByCharacterizationId(charId);
if (p != null) {
System.out.println("Protocol Id: " + p.getId()
+ "\tCreatedBy: " + p.getCreatedBy() + "\tName: "
+ p.getName() + "\tType: " + p.getType());
builder.append("Protocol Id: " + p.getId()
+ "\tCreatedBy: " + p.getCreatedBy() + "\tName: "
+ p.getName() + "\tType: " + p.getType() + "\n");
}
} catch (Exception e) {
System.out
.println("Exception getting ProtocolByCharacterizationId for charid="
+ charId + ": " + e);
builder.append("Exception getting ProtocolByCharacterizationId for charid="
+ charId + ": " + e + "\n");
}
System.out
.println("Finished printing testGetProtocolByCharacterizationId results for charId: "
+ charId + "\n");
}
public void testGetPublicationsBySampleId(String sampleId) {
// String sampleId = "20917507";
System.out.println("Testing getPublicationBySampleId : " + sampleId);
builder.append("Testing getPublicationBySampleId : " + sampleId + "\n");
try {
Publication[] pubs = gridClient.getPublicationsBySampleId(sampleId);
if (pubs != null) {
for (Publication p : pubs) {
if (p != null) {
System.out.print("Publication Id: " + p.getId()
+ "\tDesc: " + p.getDescription() + "\tName: "
+ p.getName() + "\tJournalName: "
+ p.getJournalName() + "\tTitle: "
+ p.getTitle());
builder.append("Publication Id: " + p.getId()
+ "\tDesc: " + p.getDescription() + "\tName: "
+ p.getName() + "\tJournalName: "
+ p.getJournalName() + "\tTitle: "
+ p.getTitle() + "\n");
}
}
}
} catch (Exception e) {
System.out
.println("Exception when testing getPublicationBySampleId for sampleId="
+ sampleId);
builder.append("Exception when testing getPublicationBySampleId for sampleId="
+ sampleId + "\n");
}
System.out
.println("Finished printing getPrimaryPointOfContactBySampleId results for sampleId: "
+ sampleId);
}
public void testGetSampleIds() {
try {
String[] sampleIds = gridClient.getSampleIds("", "", null, null,
null, null, null);
System.out
.println("Testing getSampleIds operation.... \n"
+ "For every sample, test get Publication, keywords, primary contact and other contact.");
builder.append("Testing getSampleIds operation.... \n"
+ "For every sample, test get Publication, keywords, primary contact and other contact." + "\n");
for (String id : sampleIds) {
testSample(id);
}
} catch (Exception e) {
System.out.println("Exception getting SampleIds: " + e);
builder.append("Exception getting SampleIds: " + e + "\n");
}
System.out.println("\nFinished testing samples.... \n");
}
public void testCharacterizationAndCompositionBySampleIds() {
try {
String[] sampleIds = gridClient.getSampleIds("", "", null, null,
null, null, null);
System.out
.println("Testing getSampleIds operation.... \n"
+ "For every sample, test get Publication, keywords, primary contact and other contact.");
builder.append("Testing getSampleIds operation.... \n"
+ "For every sample, test get Publication, keywords, primary contact and other contact." + "\n");
for (String id : sampleIds) {
testGetCharacterizationsBySampleIdByCQLQuery(id);
testGetCompositionBySampleIdByCQLQuery(id);
}
} catch (Exception e) {
System.out.println("Exception getting SampleIds: " + e);
builder.append("Exception getting SampleIds: " + e + "\n");
}
System.out.println("\nFinished testing samples.... \n");
}
public void testGetCharacterizationsBySampleIdByCQLQuery(String id) {
// TODO add this CQL and related functions for experiment configs,
// findings and point of contacts.
try {
CQLQuery query = new CQLQuery();
/*
* QueryModifier modifier = new QueryModifier();
* modifier.setCountOnly(true); query.setQueryModifier(modifier);
*/
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.Characterization");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.particle.Sample");
association.setRoleName("sample");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Characterization");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Characterization chara = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
chara = (Characterization) obj;
if (chara != null) {
testGetFindingsByCharacterizationId(chara.getId()
.toString());
testGetProtocolByCharacterizationId(chara.getId()
.toString());
testGetExperimentConfigsByCharacterizationId(chara.getId()
.toString());
}
}
} catch (Exception e) {
System.out
.println("Exception getting characterizations by Sample ID through CQL: "
+ e);
builder.append("Exception getting characterizations by Sample ID through CQL: "
+ e + "\n");
}
}
public void testGetCompositionBySampleIdByCQLQuery(String id) {
try {
// TODO add this CQl and other CQLs for chemical association,
// nanomaterial entities, functionalizing entities by composition
// id, and composing elements, functions by nanomaterial entity id,
// functions by functionalizing entity id, and function for files
// based on composition info id
// find all nanomaterial entity class names, functionalizing entity
// class names first
String[] sampleViewStrs = gridClient.getSampleViewStrs(id);
// column 8 contains characterization short class names
String[] nanoEntityClassNames = null;
if (sampleViewStrs.length > 5
&& !StringUtils.isEmpty(sampleViewStrs[5])) {
nanoEntityClassNames = sampleViewStrs[5]
.split(Constants.VIEW_CLASSNAME_DELIMITER);
}
String[] funcEntityClassNames = null;
if (sampleViewStrs.length > 6
&& !StringUtils.isEmpty(sampleViewStrs[6])) {
funcEntityClassNames = sampleViewStrs[6]
.split(Constants.VIEW_CLASSNAME_DELIMITER);
}
String[] assocClassNames = null;
if (sampleViewStrs.length > 8
&& !StringUtils.isEmpty(sampleViewStrs[8])) {
assocClassNames = sampleViewStrs[8]
.split(Constants.VIEW_CLASSNAME_DELIMITER);
}
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.SampleComposition");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.particle.Sample");
association.setRoleName("sample");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(id);
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.SampleComposition");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
SampleComposition sampleComposition = null;
System.out
.println("getting CompositionBySampleIdByCQLQuery... sampleId="
+ id);
builder.append("getting CompositionBySampleIdByCQLQuery... sampleId="
+ id + "\n");
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
sampleComposition = (SampleComposition) obj;
System.out.println("SampleComposition id="
+ sampleComposition.getId());
builder.append("SampleComposition id="
+ sampleComposition.getId() + "\n");
sampleComposition.getChemicalAssociationCollection();
sampleComposition.getFunctionalizingEntityCollection();
sampleComposition.getNanomaterialEntityCollection();
// sampleComposition.
loadCompositionAssociations(sampleComposition,
nanoEntityClassNames, funcEntityClassNames,
assocClassNames);
// compositionBean = new CompositionBean(sampleComposition);
}
} catch (Exception e) {
System.out
.println("Exception getting composition by Sample ID through CQL: "
+ e);
builder.append("Exception getting composition by Sample ID through CQL: "
+ e + "\n");
}
}
private void loadCompositionAssociations(SampleComposition composition,
String[] nanoEntityClassNames, String[] funcEntityClassNames,
String[] assocClassNames) {
try {
loadNanomaterialEntitiesForComposition(composition,
nanoEntityClassNames);
loadFunctionalizingEntitiesForComposition(composition,
funcEntityClassNames);
loadChemicalAssociationsForComposition(composition, assocClassNames);
File[] files = gridClient.getFilesByCompositionInfoId(composition
.getId().toString(), ClassUtils
.getShortClassName("SampleComposition"));
if (files != null && files.length > 0) {
// loadKeywordsForFiles(files);
composition.setFileCollection(new HashSet<File>(Arrays
.asList(files)));
}
} catch (Exception e) {
System.out
.println("Exception loading Composition Associationsfor: "
+ e);
builder.append("Exception loading Composition Associationsfor: "
+ e + "\n");
}
}
private void loadNanomaterialEntitiesForComposition(
SampleComposition composition, String[] nanoEntityClassNames) {
try {
if (nanoEntityClassNames != null) {
for (String name : nanoEntityClassNames) {
String fullClassName = null;
if (ClassUtils.getFullClass(name) != null) {
fullClassName = ClassUtils.getFullClass(name)
.getCanonicalName();
} else {
fullClassName = ClassUtils.getFullClass(
OtherNanomaterialEntity.class
.getCanonicalName()).getCanonicalName();
}
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName(fullClassName);
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.SampleComposition");
association.setRoleName("sampleComposition");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(composition.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results.setTargetClassname(fullClassName);
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(
results);
NanomaterialEntity nanoEntity = null;
composition
.setNanomaterialEntityCollection(new HashSet<NanomaterialEntity>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
nanoEntity = (NanomaterialEntity) obj;
if (nanoEntity != null) {
System.out.println("NanomaterialEntity id="
+ nanoEntity.getId() + "\tDesc="
+ nanoEntity.getDescription());
builder.append("NanomaterialEntity id="
+ nanoEntity.getId() + "\tDesc="
+ nanoEntity.getDescription() + "\n");
}
}
}
}
} catch (Exception e) {
System.out.println("Exception getting nanomaterial for composition"
+ ": " + e);
builder.append("Exception getting nanomaterial for composition"
+ ": " + e + "\n");
}
}
private void loadFunctionalizingEntitiesForComposition(
SampleComposition composition, String[] funcEntityClassNames) {
try {
if (funcEntityClassNames != null) {
for (String name : funcEntityClassNames) {
String fullClassName = null;
if (ClassUtils.getFullClass(name) != null) {
fullClassName = ClassUtils.getFullClass(name)
.getCanonicalName();
} else {
fullClassName = ClassUtils.getFullClass(
OtherFunctionalizingEntity.class
.getCanonicalName()).getCanonicalName();
}
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName(fullClassName);
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.SampleComposition");
association.setRoleName("sampleComposition");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(composition.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results.setTargetClassname(fullClassName);
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(
results);
FunctionalizingEntity funcEntity = null;
composition
.setFunctionalizingEntityCollection(new HashSet<FunctionalizingEntity>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
funcEntity = (FunctionalizingEntity) obj;
System.out.println("FunctionalizingEntity id="
+ funcEntity.getId() + "\tName="
+ funcEntity.getName() + "\tDesc="
+ funcEntity.getDescription()
+ "\tMolecularFormula="
+ funcEntity.getMolecularFormula()
+ "\tPubChemDataSourceName="
+ funcEntity.getPubChemDataSourceName()
+ "\tMolecularFormulaType="
+ funcEntity.getMolecularFormulaType()
+ "\tValueUnit=" + funcEntity.getValueUnit());
builder.append("FunctionalizingEntity id="
+ funcEntity.getId() + "\tName="
+ funcEntity.getName() + "\tDesc="
+ funcEntity.getDescription()
+ "\tMolecularFormula="
+ funcEntity.getMolecularFormula()
+ "\tPubChemDataSourceName="
+ funcEntity.getPubChemDataSourceName()
+ "\tMolecularFormulaType="
+ funcEntity.getMolecularFormulaType()
+ "\tValueUnit=" + funcEntity.getValueUnit() + "\n");
loadFunctionalizingEntityAssociations(funcEntity);
composition.getFunctionalizingEntityCollection().add(
funcEntity);
}
}
}
} catch (Exception e) {
System.out
.println("Exception getting FunctionalizingEntity for Composition for id="
+ composition.getId() + ": " + e);
builder.append("Exception getting FunctionalizingEntity for Composition for id="
+ composition.getId() + ": " + e + "\n");
}
}
private void loadChemicalAssociationsForComposition(
SampleComposition composition, String[] assocClassNames) {
try {
if (assocClassNames != null) {
for (String name : assocClassNames) {
String fullClassName = null;
if (ClassUtils.getFullClass(name) != null) {
fullClassName = ClassUtils.getFullClass(name)
.getCanonicalName();
} else {
fullClassName = ClassUtils.getFullClass(
OtherChemicalAssociation.class
.getCanonicalName()).getCanonicalName();
}
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName(fullClassName);
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.SampleComposition");
association.setRoleName("sampleComposition");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(composition.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results.setTargetClassname(fullClassName);
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(
results);
ChemicalAssociation assoc = null;
composition
.setChemicalAssociationCollection(new HashSet<ChemicalAssociation>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
assoc = (ChemicalAssociation) obj;
System.out.println("ChemicalAssociation id="
+ assoc.getId() + "\tDesc="
+ assoc.getDescription());
builder.append("ChemicalAssociation id="
+ assoc.getId() + "\tDesc="
+ assoc.getDescription() + "\n");
loadChemicalAssociationAssociations(assoc);
composition.getChemicalAssociationCollection().add(
assoc);
}
}
}
} catch (Exception e) {
System.out
.println("Exception loading ChemicalAssociation for Composition id="
+ composition.getId() + ": " + e);
builder.append("Exception loading ChemicalAssociation for Composition id="
+ composition.getId() + ": " + e + "\n");
}
}
private void loadChemicalAssociationAssociations(ChemicalAssociation assoc) {
try {
File[] files = gridClient.getFilesByCompositionInfoId(assoc.getId()
.toString(), "ChemicalAssociation");
if (files != null && files.length > 0) {
// loadKeywordsForFiles(files);
assoc
.setFileCollection(new HashSet<File>(Arrays
.asList(files)));
}
loadAssociatedElementsForChemicalAssociation(assoc, "A");
loadAssociatedElementsForChemicalAssociation(assoc, "B");
} catch (Exception e) {
System.out.println("Exception loading ChemicalAssociation for id="
+ assoc.getId() + ": " + e);
builder.append("Exception loading ChemicalAssociation for id="
+ assoc.getId() + ": " + e + "\n");
}
}
private void loadAssociatedElementsForChemicalAssociation(
ChemicalAssociation assoc, String elementNumber) {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.AssociatedElement");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.ChemicalAssociation");
String roleName = "chemicalAssociation" + elementNumber + "Collection";
association.setRoleName(roleName);
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(assoc.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.AssociatedElement");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
AssociatedElement element = (AssociatedElement) obj;
if (element instanceof ComposingElement) {
loadInherentFunctionsForComposingElement((ComposingElement) element);
} else if (element instanceof FunctionalizingEntity) {
loadFunctionalizingEntityAssociations((FunctionalizingEntity) element);
}
if (elementNumber.equals("A")) {
assoc.setAssociatedElementA(element);
} else if (elementNumber.equals("B")) {
assoc.setAssociatedElementB(element);
}
}
} catch (Exception e) {
System.out
.println("Exception getting AssocatedElement for ChenicalAssociation: "
+ e);
builder.append("Exception getting AssocatedElement for ChenicalAssociation: "
+ e + "\n");
}
}
private void loadFunctionalizingEntityAssociations(
FunctionalizingEntity entity) throws Exception {
File[] files = gridClient.getFilesByCompositionInfoId(entity.getId()
.toString(), "FunctionalizingEntity");
if (files != null && files.length > 0) {
for (File file : files) {
System.out.println("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri());
builder.append("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri() + "\n");
// TODO add CQL for keywords by file id
loadKeywordsForFile(file);
}
}
}
private void loadKeywordsForFile(File file) {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Keyword");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.File");
association.setRoleName("fileCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(file.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Keyword");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
file.setKeywordCollection(new HashSet<Keyword>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Keyword keyword = (Keyword) obj;
if (keyword != null) {
System.out.println("Keyword id=" + keyword.getId()
+ "\tName=" + keyword.getName());
builder.append("Keyword id=" + keyword.getId()
+ "\tName=" + keyword.getName() + "\n");
}
file.getKeywordCollection().add(keyword);
}
} catch (Exception e) {
System.out.println("Exception getting keyword for file id="
+ file.getId() + ": " + e);
builder.append("Exception getting keyword for file id="
+ file.getId() + ": " + e + "\n");
}
}
public void testGetPublicationIdsBy() {
try {
String[] pubIds = gridClient.getPublicationIdsBy("", "", "", null,
null, null, null, null, null, null, null);
System.out.println("Testing getPublicationIdsBy operation.... \n "
+ "For every publication, test Publication");
builder.append("Testing getPublicationIdsBy operation.... \n "
+ "For every publication, test Publication" + "\n");
if (pubIds != null) {
for (String id : pubIds) {
if (id != null) {
testPublication(id);
}
}
}
} catch (Exception e) {
System.out.println("Exception getting PublicationIds: " + e);
builder.append("Exception getting PublicationIds: " + e + "\n");
}
System.out.println("\nFinished testing publications.....\n");
}
public void testGetFileByProtocolId(String protocolId) {
// String protocolId = "24390915";
System.out.println("Testing getFileByProtocolId: " + protocolId);
builder.append("Testing getFileByProtocolId: " + protocolId + "\n");
try {
File file = gridClient.getFileByProtocolId(protocolId);
if (file != null) {
System.out.println("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri());
builder.append("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri() + "\n");
// TODO add CQL for keywords by file id
loadKeywordsForFile(file);
}
} catch (Exception e) {
System.out
.println("Exception getting ExperimentConfigsByCharacterizationId for protocolid="
+ protocolId + ": " + e);
builder.append("Exception getting ExperimentConfigsByCharacterizationId for protocolid="
+ protocolId + ": " + e + "\n");
}
}
public void testGetFilesByCompositionInfoId(String id, String className) {
// String id = "21376285";//"21376285";
// String className="NanoMaterialEntity";
System.out.println("Test getFilesByCompositionInfoId: id=" + id
+ ", className=" + className);
builder.append("Test getFilesByCompositionInfoId: id=" + id
+ ", className=" + className + "\n");
try {
File[] files = gridClient
.getFilesByCompositionInfoId(id, className);
if (files != null) {
for (File file : files) {
System.out.println("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri());
builder.append("File desc: " + file.getDescription()
+ "\tName: " + file.getName() + "\tUri: "
+ file.getUri() + "\n");
// TODO add CQL for keywords by file id
loadKeywordsForFile(file);
}
}
} catch (Exception e) {
System.out
.println("Exception getting FilesByCompositionInfoId for id="
+ id + ", className=" + className + ": " + e);
builder.append("Exception getting FilesByCompositionInfoId for id="
+ id + ", className=" + className + ": " + e + "\n");
}
}
/**
* load all InherentFunction for an associated ComposingElement
*/
private void loadInherentFunctionsForComposingElement(
ComposingElement composingElement) {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.particle.Function");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.ComposingElement");
association.setRoleName("composingElement");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(composingElement.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
try {
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.Function");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
composingElement
.setInherentFunctionCollection(new HashSet<Function>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
Function function = (Function) obj;
composingElement.getInherentFunctionCollection().add(function);
System.out.println("Function for ComposingElement: id="
+ function.getId() + "\tDesc="
+ function.getDescription());
builder.append("Function for ComposingElement: id="
+ function.getId() + "\tDesc="
+ function.getDescription() + "\n");
}
} catch (Exception e) {
System.out
.println("Exception getting Funtion for ComposingElement for id="
+ composingElement.getId() + ": " + e);
builder.append("Exception getting Funtion for ComposingElement for id="
+ composingElement.getId() + ": " + e + "\n");
}
}
public static void main(String[] args) {
System.out.println("Running the Grid Service Client");
try {
if (!(args.length < 2)) {
if (args[0].equals("-url")) {
CaNanoLabServiceClient client = new CaNanoLabServiceClient(
args[1]);
GridClientTest test = new GridClientTest(client);
System.out.println(new Date());
long start = System.currentTimeMillis();
test.builder.append("Start time: " + new Date() + "\n" );
test.testGetSampleIds();
//test.testCharacterizationAndCompositionBySampleIds();
//test.testGetPublicationIdsBy();
//test.testGetAllProtocolsByCQLQuery();
System.out.println(new Date());
long end = System.currentTimeMillis();
test.builder.append("End time: " + new Date()+ "\n" );
test.builder.append("Total time: " + (end - start)/1000 + " seconds");
// test.testSampleComposition("6160390");
// test.testGetPrimaryPointOfContactBySampleId("10354688");
// test.testGetCompositionBySampleIdByCQLQuery("9142300");
// test.testGetPrimaryPointOfContactBySampleId("10354688");
// test.testGetSampleIds();
// // test.testGetAllCharacterizationByCQLQuery(); //
// // these methods user can plug in any parameter
// test.testGetFindingsByCharacterizationId("3932251");
// test.testGetProtocolByCharacterizationId("3932251");
// test
// .testGetExperimentConfigsByCharacterizationId("3932251");
// test.testCharacterization("3932251");
// test.testGetFileByProtocolId("24390915");
// test.testGetFilesByCompositionInfoId("21376285",
// "NanomaterialEntity");
// test.testNanomaterialEntity("6160399");
// test.testFunction("10944705");
// test.testComposingElement("6062106");
// test.testFunctionalizingEntity("6225945");
// test.testChemicalAssociation("8847369");
// test.testSampleComposition("6160390");
// test.testActivationMethod("3833872");
// test.testProtocol("24390915");
test.writeOutput();
} else {
System.exit(1);
}
} else {
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void writeOutput(){
String fileName = "caNanoLabGridClientOutput.txt";
/*java.io.File outputFile = new java.io.File(".");
String dir = System.getProperty("java.io.tmpdir");
String path = dir + fileName;
System.out.println("path: " + path);
java.io.File file = new java.io.File(dir + fileName + java.io.File.separator + "test.txt");
if(!file.exists()){
file.mkdirs();
}*/
DataOutputStream oStream = null;
try {
oStream = new DataOutputStream(new FileOutputStream(fileName));
oStream.writeBytes(builder.toString());
oStream.flush();
System.out.println("Finished writing output file.");
} catch (FileNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
finally {
if (oStream != null) {
try {
oStream.close();
} catch (Exception e) {
}
}
}
}
} |
package com.sequenceiq.cloudbreak.metrics.processor;
import java.io.IOException;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
import org.xerial.snappy.Snappy;
import com.sequenceiq.cloudbreak.streaming.model.StreamProcessingException;
import com.sequenceiq.cloudbreak.streaming.processor.RecordWorker;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
public class MetricsRecordWorker extends RecordWorker<MetricsRecordProcessor, MetricsProcessorConfiguration, MetricsRecordRequest> {
private static final Integer STATUS_OK = 200;
private static final Integer LAST_REDIRECT_CODE = 399;
private final OkHttpClient client;
private final String remoteWriteUrlUnformatted;
public MetricsRecordWorker(String name, String serviceName, MetricsRecordProcessor recordProcessor, BlockingDeque<MetricsRecordRequest> processingQueue,
MetricsProcessorConfiguration configuration) {
super(name, serviceName, recordProcessor, processingQueue, configuration);
client = createClient();
remoteWriteUrlUnformatted = configuration.getRemoteWriteUrl().replace("$accountid", "%s");
}
@Override
public void processRecordInput(MetricsRecordRequest input) throws StreamProcessingException {
try {
byte[] compressed = Snappy.compress(input.getWriteRequest().toByteArray());
MediaType mediaType = MediaType.parse("application/x-protobuf");
RequestBody body = RequestBody.create(mediaType, compressed);
Request request = new Request.Builder()
.url(String.format(remoteWriteUrlUnformatted, input.getAccountId()))
.addHeader("Content-Encoding", "snappy")
.addHeader("User-Agent", "cb-prometheus-java-client")
.addHeader("X-Prometheus-Remote-Write-Version", "0.1.0")
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.code() < STATUS_OK || response.code() > LAST_REDIRECT_CODE) {
throw new StreamProcessingException(String.format("Response code is not valid. (status code: %s)", response.code()));
}
if (response.body() != null) {
response.body().close();
}
} catch (IOException e) {
throw new StreamProcessingException(e);
}
}
@Override
public void onInterrupt() {
}
private OkHttpClient createClient() {
Integer timeout = getConfiguration().getHttpTimeout();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(timeout, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);
okHttpClient.setWriteTimeout(timeout, TimeUnit.SECONDS);
return okHttpClient;
}
} |
package org.xcolab.client.members;
import org.xcolab.client.members.exceptions.MessageNotFoundException;
import org.xcolab.client.members.pojo.Member;
import org.xcolab.client.members.pojo.Message;
import org.xcolab.client.members.pojo.MessagingUserPreferences;
import org.xcolab.util.http.client.RestResource;
import org.xcolab.util.http.client.RestService;
import org.xcolab.util.http.exceptions.EntityNotFoundException;
import java.util.Date;
import java.util.List;
public final class MessagingClient {
private static final RestService memberService = new RestService("members-service");
private static final RestResource<Member> memberResource = new RestResource<>(memberService,
"members", Member.TYPES);
private static final RestResource<Message> messageResource = new RestResource<>(memberService,
"messages", Message.TYPES);
private MessagingClient() { }
public static Message getMessage(long messageId) throws MessageNotFoundException {
try {
return messageResource.get(messageId).execute();
} catch (EntityNotFoundException e) {
throw new MessageNotFoundException(messageId);
}
}
public static List<Message> getMessagesForUser(int firstMessage, int lastMessage, long userId, boolean isArchived) {
return messageResource.list()
.addRange(firstMessage, lastMessage)
.queryParam("recipientId", userId)
.queryParam("isArchived", isArchived)
.execute();
}
public static List<Message> getSentMessagesForUser(int firstMessage, int lastMessage, long userId) {
return messageResource.list()
.addRange(firstMessage, lastMessage)
.queryParam("senderId", userId).execute();
}
public static int getMessageCountForUser(long userId, boolean isArchived) {
return messageResource.count()
.queryParam("recipientId", userId)
.queryParam("isArchived", isArchived)
.execute();
}
public static int getMessageCountForMemberSinceDate(long memberId, Date sinceDate) {
return messageResource.count()
.queryParam("recipientId", memberId)
.queryParam("sinceDate", sinceDate.getTime())
.execute();
}
public static int getUnreadMessageCountForUser(long userId) {
return messageResource.count()
.queryParam("recipientId", userId)
.queryParam("isOpened", false)
.queryParam("isArchived", false)
.execute();
}
public static int getSentMessageCountForUser(long userId) {
return messageResource.count()
.queryParam("senderId", userId)
.execute();
}
public static Message createMessage(Message message) {
return messageResource.create(message).execute();
}
public static void createRecipient(long messageId, long recipientId) {
messageResource.service(messageId, "recipients", String.class)
.queryParam("recipientId", recipientId)
.post();
}
public static List<Member> getMessageRecipients(long messageId) {
return messageResource.getSubRestResource(messageId, "recipients",
Member.TYPES)
.list()
.execute();
}
public static void setArchived(long messageId, long memberId, boolean isArchived) {
messageResource.getSubServiceResource(messageId, "recipients")
.query(memberId, Void.class)
.queryParam("memberId", memberId)
.queryParam("isArchived", isArchived)
.put();
}
public static void setOpened(long messageId, long memberId, boolean isOpened) {
messageResource.getSubServiceResource(messageId, "recipients")
.query(memberId, Void.class)
.queryParam("memberId", memberId)
.queryParam("isOpened", isOpened)
.put();
}
public static MessagingUserPreferences getMessagingPreferencesForMember(long memberId) {
return memberResource.service(memberId, "messagingPreferences", MessagingUserPreferences.class)
.getUnchecked();
}
public static MessagingUserPreferences createMessagingPreferences(MessagingUserPreferences messagingUserPreferences) {
return memberResource
.getSubRestResource(messagingUserPreferences.getUserId(), "messagingPreferences", MessagingUserPreferences.TYPES)
.create(messagingUserPreferences)
.execute();
}
public static boolean updateMessagingPreferences(MessagingUserPreferences messagingUserPreferences) {
if (messagingUserPreferences.getMessagingPreferencesId() == null) {
createMessagingPreferences(messagingUserPreferences);
return true;
}
return memberResource
.getSubRestResource(messagingUserPreferences.getUserId(), "messagingPreferences", MessagingUserPreferences.TYPES)
.update(messagingUserPreferences, messagingUserPreferences.getMessagingPreferencesId())
.execute();
}
} |
package com.intellij.debugger.ui.impl;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.WeakMouseListener;
import com.intellij.debugger.ui.WeakMouseMotionListener;
import com.intellij.ui.ListenerUtil;
import com.intellij.util.Alarm;
import com.intellij.util.WeakListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TipManager {
private static int SHOW_DELAY = 1000;
public static interface TipFactory {
JComponent createToolTip (MouseEvent e);
}
private class MyMouseListener extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
tryTooltip(e);
}
private boolean isOverTip(MouseEvent e) {
if (myCurrentTooltip != null) {
final Window tipWindow = SwingUtilities.windowForComponent(myCurrentTooltip);
if (tipWindow == null) {
return false;
}
if(!tipWindow.isShowing()) {
hideTooltip();
return false;
}
final Point point = e.getComponent().getLocationOnScreen();
point.translate(e.getX(), e.getY());
return tipWindow.getBounds().contains(point);
}
return false;
}
public void mouseExited(MouseEvent e) {
myAlarm.cancelAllRequests();
if (isOverTip(e)) {
ListenerUtil.addMouseListener(myCurrentTooltip, new MouseAdapter() {
public void mouseExited(MouseEvent e) {
if (myCurrentTooltip != null) {
if(!isOverTip(e)) {
final Window tipWindow = SwingUtilities.windowForComponent(myCurrentTooltip);
if (tipWindow != null) {
tipWindow.removeMouseListener(this);
}
hideTooltip();
}
}
}
});
}
else {
hideTooltip();
}
}
}
private class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
tryTooltip(e);
}
}
private void tryTooltip(final MouseEvent e) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
showTooltip(e);
}
}, DebuggerSettings.getInstance().VALUE_LOOKUP_DELAY);
}
private void showTooltip(MouseEvent e) {
JComponent newTip = myTipFactory.createToolTip(e);
if(newTip == myCurrentTooltip) {
return;
}
hideTooltip();
if(newTip != null && myComponent.isShowing()) {
PopupFactory popupFactory = PopupFactory.getSharedInstance();
Point sLocation = myComponent.getLocationOnScreen();
Point location = newTip.getLocation();
location.x += sLocation.x;
location.y += sLocation.y;
Popup tipPopup = popupFactory.getPopup(myComponent, newTip, location.x, location.y);
tipPopup.show();
myCurrentTooltip = newTip;
}
}
public void hideTooltip() {
if (myCurrentTooltip != null) {
Window window = SwingUtilities.windowForComponent(myCurrentTooltip);
if(window != null && !(window instanceof JFrame)) {
window.hide();
}
myCurrentTooltip = null;
}
}
private JComponent myCurrentTooltip;
private final TipFactory myTipFactory;
private final JComponent myComponent;
private MouseListener myMouseListener = new MyMouseListener();
private MouseMotionListener myMouseMotionListener = new MyMouseMotionListener();
private final Alarm myAlarm = new Alarm();
public TipManager(JComponent component, TipFactory factory) {
new WeakMouseListener(component, myMouseListener);
new WeakMouseMotionListener(component, myMouseMotionListener);
myTipFactory = factory;
myComponent = component;
}
public void dispose() {
myMouseListener = null;
myMouseMotionListener = null;
}
} |
package org.jasig.portal.channels;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.jasig.portal.*;
import java.net.*;
/**
* Authorization channel. This channel works in conjunction with
* authorization.jsp
* @author Ken Weiner
* @version $Revision$
*
* This channel how works in conjunction with the "authentication.jsp"
* -ADN
*/
public class CAuthorization implements org.jasig.portal.IChannel
{
private static Vector params = null;
public void init (ChannelConfig chConfig) {};
public String getName () {return "Sign in";}
public boolean isMinimizable () {return false;}
public boolean isDetachable () {return false;}
public boolean isRemovable () {return false;}
public boolean isEditable () {return false;}
public boolean hasHelp () {return true;}
public int getDefaultDetachWidth () {return 0;}
public int getDefaultDetachHeight () {return 0;}
public Vector getParameters()
{
return params;
}
/**
* Called when channel should output its contents
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
public void render (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
try
{
doDisplaySignIn (req, res, out);
}
catch (Exception e)
{
Logger.log (Logger.ERROR, e);
}
}
/**
* Called when user clicks this channel's edit button
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
public void edit (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
// This channel is not editable
}
/**
* Called when user clicks this channel's help button
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
public void help (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
try
{
out.println ("<p>Please sign in with the following user name and password:");
out.println ("<p><p>");
out.println ("<table border=0 cellspacing=5 cellpadding=5>");
out.println (" <tr><th align=right>User name:</th><td><tt>demo</tt></td></tr>");
out.println (" <tr><th align=right>Password:</th><td><tt>demo</tt></td></tr>");
out.println ("</table>");
out.println ("<form action=\"layout.jsp\" method=post>");
out.println ("<input type=submit name=submit value=\"Try Again\">");
out.println ("</form>");
}
catch (Exception e)
{
Logger.log (Logger.ERROR, e);
}
}
/**
* Called by this channels render method. Outputs an html form prompting
* for user name and password.
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
protected void doDisplaySignIn (HttpServletRequest req, HttpServletResponse res, JspWriter out) throws IOException
{
HttpSession session = req.getSession (false);
String sUserName = (String) session.getAttribute ("userName");
if (sUserName != null && sUserName.equals ("guest"))
doDisplayFailedLogonMsg (req, res, out);
out.println ("<p>");
out.println ("<form action=\"authentication.jsp\" method=post>");
out.println ("<table align=center border=0 width=100%>");
out.println (" <tr>");
out.println (" <td>User Name: </td>");
out.println (" <td><input name=userName type=text size=15 value=\"\"></td>");
out.println (" </tr>");
out.println (" <tr>");
out.println (" <td>Password: </td>");
out.println (" <td><input name=password type=password size=15 value=\"\"></td>");
out.println (" </tr>");
out.println ("</table>");
out.println ("<center>");
out.println ("<p><input name=signIn type=submit value=\"Sign in\">");
out.println ("</center>");
out.println ("</form>");
}
/**
* Called when this channel is redisplayed after an incorrect username/password
* is submitted by the user
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
protected void doDisplayFailedLogonMsg (HttpServletRequest req, HttpServletResponse res, JspWriter out) throws IOException
{
out.print ("<font color=red>");
out.print ("Invalid user name or password!<br>");
out.print ("Please try again.");
out.print ("</font>");
}
} |
package org.openlmis.web.controller;
import lombok.NoArgsConstructor;
import org.openlmis.web.configurationReader.StaticReferenceDataReader;
import org.openlmis.web.response.OpenLmisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@NoArgsConstructor
@PropertySource({"classpath:/default.properties", "classpath:${environmentName}/app.properties"})
public class StaticReferenceDataController extends BaseController {
public static final String CURRENCY = "currency";
private StaticReferenceDataReader staticReferenceDataReader;
private Environment environment;
@Autowired
public StaticReferenceDataController(StaticReferenceDataReader staticReferenceDataReader, Environment environment) {
this.staticReferenceDataReader = staticReferenceDataReader;
this.environment = environment;
}
@RequestMapping(value = "/reference-data/currency", method = RequestMethod.GET)
public ResponseEntity<OpenLmisResponse> getCurrency() {
OpenLmisResponse response = new OpenLmisResponse(CURRENCY, staticReferenceDataReader.getCurrency());
return new ResponseEntity(response, HttpStatus.OK);
}
@RequestMapping(value = "/reference-data/lineitem/pagesize", method = RequestMethod.GET)
public ResponseEntity<OpenLmisResponse> getPageSize() {
OpenLmisResponse response = new OpenLmisResponse("pageSize", environment.getProperty("rnr.lineitem.page.size"));
return new ResponseEntity(response, HttpStatus.OK);
}
} |
package org.jasig.portal.tools.dbloader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.apache.oro.text.perl.Perl5Util;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.RDBMServices;
import org.jasig.portal.utils.XSLT;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
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 org.xml.sax.helpers.DefaultHandler;
/**
* <p>A tool to set up a uPortal database. This tool was created so that uPortal
* developers would only have to maintain a single set of xml documents to define
* the uPortal database schema and data. Previously it was necessary to maintain
* different scripts for each database we wanted to support.</p>
*
* <p>DbLoader reads the generic types that are specified in tables.xml and
* tries to map them to local types by querying the database metadata via methods
* implemented by the JDBC driver. Fallback mappings can be supplied in
* dbloader.xml for cases where the JDBC driver is not able to determine the
* appropriate mapping. Such cases will be reported to standard out.</p>
*
* <p>An xsl transformation is used to produce the DROP TABLE and CREATE TABLE
* SQL statements. These statements can be altered by modifying tables.xsl</p>
*
* <p>Generic data types (as defined in java.sql.Types) which may be specified
* in tables.xml include:
* <code>BIT, TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, REAL, DOUBLE,
* NUMERIC, DECIMAL, CHAR, VARCHAR, LONGVARCHAR, DATE, TIME, TIMESTAMP,
* BINARY, VARBINARY, LONGVARBINARY, NULL, OTHER, JAVA_OBJECT, DISTINCT,
* STRUCT, ARRAY, BLOB, CLOB, REF</code>
*
* <p><strong>WARNING: YOU MAY WANT TO MAKE A BACKUP OF YOUR DATABASE BEFORE RUNNING DbLoader</strong></p>
*
* <p>DbLoader will perform the following steps:
* <ol>
* <li>Read configurable properties from dbloader.xml</li>
* <li>Get database connection from RDBMServices
* (reads JDBC database settings from rdbm.properties).</li>
* <li>Read tables.xml and issue corresponding DROP TABLE and CREATE TABLE SQL statements.</li>
* <li>Read data.xml and issue corresponding INSERT/UPDATE/DELETE SQL statements.</li>
* </ol>
* </p>
*
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
* @see java.sql.Types
* @since uPortal 2.0
*/
public class DbLoader
{
private static URL propertiesURL;
private static URL tablesURL;
private static URL dataURL;
private static String tablesXslUri;
private static Connection con;
private static Statement stmt;
private static PreparedStatement pstmt;
private static RDBMServices rdbmService;
private static Document tablesDoc;
private static Document tablesDocGeneric;
private static boolean createScript;
private static boolean dropTables;
private static boolean createTables;
private static boolean populateTables;
private static PrintWriter scriptOut;
private static String admin_locale;
private static boolean localeAware;
private static Hashtable tableColumnTypes = new Hashtable(300);
public static void main(String[] args)
{
try
{
System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver"));
propertiesURL = DbLoader.class.getResource("/properties/db/dbloader.xml");
con = RDBMServices.getConnection ();
if (con != null)
{
long startTime = System.currentTimeMillis();
// Read in the properties
XMLReader parser = getXMLReader();
printInfo();
readProperties(parser);
// Read drop/create/populate table settings
dropTables = Boolean.valueOf(PropertiesHandler.properties.getDropTables()).booleanValue();
createTables = Boolean.valueOf(PropertiesHandler.properties.getCreateTables()).booleanValue();
populateTables = Boolean.valueOf(PropertiesHandler.properties.getPopulateTables()).booleanValue();
// Set up script
createScript = Boolean.valueOf(PropertiesHandler.properties.getCreateScript()).booleanValue();
if (createScript)
initScript();
// read command line arguements to override properties in dbloader.xml
boolean usetable = false;
boolean usedata = false;
boolean useLocale = false;
for (int i = 0; i < args.length; i++) {
//System.out.println("args["+i+"]: "+args[i]);
if (!args[i].startsWith("-")) {
if (usetable) {
PropertiesHandler.properties.setTablesUri(args[i]);
usetable=false;
} else if (usedata) {
PropertiesHandler.properties.setDataUri(args[i]);
usedata=false;
} else if (useLocale) {
admin_locale = args[i];
System.out.println("Using admin locale '" + admin_locale + "'");
useLocale = false;
}
} else if (args[i].equals("-t")) {
usetable = true;
} else if (args[i].equals("-d")) {
usedata= true;
} else if (args[i].equals("-c")) {
createScript = true;
} else if (args[i].equals("-nc")) {
createScript = false;
} else if (args[i].equals("-D")) {
dropTables = true;
} else if (args[i].equals("-nD")) {
dropTables = false;
} else if (args[i].equals("-C")) {
createTables = true;
} else if (args[i].equals("-nC")) {
createTables = false;
} else if (args[i].equals("-P")) {
populateTables = true;
} else if (args[i].equals("-nP")) {
populateTables = false;
} else if (args[i].equals("-l")) {
localeAware = true;
useLocale = true;
}
}
// okay, start processing
// get tablesURL and dataURL here
tablesURL = DbLoader.class.getResource(PropertiesHandler.properties.getTablesUri());
dataURL = DbLoader.class.getResource(PropertiesHandler.properties.getDataUri());
System.out.println("Getting tables from: "+tablesURL);
System.out.println("Getting data from: "+dataURL);
try
{
// Read tables.xml
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder domParser = dbf.newDocumentBuilder();
// Eventually, write and validate against a DTD
//domParser.setEntityResolver(new DTDResolver("tables.dtd"));
//tablesURL = DbLoader.class.getResource(PropertiesHandler.properties.getTablesUri());
tablesDoc = domParser.parse(new InputSource(tablesURL.openStream()));
} catch (ParserConfigurationException pce) {
System.out.println("Unable to instantiate DOM parser. Pease check your JAXP configuration.");
pce.printStackTrace();
}
catch(Exception e)
{
System.out.println("Could not open " + tablesURL);
e.printStackTrace();
return;
}
// Hold on to tables xml with generic types
tablesDocGeneric = (Document)tablesDoc.cloneNode(true);
// Replace all generic data types with local data types
replaceDataTypes(tablesDoc);
// tables.xml + tables.xsl --> DROP TABLE and CREATE TABLE sql statements
tablesXslUri = PropertiesHandler.properties.getTablesXslUri();
XSLT xslt = XSLT.getTransformer(new DbLoader());
xslt.setXML(tablesDoc);
xslt.setXSL(tablesXslUri);
xslt.setTarget(new TableHandler());
xslt.transform();
// data.xml --> INSERT sql statements
readData(parser);
System.out.println("Done!");
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time: " + ((endTime - startTime) / 1000f) + " seconds");
}
else
System.out.println("DbLoader couldn't obtain a database connection. See the portal log for details.");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
// call local exit method to clean up. This does not actually
// do a system.exit() allowing a stack trace to the console in
// the case of a run time error.
{
exit();
}
}
private static XMLReader getXMLReader() throws SAXException, ParserConfigurationException
{
SAXParserFactory spf=SAXParserFactory.newInstance();
return spf.newSAXParser().getXMLReader();
}
private static void printInfo () throws SQLException
{
DatabaseMetaData dbMetaData = con.getMetaData();
String dbName = dbMetaData.getDatabaseProductName();
String dbVersion = dbMetaData.getDatabaseProductVersion();
String driverName = dbMetaData.getDriverName();
String driverVersion = dbMetaData.getDriverVersion();
String driverClass = RDBMServices.getJdbcDriver();
String url = RDBMServices.getJdbcUrl();
String user = RDBMServices.getJdbcUser();
System.out.println("Starting DbLoader...");
System.out.println("Database name: '" + dbName + "'");
System.out.println("Database version: '" + dbVersion + "'");
System.out.println("Driver name: '" + driverName + "'");
System.out.println("Driver version: '" + driverVersion + "'");
System.out.println("Driver class: '" + driverClass + "'");
System.out.println("Connection URL: '" + url + "'");
System.out.println("User: '" + user + "'");
}
private static void readData (XMLReader parser) throws SAXException, IOException
{
InputSource dataInSrc = new InputSource(DbLoader.class.getResourceAsStream(PropertiesHandler.properties.getDataUri()));
DataHandler dataHandler = new DataHandler();
parser.setContentHandler(dataHandler);
parser.setErrorHandler(dataHandler);
parser.parse(dataInSrc);
}
private static void initScript() throws java.io.IOException
{
String scriptFileName = PropertiesHandler.properties.getScriptFileName();
File scriptFile = new File(scriptFileName);
if (scriptFile.exists())
scriptFile.delete();
scriptFile.createNewFile();
scriptOut = new PrintWriter(new BufferedWriter(new FileWriter(scriptFileName, true)));
}
private static void replaceDataTypes (Document tablesDoc)
{
Element tables = tablesDoc.getDocumentElement();
NodeList types = tables.getElementsByTagName("type");
for (int i = 0; i < types.getLength(); i++)
{
Node type = (Node)types.item(i);
NodeList typeChildren = type.getChildNodes();
for (int j = 0; j < typeChildren.getLength(); j++)
{
Node text = (Node)typeChildren.item(j);
String genericType = text.getNodeValue();
// Replace generic type with mapped local type
text.setNodeValue(getLocalDataTypeName(genericType));
}
}
}
private static int getJavaSqlDataTypeOfColumn(Document tablesDocGeneric, String tableName, String columnName)
{
int dataType = 0;
String hashKey = tableName + File.separator + columnName;
// Try to use cached version first
if (tableColumnTypes.get(hashKey) != null) {
dataType = ((Integer)tableColumnTypes.get(hashKey)).intValue();
} else {
// Find the right table element
Element table = getTableWithName(tablesDocGeneric, tableName);
// Find the columns element within
Element columns = getFirstChildWithName(table, "columns");
// Search for the first column who's name is columnName
for (Node ch = columns.getFirstChild(); ch != null; ch = ch.getNextSibling())
{
if (ch instanceof Element && ch.getNodeName().equals("column"))
{
Element name = getFirstChildWithName((Element)ch, "name");
if (getNodeValue(name).equals(columnName))
{
// Get the corresponding type and return it's type code
Element value = getFirstChildWithName((Element)ch, "type");
dataType = getJavaSqlType(getNodeValue(value));
}
}
}
// Store value in hashtable for next call to this method.
// This prevents repeating xml parsing which takes a very long time
tableColumnTypes.put(hashKey, new Integer(dataType));
}
return dataType;
}
private static Element getFirstChildWithName (Element parent, String name)
{
Element child = null;
for (Node ch = parent.getFirstChild(); ch != null; ch = ch.getNextSibling())
{
if (ch instanceof Element && ch.getNodeName().equals(name))
{
child = (Element)ch;
break;
}
}
return child;
}
private static Element getTableWithName (Document tablesDoc, String tableName)
{
Element tableElement = null;
NodeList tables = tablesDoc.getElementsByTagName("table");
for (int i = 0; i < tables.getLength(); i++)
{
Node table = (Node)tables.item(i);
for (Node tableChild = table.getFirstChild(); tableChild != null; tableChild = tableChild.getNextSibling())
{
if (tableChild instanceof Element && tableChild.getNodeName() != null && tableChild.getNodeName().equals("name"))
{
if (tableName.equals(getNodeValue(tableChild)))
{
tableElement = (Element)table;
break;
}
}
}
}
return tableElement;
}
private static String getNodeValue (Node node)
{
String nodeVal = null;
for (Node ch = node.getFirstChild(); ch != null; ch = ch.getNextSibling())
{
if (ch instanceof Text)
nodeVal = ch.getNodeValue();
}
return nodeVal;
}
private static String getLocalDataTypeName (String genericDataTypeName)
{
String localDataTypeName = null;
try
{
DatabaseMetaData dbmd = con.getMetaData();
String dbName = dbmd.getDatabaseProductName();
String dbVersion = dbmd.getDatabaseProductVersion();
String driverName = dbmd.getDriverName();
String driverVersion = dbmd.getDriverVersion();
// Check for a mapping in DbLoader.xml
localDataTypeName = PropertiesHandler.properties.getMappedDataTypeName(dbName, dbVersion, driverName, driverVersion, genericDataTypeName);
if (localDataTypeName != null)
return localDataTypeName;
// Find the type code for this generic type name
int dataTypeCode = getJavaSqlType(genericDataTypeName);
// Find the first local type name matching the type code
ResultSet rs = dbmd.getTypeInfo();
try {
while (rs.next())
{
int localDataTypeCode = rs.getInt("DATA_TYPE");
if (dataTypeCode == localDataTypeCode)
{
try { localDataTypeName = rs.getString("TYPE_NAME"); } catch (SQLException sqle) { }
break;
}
}
} finally {
rs.close();
}
if (localDataTypeName != null)
return localDataTypeName;
// No matching type found, report an error
System.out.println("Your database driver, '"+ driverName + "', version '" + driverVersion + "', was unable to find a local type name that matches the generic type name, '" + genericDataTypeName + "'.");
System.out.println("Please add a mapped type for database '" + dbName + "', version '" + dbVersion + "' inside '" + propertiesURL + "' and run this program again.");
System.out.println("Exiting...");
exit();
}
catch (Exception e)
{
e.printStackTrace();
exit();
}
return null;
}
private static int getJavaSqlType (String genericDataTypeName)
{
// Find the type code for this generic type name
int dataTypeCode = 0;
if (genericDataTypeName.equalsIgnoreCase("BIT"))
dataTypeCode = Types.BIT;
else if (genericDataTypeName.equalsIgnoreCase("TINYINT"))
dataTypeCode = Types.TINYINT;
else if (genericDataTypeName.equalsIgnoreCase("SMALLINT"))
dataTypeCode = Types.SMALLINT;
else if (genericDataTypeName.equalsIgnoreCase("INTEGER"))
dataTypeCode = Types.INTEGER;
else if (genericDataTypeName.equalsIgnoreCase("BIGINT"))
dataTypeCode = Types.BIGINT;
else if (genericDataTypeName.equalsIgnoreCase("FLOAT"))
dataTypeCode = Types.FLOAT;
else if (genericDataTypeName.equalsIgnoreCase("REAL"))
dataTypeCode = Types.REAL;
else if (genericDataTypeName.equalsIgnoreCase("DOUBLE"))
dataTypeCode = Types.DOUBLE;
else if (genericDataTypeName.equalsIgnoreCase("NUMERIC"))
dataTypeCode = Types.NUMERIC;
else if (genericDataTypeName.equalsIgnoreCase("DECIMAL"))
dataTypeCode = Types.DECIMAL;
else if (genericDataTypeName.equalsIgnoreCase("CHAR"))
dataTypeCode = Types.CHAR;
else if (genericDataTypeName.equalsIgnoreCase("VARCHAR"))
dataTypeCode = Types.VARCHAR;
else if (genericDataTypeName.equalsIgnoreCase("LONGVARCHAR"))
dataTypeCode = Types.LONGVARCHAR;
else if (genericDataTypeName.equalsIgnoreCase("DATE"))
dataTypeCode = Types.DATE;
else if (genericDataTypeName.equalsIgnoreCase("TIME"))
dataTypeCode = Types.TIME;
else if (genericDataTypeName.equalsIgnoreCase("TIMESTAMP"))
dataTypeCode = Types.TIMESTAMP;
else if (genericDataTypeName.equalsIgnoreCase("BINARY"))
dataTypeCode = Types.BINARY;
else if (genericDataTypeName.equalsIgnoreCase("VARBINARY"))
dataTypeCode = Types.VARBINARY;
else if (genericDataTypeName.equalsIgnoreCase("LONGVARBINARY"))
dataTypeCode = Types.LONGVARBINARY;
else if (genericDataTypeName.equalsIgnoreCase("NULL"))
dataTypeCode = Types.NULL;
else if (genericDataTypeName.equalsIgnoreCase("OTHER"))
dataTypeCode = Types.OTHER; // 1111
else if (genericDataTypeName.equalsIgnoreCase("JAVA_OBJECT"))
dataTypeCode = Types.JAVA_OBJECT; // 2000
else if (genericDataTypeName.equalsIgnoreCase("DISTINCT"))
dataTypeCode = Types.DISTINCT; // 2001
else if (genericDataTypeName.equalsIgnoreCase("STRUCT"))
dataTypeCode = Types.STRUCT; // 2002
else if (genericDataTypeName.equalsIgnoreCase("ARRAY"))
dataTypeCode = Types.ARRAY; // 2003
else if (genericDataTypeName.equalsIgnoreCase("BLOB"))
dataTypeCode = Types.BLOB; // 2004
else if (genericDataTypeName.equalsIgnoreCase("CLOB"))
dataTypeCode = Types.CLOB; // 2005
else if (genericDataTypeName.equalsIgnoreCase("REF"))
dataTypeCode = Types.REF; // 2006
return dataTypeCode;
}
private static void dropTable (String dropTableStatement)
{
System.out.print("...");
if (createScript)
scriptOut.println(dropTableStatement + PropertiesHandler.properties.getStatementTerminator());
try
{
stmt = con.createStatement();
try { stmt.executeUpdate(dropTableStatement); } catch (SQLException sqle) {/*Table didn't exist*/}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try { stmt.close(); } catch (Exception e) { }
}
}
private static void createTable (String createTableStatement)
{
System.out.print("...");
if (createScript)
scriptOut.println(createTableStatement + PropertiesHandler.properties.getStatementTerminator());
try
{
stmt = con.createStatement();
stmt.executeUpdate(createTableStatement);
}
catch (Exception e)
{
System.out.println(createTableStatement);
e.printStackTrace();
}
finally
{
try { stmt.close(); } catch (Exception e) { }
}
}
private static void readProperties (XMLReader parser) throws SAXException, IOException
{
PropertiesHandler propertiesHandler = new PropertiesHandler();
parser.setContentHandler(propertiesHandler);
parser.setErrorHandler(propertiesHandler);
parser.parse(new InputSource(propertiesURL.openStream()));
}
static class PropertiesHandler extends DefaultHandler
{
private static StringBuffer charBuff = null;
static Properties properties;
static DbTypeMapping dbTypeMapping;
static Type type;
public void startDocument ()
{
System.out.print("Parsing " + propertiesURL + "...");
}
public void endDocument ()
{
System.out.println("");
}
public void startElement (String namespaceURI, String localName, String qName, Attributes atts)
{
charBuff = new StringBuffer();
if (qName.equals("properties"))
properties = new Properties();
else if (qName.equals("db-type-mapping"))
dbTypeMapping = new DbTypeMapping();
else if (qName.equals("type"))
type = new Type();
}
public void endElement (String namespaceURI, String localName, String qName)
{
if (qName.equals("drop-tables")) // drop tables ("true" or "false")
properties.setDropTables(charBuff.toString());
else if (qName.equals("create-tables")) // create tables ("true" or "false")
properties.setCreateTables(charBuff.toString());
else if (qName.equals("populate-tables")) // populate tables ("true" or "false")
properties.setPopulateTables(charBuff.toString());
else if (qName.equals("tables-uri")) // tables URI
properties.setTablesUri(charBuff.toString());
else if (qName.equals("tables-xsl-uri")) // tables xsl URI
properties.setTablesXslUri(charBuff.toString());
else if (qName.equals("data-uri")) // data xml URI
properties.setDataUri(charBuff.toString());
else if (qName.equals("create-script")) // create script ("true" or "false")
properties.setCreateScript(charBuff.toString());
else if (qName.equals("script-file-name")) // script file name
properties.setScriptFileName(charBuff.toString());
else if (qName.equals("statement-terminator")) // statement terminator
properties.setStatementTerminator(charBuff.toString());
else if (qName.equals("db-type-mapping"))
properties.addDbTypeMapping(dbTypeMapping);
else if (qName.equals("db-name")) // database name
dbTypeMapping.setDbName(charBuff.toString());
else if (qName.equals("db-version")) // database version
dbTypeMapping.setDbVersion(charBuff.toString());
else if (qName.equals("driver-name")) // driver name
dbTypeMapping.setDriverName(charBuff.toString());
else if (qName.equals("driver-version")) // driver version
dbTypeMapping.setDriverVersion(charBuff.toString());
else if (qName.equals("type"))
dbTypeMapping.addType(type);
else if (qName.equals("generic")) // generic type
type.setGeneric(charBuff.toString());
else if (qName.equals("local")) // local type
type.setLocal(charBuff.toString());
}
public void characters (char ch[], int start, int length)
{
charBuff.append(ch, start, length);
}
class Properties
{
private String dropTables;
private String createTables;
private String populateTables;
private String tablesUri;
private String tablesXslUri;
private String dataUri;
private String dataXslUri;
private String createScript;
private String scriptFileName;
private String statementTerminator;
private ArrayList dbTypeMappings = new ArrayList();
public String getDropTables() { return dropTables; }
public String getCreateTables() { return createTables; }
public String getPopulateTables() { return populateTables; }
public String getTablesUri() { return tablesUri; }
public String getTablesXslUri() { return tablesXslUri; }
public String getDataUri() {
String ret = dataUri;
if (localeAware == true && admin_locale != null) {
// Switch to replaceAll when we can rely on JDK 1.4
// ret = ret.replaceAll("\\.xml", "_" + admin_locale + ".xml");
Perl5Util perl5Util = new Perl5Util();
ret = perl5Util.substitute("s/\\.xml/_" + admin_locale + ".xml" + "/g", ret);
System.out.println("Getting locale-aware data from: " + ret);
}
return ret;
}
public String getDataXslUri() { return dataXslUri; }
public String getCreateScript() { return createScript; }
public String getScriptFileName() { return scriptFileName; }
public String getStatementTerminator() { return statementTerminator; }
public ArrayList getDbTypeMappings() { return dbTypeMappings; }
public void setDropTables(String dropTables) { this.dropTables = dropTables; }
public void setCreateTables(String createTables) { this.createTables = createTables; }
public void setPopulateTables(String populateTables) { this.populateTables = populateTables; }
public void setTablesUri(String tablesUri) { this.tablesUri = tablesUri; }
public void setTablesXslUri(String tablesXslUri) { this.tablesXslUri = tablesXslUri; }
public void setDataUri(String dataUri) { this.dataUri = dataUri; }
public void setDataXslUri(String dataXslUri) { this.dataXslUri = dataXslUri; }
public void setCreateScript(String createScript) { this.createScript = createScript; }
public void setScriptFileName(String scriptFileName) { this.scriptFileName = scriptFileName; }
public void setStatementTerminator(String statementTerminator) { this.statementTerminator = statementTerminator; }
public void addDbTypeMapping(DbTypeMapping dbTypeMapping) { dbTypeMappings.add(dbTypeMapping); }
public String getMappedDataTypeName(String dbName, String dbVersion, String driverName, String driverVersion, String genericDataTypeName)
{
String mappedDataTypeName = null;
Iterator iterator = dbTypeMappings.iterator();
while (iterator.hasNext())
{
DbTypeMapping dbTypeMapping = (DbTypeMapping)iterator.next();
String dbNameProp = dbTypeMapping.getDbName();
String dbVersionProp = dbTypeMapping.getDbVersion();
String driverNameProp = dbTypeMapping.getDriverName();
String driverVersionProp = dbTypeMapping.getDriverVersion();
if (dbNameProp.equalsIgnoreCase(dbName) && dbVersionProp.equalsIgnoreCase(dbVersion) &&
driverNameProp.equalsIgnoreCase(driverName) && driverVersionProp.equalsIgnoreCase(driverVersion))
{
// Found a matching database/driver combination
mappedDataTypeName = dbTypeMapping.getMappedDataTypeName(genericDataTypeName);
}
}
return mappedDataTypeName;
}
}
class DbTypeMapping
{
String dbName;
String dbVersion;
String driverName;
String driverVersion;
ArrayList types = new ArrayList();
public String getDbName() { return dbName; }
public String getDbVersion() { return dbVersion; }
public String getDriverName() { return driverName; }
public String getDriverVersion() { return driverVersion; }
public ArrayList getTypes() { return types; }
public void setDbName(String dbName) { this.dbName = dbName; }
public void setDbVersion(String dbVersion) { this.dbVersion = dbVersion; }
public void setDriverName(String driverName) { this.driverName = driverName; }
public void setDriverVersion(String driverVersion) { this.driverVersion = driverVersion; }
public void addType(Type type) { types.add(type); }
public String getMappedDataTypeName(String genericDataTypeName)
{
String mappedDataTypeName = null;
Iterator iterator = types.iterator();
while (iterator.hasNext())
{
Type type = (Type)iterator.next();
if (type.getGeneric().equalsIgnoreCase(genericDataTypeName))
mappedDataTypeName = type.getLocal();
}
return mappedDataTypeName;
}
}
class Type
{
String genericType; // "generic" is a Java reserved word
String local;
public String getGeneric() { return genericType; }
public String getLocal() { return local; }
public void setGeneric(String genericType) { this.genericType = genericType; }
public void setLocal(String local) { this.local = local; }
}
}
static class TableHandler implements ContentHandler
{
private static final int UNSET = -1;
private static final int DROP = 0;
private static final int CREATE = 1;
private static int mode = UNSET;
private static StringBuffer stmtBuffer;
public void startDocument ()
{
}
public void endDocument ()
{
System.out.println();
}
public void startElement (String namespaceURI, String localName, String qName, Attributes atts)
{
if (qName.equals("statement"))
{
stmtBuffer = new StringBuffer(1024);
String statementType = atts.getValue("type");
if (mode == UNSET || mode == CREATE && statementType != null && statementType.equals("drop"))
{
mode = DROP;
System.out.print("Dropping tables...");
if (!dropTables)
System.out.print("disabled.");
}
else if (mode == UNSET || mode == DROP && statementType != null && statementType.equals("create"))
{
mode = CREATE;
System.out.print("\nCreating tables...");
if (!createTables)
System.out.print("disabled.");
}
}
}
public void endElement (String namespaceURI, String localName, String qName)
{
if (qName.equals("statement"))
{
String statement = stmtBuffer.toString();
switch (mode)
{
case DROP:
if (dropTables)
dropTable(statement);
break;
case CREATE:
if (createTables)
createTable(statement);
break;
default:
break;
}
}
}
public void characters (char ch[], int start, int length)
{
stmtBuffer.append(ch, start, length);
}
public void setDocumentLocator (Locator locator)
{
}
public void processingInstruction (String target, String data)
{
}
public void ignorableWhitespace (char[] ch, int start, int length)
{
}
public void startPrefixMapping (String prefix, String uri) throws SAXException {};
public void endPrefixMapping (String prefix) throws SAXException {};
public void skippedEntity(String name) throws SAXException {};
}
static class DataHandler extends DefaultHandler
{
private static StringBuffer charBuff = null;
private static boolean insideData = false;
private static boolean insideTable = false;
private static boolean insideName = false;
private static boolean insideRow = false;
private static boolean insideColumn = false;
private static boolean insideValue = false;
private static boolean supportsPreparedStatements = false;
static Table table;
static Row row;
static Column column;
static String action; //determines sql function for a table row
static String type; //determines type of column
public void startDocument ()
{
System.out.print("Populating tables...");
if (!populateTables)
System.out.print("disabled.");
supportsPreparedStatements = supportsPreparedStatements();
}
public void endDocument ()
{
System.out.println("");
}
public void startElement (String namespaceURI, String localName, String qName, Attributes atts)
{
charBuff = new StringBuffer();
if (qName.equals("data"))
insideData = true;
else if (qName.equals("table"))
{
insideTable = true;
table = new Table();
action = atts.getValue("action");
}
else if (qName.equals("name"))
insideName = true;
else if (qName.equals("row"))
{
insideRow = true;
row = new Row();
}
else if (qName.equals("column"))
{
insideColumn = true;
column = new Column();
type = atts.getValue("type");
}
else if (qName.equals("value"))
insideValue = true;
}
public void endElement (String namespaceURI, String localName, String qName)
{
if (qName.equals("data"))
insideData = false;
else if (qName.equals("table"))
insideTable = false;
else if (qName.equals("name"))
{
insideName = false;
if (!insideColumn) // table name
table.setName(charBuff.toString());
else // column name
column.setName(charBuff.toString());
}
else if (qName.equals("row"))
{
insideRow = false;
if (action != null)
{
if ( action.equals("delete") )
executeSQL(table, row, "delete");
else if ( action.equals("modify") )
executeSQL(table, row, "modify");
else if ( action.equals("add") )
executeSQL(table, row, "insert");
}
else if (populateTables)
executeSQL(table, row, "insert");
}
else if (qName.equals("column"))
{
insideColumn = false;
if (type != null) column.setType(type);
row.addColumn(column);
}
else if (qName.equals("value"))
{
insideValue = false;
if (insideColumn) // column value
column.setValue(charBuff.toString());
}
}
public void characters (char ch[], int start, int length)
{
charBuff.append(ch, start, length);
}
private String prepareInsertStatement (Row row, boolean preparedStatement)
{
StringBuffer sb = new StringBuffer("INSERT INTO ");
sb.append(table.getName()).append(" (");
ArrayList columns = row.getColumns();
Iterator iterator = columns.iterator();
while (iterator.hasNext())
{
Column column = (Column)iterator.next();
sb.append(column.getName()).append(", ");
}
// Delete comma and space after last column name (kind of sloppy, but it works)
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.append(") VALUES (");
iterator = columns.iterator();
while (iterator.hasNext())
{
Column column = (Column)iterator.next();
if (preparedStatement)
sb.append("?");
else
{
String value = column.getValue();
if (value != null)
{
if (value.equals("SYSDATE"))
sb.append(value);
else if (value.equals("NULL"))
sb.append(value);
else if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER)
// this column is an integer, so don't put quotes (Sybase cares about this)
sb.append(value);
else
{
sb.append("'");
sb.append(sqlEscape(value.trim()));
sb.append("'");
}
}
else
sb.append("''");
}
sb.append(", ");
}
// Delete comma and space after last value (kind of sloppy, but it works)
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.append(")");
return sb.toString();
}
private String prepareDeleteStatement (Row row, boolean preparedStatement)
{
StringBuffer sb = new StringBuffer("DELETE FROM ");
sb.append(table.getName()).append(" WHERE ");
ArrayList columns = row.getColumns();
Iterator iterator = columns.iterator();
Column column;
while (iterator.hasNext())
{
column = (Column) iterator.next();
if (preparedStatement)
sb.append(column.getName() + " = ? and ");
else if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER)
sb.append(column.getName() + " = " + sqlEscape(column.getValue().trim()) + " and ");
else
sb.append(column.getName() + " = " + "'" + sqlEscape(column.getValue().trim()) + "' and ");
}
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
if (!preparedStatement)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
private String prepareUpdateStatement (Row row, boolean preparedStatement)
{
StringBuffer sb = new StringBuffer("UPDATE ");
sb.append(table.getName()).append(" SET ");
ArrayList columns = row.getColumns();
Iterator iterator = columns.iterator();
Hashtable setPairs = new Hashtable();
Hashtable wherePairs = new Hashtable();
String type;
Column column;
while (iterator.hasNext())
{
column = (Column) iterator.next();
type = column.getType();
if (type != null && type.equals("select"))
{
if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER)
wherePairs.put(column.getName(), column.getValue().trim());
else
wherePairs.put(column.getName(), "'" + column.getValue().trim() + "'");
}
else
{
if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER)
setPairs.put(column.getName(), column.getValue().trim());
else
setPairs.put(column.getName(), "'" + column.getValue().trim() + "'");
}
}
String nm;
String val;
Enumeration sKeys = setPairs.keys();
while (sKeys.hasMoreElements())
{
nm = (String) sKeys.nextElement();
val = (String) setPairs.get(nm);
sb.append( nm + " = " + sqlEscape(val) + ", ");
}
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.append(" WHERE ");
Enumeration wKeys = wherePairs.keys();
while (wKeys.hasMoreElements())
{
nm = (String) wKeys.nextElement();
val = (String) wherePairs.get(nm);
sb.append( nm + "=" + sqlEscape(val) + " and ");
}
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Make a string SQL safe
* @param string
* @return SQL safe string
*/
public static final String sqlEscape (String sql) {
if (sql == null) {
return "";
}
else {
int primePos = sql.indexOf("'");
if (primePos == -1) {
return sql;
}
else {
StringBuffer sb = new StringBuffer(sql.length() + 4);
int startPos = 0;
do {
sb.append(sql.substring(startPos, primePos + 1));
sb.append("'");
startPos = primePos + 1;
primePos = sql.indexOf("'", startPos);
} while (primePos != -1);
sb.append(sql.substring(startPos));
return sb.toString();
}
}
}
private void executeSQL (Table table, Row row, String action)
{
System.out.print("...");
if (createScript)
{
if (action.equals("delete"))
scriptOut.println(prepareDeleteStatement(row, false) + PropertiesHandler.properties.getStatementTerminator());
else if (action.equals("modify"))
scriptOut.println(prepareUpdateStatement(row, false) + PropertiesHandler.properties.getStatementTerminator());
else if (action.equals("insert"))
scriptOut.println(prepareInsertStatement(row, false) + PropertiesHandler.properties.getStatementTerminator());
}
if (supportsPreparedStatements)
{
String preparedStatement = "";
try
{
if (action.equals("delete"))
preparedStatement = prepareDeleteStatement(row, true);
else if (action.equals("modify"))
preparedStatement = prepareUpdateStatement(row, true);
else if (action.equals("insert"))
preparedStatement = prepareInsertStatement(row, true);
//System.out.println(preparedStatement);
pstmt = con.prepareStatement(preparedStatement);
pstmt.clearParameters ();
// Loop through parameters and set them, checking for any that excede 4k
ArrayList columns = row.getColumns();
Iterator iterator = columns.iterator();
for (int i = 1; iterator.hasNext(); i++)
{
Column column = (Column)iterator.next();
String value = column.getValue();
// Get a java sql data type for column name
int javaSqlDataType = getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName());
if (value==null || (value!=null && value.equalsIgnoreCase("NULL")))
pstmt.setNull(i, javaSqlDataType);
else if (javaSqlDataType == Types.TIMESTAMP)
{
if (value.equals("SYSDATE"))
pstmt.setTimestamp(i, new java.sql.Timestamp(System.currentTimeMillis()));
else
pstmt.setTimestamp(i, java.sql.Timestamp.valueOf(value));
}
else
{
value = value.trim(); // portal can't read xml properly without this, don't know why yet
int valueLength = value.length();
if (valueLength <= 4000)
{
try
{
// Needed for Sybase and maybe others
pstmt.setObject(i, value, javaSqlDataType);
}
catch (Exception e)
{
// Needed for Oracle and maybe others
pstmt.setObject(i, value);
}
}
else
{
try
{
try
{
// Needed for Sybase and maybe others
pstmt.setObject(i, value, javaSqlDataType);
}
catch (Exception e)
{
// Needed for Oracle and maybe others
pstmt.setObject(i, value);
}
}
catch (SQLException sqle)
{
// For Oracle and maybe others
pstmt.setCharacterStream(i, new StringReader(value), valueLength);
}
}
}
}
pstmt.executeUpdate();
}
catch (SQLException sqle)
{
System.err.println();
System.err.println(preparedStatement);
sqle.printStackTrace();
}
catch (Exception e)
{
System.err.println();
e.printStackTrace();
}
finally
{
try { pstmt.close(); } catch (Exception e) { }
}
}
else
{
// If prepared statements aren't supported, try a normal sql statement
String statement = "";
if (action.equals("delete"))
statement = prepareDeleteStatement(row, false);
else if (action.equals("modify"))
statement = prepareUpdateStatement(row, false);
else if (action.equals("insert"))
statement = prepareInsertStatement(row, false);
//System.out.println(statement);
try
{
stmt = con.createStatement();
stmt.executeUpdate(statement);
}
catch (Exception e)
{
System.err.println();
System.err.println(statement);
e.printStackTrace();
}
finally
{
try { stmt.close(); } catch (Exception e) { }
}
}
}
private static boolean supportsPreparedStatements()
{
boolean supportsPreparedStatements = true;
try
{
// Issue a prepared statement to see if database/driver accepts them.
// The assumption is that if a SQLException is thrown, it doesn't support them.
// I don't know of any other way to check if the database/driver accepts
// prepared statements. If you do, please change this method!
Statement stmt;
stmt = con.createStatement();
try {
stmt.executeUpdate("CREATE TABLE PREP_TEST (A VARCHAR(1))");
} catch (Exception e){/* Assume it already exists */
} finally {
try {stmt.close();} catch (Exception e) { }
}
pstmt = con.prepareStatement("SELECT A FROM PREP_TEST WHERE A=?");
pstmt.clearParameters ();
pstmt.setString(1, "D");
ResultSet rs = pstmt.executeQuery();
rs.close();
}
catch (SQLException sqle)
{
supportsPreparedStatements = false;
sqle.printStackTrace();
}
finally
{
try {
stmt = con.createStatement();
stmt.executeUpdate("DROP TABLE PREP_TEST");
} catch (Exception e){/* Assume it already exists */
} finally {
try {stmt.close();} catch (Exception e) { }
}
try { pstmt.close(); } catch (Exception e) { }
}
return supportsPreparedStatements;
}
class Table
{
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
class Row
{
ArrayList columns = new ArrayList();
public ArrayList getColumns() { return columns; }
public void addColumn(Column column) { columns.add(column); }
}
class Column
{
private String name;
private String value;
private String type;
public String getName() { return name; }
public String getValue() { return value; }
public String getType() { return type; }
public void setName(String name) { this.name = name; }
public void setValue(String value) { this.value = value; }
public void setType(String type) { this.type = type; }
}
}
private static void exit()
{
RDBMServices.releaseConnection(con);
if (scriptOut != null)
scriptOut.close();
}
} |
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.RectangleInsets;
/**
* A record that contains information for one "band" of date labels in
* a {@link PeriodAxis}.
*/
public class PeriodAxisLabelInfo implements Cloneable, Serializable {
// TODO: this class is mostly immutable, so implementing Cloneable isn't
// really necessary. But there is still a hole in that you can get the
// dateFormat and modify it. We could return a copy, but that would slow
// things down. Needs resolving.
/** For serialization. */
private static final long serialVersionUID = 5710451740920277357L;
/** The default insets. */
public static final RectangleInsets DEFAULT_INSETS
= new RectangleInsets(2, 2, 2, 2);
/** The default font. */
public static final Font DEFAULT_FONT
= new Font("SansSerif", Font.PLAIN, 10);
/** The default label paint. */
public static final Paint DEFAULT_LABEL_PAINT = Color.black;
/** The default divider stroke. */
public static final Stroke DEFAULT_DIVIDER_STROKE = new BasicStroke(0.5f);
/** The default divider paint. */
public static final Paint DEFAULT_DIVIDER_PAINT = Color.gray;
/** The subclass of {@link RegularTimePeriod} to use for this band. */
private Class periodClass;
/** Controls the gaps around the band. */
private RectangleInsets padding;
/** The date formatter. */
private DateFormat dateFormat;
/** The label font. */
private Font labelFont;
/** The label paint. */
private transient Paint labelPaint;
/** A flag that controls whether or not dividers are visible. */
private boolean drawDividers;
/** The stroke used to draw the dividers. */
private transient Stroke dividerStroke;
/** The paint used to draw the dividers. */
private transient Paint dividerPaint;
/**
* Creates a new instance.
*
* @param periodClass the subclass of {@link RegularTimePeriod} to use
* (<code>null</code> not permitted).
* @param dateFormat the date format (<code>null</code> not permitted).
*/
public PeriodAxisLabelInfo(Class periodClass, DateFormat dateFormat) {
this(periodClass, dateFormat, DEFAULT_INSETS, DEFAULT_FONT,
DEFAULT_LABEL_PAINT, true, DEFAULT_DIVIDER_STROKE,
DEFAULT_DIVIDER_PAINT);
}
/**
* Creates a new instance.
*
* @param periodClass the subclass of {@link RegularTimePeriod} to use
* (<code>null</code> not permitted).
* @param dateFormat the date format (<code>null</code> not permitted).
* @param padding controls the space around the band (<code>null</code>
* not permitted).
* @param labelFont the label font (<code>null</code> not permitted).
* @param labelPaint the label paint (<code>null</code> not permitted).
* @param drawDividers a flag that controls whether dividers are drawn.
* @param dividerStroke the stroke used to draw the dividers
* (<code>null</code> not permitted).
* @param dividerPaint the paint used to draw the dividers
* (<code>null</code> not permitted).
*/
public PeriodAxisLabelInfo(Class periodClass, DateFormat dateFormat,
RectangleInsets padding, Font labelFont, Paint labelPaint,
boolean drawDividers, Stroke dividerStroke, Paint dividerPaint) {
ParamChecks.nullNotPermitted(periodClass, "periodClass");
ParamChecks.nullNotPermitted(dateFormat, "dateFormat");
ParamChecks.nullNotPermitted(padding, "padding");
ParamChecks.nullNotPermitted(labelFont, "labelFont");
ParamChecks.nullNotPermitted(labelPaint, "labelPaint");
ParamChecks.nullNotPermitted(dividerStroke, "dividerStroke");
ParamChecks.nullNotPermitted(dividerPaint, "dividerPaint");
this.periodClass = periodClass;
this.dateFormat = dateFormat;
this.padding = padding;
this.labelFont = labelFont;
this.labelPaint = labelPaint;
this.drawDividers = drawDividers;
this.dividerStroke = dividerStroke;
this.dividerPaint = dividerPaint;
}
/**
* Returns the subclass of {@link RegularTimePeriod} that should be used
* to generate the date labels.
*
* @return The class.
*/
public Class getPeriodClass() {
return this.periodClass;
}
/**
* Returns the date formatter.
*
* @return The date formatter (never <code>null</code>).
*/
public DateFormat getDateFormat() {
return this.dateFormat;
}
/**
* Returns the padding for the band.
*
* @return The padding.
*/
public RectangleInsets getPadding() {
return this.padding;
}
/**
* Returns the label font.
*
* @return The label font (never <code>null</code>).
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Returns the label paint.
*
* @return The label paint.
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Returns a flag that controls whether or not dividers are drawn.
*
* @return A flag.
*/
public boolean getDrawDividers() {
return this.drawDividers;
}
/**
* Returns the stroke used to draw the dividers.
*
* @return The stroke.
*/
public Stroke getDividerStroke() {
return this.dividerStroke;
}
/**
* Returns the paint used to draw the dividers.
*
* @return The paint.
*/
public Paint getDividerPaint() {
return this.dividerPaint;
}
/**
* Creates a time period that includes the specified millisecond, assuming
* the given time zone.
*
* @param millisecond the time.
* @param zone the time zone.
*
* @return The time period.
*
* @deprecated As of 1.0.13, use the method that specifies the locale also.
*/
public RegularTimePeriod createInstance(Date millisecond, TimeZone zone) {
return createInstance(millisecond, zone, Locale.getDefault());
}
/**
* Creates a time period that includes the specified millisecond, assuming
* the given time zone.
*
* @param millisecond the time.
* @param zone the time zone.
* @param locale the locale.
*
* @return The time period.
*
* @since 1.0.13.
*/
public RegularTimePeriod createInstance(Date millisecond, TimeZone zone,
Locale locale) {
RegularTimePeriod result = null;
try {
Constructor c = this.periodClass.getDeclaredConstructor(
new Class[] {Date.class, TimeZone.class, Locale.class});
result = (RegularTimePeriod) c.newInstance(new Object[] {
millisecond, zone, locale});
}
catch (Exception e) {
// do nothing
}
return result;
}
/**
* Tests this object for equality with an arbitrary object.
*
* @param obj the object to test against (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof PeriodAxisLabelInfo) {
PeriodAxisLabelInfo info = (PeriodAxisLabelInfo) obj;
if (!info.periodClass.equals(this.periodClass)) {
return false;
}
if (!info.dateFormat.equals(this.dateFormat)) {
return false;
}
if (!info.padding.equals(this.padding)) {
return false;
}
if (!info.labelFont.equals(this.labelFont)) {
return false;
}
if (!info.labelPaint.equals(this.labelPaint)) {
return false;
}
if (info.drawDividers != this.drawDividers) {
return false;
}
if (!info.dividerStroke.equals(this.dividerStroke)) {
return false;
}
if (!info.dividerPaint.equals(this.dividerPaint)) {
return false;
}
return true;
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 41;
result = 37 * this.periodClass.hashCode();
result = 37 * this.dateFormat.hashCode();
return result;
}
/**
* Returns a clone of the object.
*
* @return A clone.
*
* @throws CloneNotSupportedException if cloning is not supported.
*/
public Object clone() throws CloneNotSupportedException {
PeriodAxisLabelInfo clone = (PeriodAxisLabelInfo) super.clone();
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.labelPaint, stream);
SerialUtilities.writeStroke(this.dividerStroke, stream);
SerialUtilities.writePaint(this.dividerPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.labelPaint = SerialUtilities.readPaint(stream);
this.dividerStroke = SerialUtilities.readStroke(stream);
this.dividerPaint = SerialUtilities.readPaint(stream);
}
} |
package com.nowellpoint.aws.api.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.esotericsoftware.yamlbeans.YamlWriter;
import com.nowellpoint.aws.api.dto.EnvironmentDTO;
import com.nowellpoint.aws.api.dto.EnvironmentVariableDTO;
import com.nowellpoint.aws.api.dto.EventListenerDTO;
import com.nowellpoint.aws.api.dto.SalesforceConnectorDTO;
import com.nowellpoint.aws.api.dto.ServiceInstanceDTO;
import com.nowellpoint.aws.api.dto.ServiceProviderDTO;
import com.nowellpoint.aws.api.model.Environment;
import com.nowellpoint.aws.api.model.EnvironmentVariable;
import com.nowellpoint.aws.api.model.EventListener;
import com.nowellpoint.aws.api.model.SalesforceConnector;
import com.nowellpoint.aws.api.model.ServiceInstance;
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.DescribeGlobalResult;
import com.sforce.soap.partner.DescribeGlobalSObjectResult;
import com.sforce.soap.partner.DescribeSObjectResult;
import com.sforce.soap.partner.Field;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.fault.InvalidSObjectFault;
import com.sforce.soap.partner.fault.LoginFault;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class SalesforceConnectorService extends AbstractDocumentService<SalesforceConnectorDTO, SalesforceConnector> {
public SalesforceConnectorService() {
super(SalesforceConnectorDTO.class, SalesforceConnector.class);
}
public Set<SalesforceConnectorDTO> getAll(String subject) {
Set<SalesforceConnectorDTO> resources = hscan( subject, SalesforceConnectorDTO.class );
if (resources.isEmpty()) {
resources = findAllByOwner(subject);
hset( subject, resources );
}
return resources;
}
public SalesforceConnectorDTO createSalesforceConnector(SalesforceConnectorDTO resource) {
create( resource );
hset( resource.getSubject(), SalesforceConnectorDTO.class.getName().concat( resource.getId()), resource );
hset( resource.getId(), resource.getSubject(), resource );
return resource;
}
public SalesforceConnectorDTO updateSalesforceConnector(SalesforceConnectorDTO resource) {
SalesforceConnectorDTO original = findSalesforceConnector(resource.getSubject(), resource.getId());
resource.setCreatedById(original.getCreatedById());
resource.setCreatedDate(original.getCreatedDate());
replace( resource );
hset( resource.getSubject(), SalesforceConnectorDTO.class.getName().concat( resource.getId() ), resource );
hset( resource.getId(), resource.getSubject(), resource );
return resource;
}
public void deleteSalesforceConnector(String id, String subject) {
SalesforceConnectorDTO resource = new SalesforceConnectorDTO(id);
delete(resource);
hdel( subject, SalesforceConnectorDTO.class.getName().concat(id) );
hdel( id, subject );
}
public SalesforceConnectorDTO findSalesforceConnector(String subject, String id) {
SalesforceConnectorDTO resource = hget( SalesforceConnectorDTO.class, id, subject );
if ( resource == null ) {
resource = find(id);
hset( id, subject, resource );
}
return resource;
}
public SalesforceConnectorDTO addService(ServiceProviderDTO serviceProvider, String subject, String id) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setKey(UUID.randomUUID().toString().replace("-", ""));
serviceInstance.setServiceType(serviceProvider.getService().getType());
serviceInstance.setConfigurationPage(serviceProvider.getService().getConfigurationPage());
serviceInstance.setCurrencyIsoCode(serviceProvider.getService().getCurrencyIsoCode());
serviceInstance.setProviderName(serviceProvider.getName());
serviceInstance.setIsActive(Boolean.FALSE);
serviceInstance.setServiceName(serviceProvider.getService().getName());
serviceInstance.setPrice(serviceProvider.getService().getPrice());
serviceInstance.setProviderType(serviceProvider.getType());
serviceInstance.setUom(serviceProvider.getService().getUnitOfMeasure());
serviceInstance.setEnvironmentVariableValues(serviceProvider.getService().getEnvironmentVariableValues());
Set<Environment> environments = new HashSet<Environment>();
Environment environment = new Environment();
environment.setActive(Boolean.TRUE);
environment.setIndex(0);
environment.setLabel("Production");
environment.setLocked(Boolean.TRUE);
environment.setName("PRODUCTION");
environment.setStatus("NOT STARTED");
environment.setTest(Boolean.FALSE);
environment.setEnvironmentVariables(serviceProvider.getService().getEnvironmentVariables());
environments.add(environment);
for (int i = 0; i < serviceProvider.getService().getSandboxCount(); i++) {
environment = new Environment();
environment.setActive(Boolean.FALSE);
environment.setIndex(i + 1);
environment.setLocked(Boolean.FALSE);
environment.setName("SANDBOX_" + (i + 1));
environment.setStatus("NOT STARTED");
environment.setTest(Boolean.FALSE);
environment.setEnvironmentVariables(serviceProvider.getService().getEnvironmentVariables());
environments.add(environment);
}
serviceInstance.setEnvironments(environments);
resource.setSubject(subject);
resource.addServiceInstance(serviceInstance);
updateSalesforceConnector(resource);
return resource;
}
public SalesforceConnectorDTO updateService(String subject, String id, String key, ServiceInstanceDTO serviceInstance) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
if (resource.getServiceInstances() == null) {
resource.setServiceInstances(Collections.emptyList());
}
Map<String,ServiceInstance> map = resource.getServiceInstances().stream().collect(Collectors.toMap(p -> p.getKey(), (p) -> p));
resource.getServiceInstances().clear();
if (map.containsKey(key)) {
ServiceInstance original = map.get(key);
original.setDefaultEnvironment(serviceInstance.getDefaultEnvironment());
original.setName(serviceInstance.getName());
map.put(key, original);
}
resource.setServiceInstances(new ArrayList<ServiceInstance>(map.values()));
updateSalesforceConnector(resource);
return resource;
}
public SalesforceConnectorDTO removeService(String subject, String id, String key) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
resource.getServiceInstances().removeIf(p -> p.getKey().equals(key));
updateSalesforceConnector(resource);
return resource;
}
public SalesforceConnectorDTO addEnvironments(String subject, String id, String key, Set<EnvironmentDTO> environments) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances().stream().filter(p -> p.getKey().equals(key)).findFirst();
if (serviceInstance.isPresent()) {
Map<Integer,Environment> map = serviceInstance.get().getEnvironments().stream().collect(Collectors.toMap(p -> p.getIndex(), (p) -> p));
serviceInstance.get().getEnvironments().clear();
serviceInstance.get().setActiveEnvironments(new Long(0));
AtomicInteger index = new AtomicInteger();
environments.stream().sorted((p1,p2) -> p2.getIndex().compareTo(p1.getIndex())).forEach(e -> {
Environment environment = null;
if (map.containsKey(e.getIndex())) {
environment = map.get(e.getIndex());
} else {
environment = new Environment();
environment.setLocked(Boolean.FALSE);
environment.setIndex(index.get());
}
environment.setName(e.getName());
environment.setActive(e.getActive());
environment.setLabel(e.getLabel());
AtomicLong activeEnvironments = new AtomicLong(serviceInstance.get().getActiveEnvironments());
if (e.getActive()) {
activeEnvironments.incrementAndGet();
}
serviceInstance.get().setActiveEnvironments(activeEnvironments.get());
serviceInstance.get().getEnvironments().add(environment);
index.incrementAndGet();
});
}
updateSalesforceConnector(resource);
return resource;
}
public SalesforceConnectorDTO addEnvironmentVariables(String subject, String id, String key, String environmentName, Set<EnvironmentVariableDTO> environmentVariables) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
Set<String> variables = new HashSet<String>();
environmentVariables.stream().forEach(variable -> {
if (variables.contains(variable.getVariable())) {
throw new UnsupportedOperationException("Duplicate variable names: " + variable.getVariable());
}
variables.add(variable.getVariable());
if (variable.getVariable().contains(" ")) {
throw new IllegalArgumentException("Environment variables must not contain spaces: " + variable.getVariable());
}
});
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances().stream().filter(p -> p.getKey().equals(key)).findFirst();
if (serviceInstance.isPresent()) {
Optional<Environment> environment = serviceInstance.get().getEnvironments().stream().filter(p -> p.getName().equals(environmentName)).findFirst();
if (environment.isPresent()) {
Map<String,EnvironmentVariable> map = environment.get().getEnvironmentVariables().stream().collect(Collectors.toMap(p -> p.getVariable(), (p) -> p));
environment.get().getEnvironmentVariables().clear();
environmentVariables.stream().forEach(e -> {
EnvironmentVariable environmentVariable = null;
if (map.containsKey(e.getVariable())) {
environmentVariable = map.get(e.getVariable());
} else {
environmentVariable = new EnvironmentVariable();
environmentVariable.setVariable(e.getVariable());
environmentVariable.setLocked(Boolean.FALSE);
}
environmentVariable.setValue(e.getValue());
environmentVariable.setEncrypted(e.getEncrypted());
environment.get().getEnvironmentVariables().add(environmentVariable);
});
}
updateSalesforceConnector(resource);
}
return resource;
}
public SalesforceConnectorDTO addEventListeners(String subject, String id, String key, Set<EventListenerDTO> eventListeners) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances().stream().filter(p -> p.getKey().equals(key)).findFirst();
if (serviceInstance.isPresent()) {
if (serviceInstance.get().getEventListeners() == null) {
serviceInstance.get().setEventListeners(Collections.emptySet());
}
Map<String,EventListener> map = serviceInstance.get().getEventListeners().stream().collect(Collectors.toMap(p -> p.getType(), (p) -> p));
serviceInstance.get().getEventListeners().clear();
eventListeners.stream().forEach(p -> {
EventListener eventListener = modelMapper.map(p, EventListener.class);
map.put(p.getType(), eventListener);
});
serviceInstance.get().setEventListeners(new HashSet<EventListener>(map.values()));
updateSalesforceConnector(resource);
}
return resource;
}
public SalesforceConnectorDTO testConnection(String subject, String id, String key, String environmentName) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances()
.stream()
.filter(p -> p.getKey().equals(key))
.findFirst();
if (serviceInstance.isPresent()) {
Optional<Environment> environment = serviceInstance.get()
.getEnvironments()
.stream()
.filter(p -> p.getName().equals(environmentName))
.findFirst();
if (environment.isPresent()) {
try {
PartnerConnection connection = login(environment.get());
environment.get().setEndpoint(connection.getConfig().getServiceEndpoint());
environment.get().setOrganization(connection.getUserInfo().getOrganizationId());
environment.get().setTest(Boolean.TRUE);
environment.get().setTestMessage("Success!");
} catch (ConnectionException e) {
if (e instanceof LoginFault) {
LoginFault loginFault = (LoginFault) e;
environment.get().setTest(Boolean.FALSE);
environment.get().setTestMessage(loginFault.getExceptionCode().name().concat(": ").concat(loginFault.getExceptionMessage()));
} else {
throw new InternalServerErrorException(e.getMessage());
}
} catch (IllegalArgumentException e) {
environment.get().setTest(Boolean.FALSE);
environment.get().setTestMessage("Missing connection enviroment variables");
} finally {
updateSalesforceConnector(resource);
}
}
}
return resource;
}
public DescribeGlobalSObjectResult[] describeGlobal(String subject, String id, String key, String environmentName) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
DescribeGlobalSObjectResult[] sobjects = null;
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances()
.stream()
.filter(p -> p.getKey().equals(key))
.findFirst();
if (serviceInstance.isPresent()) {
Optional<Environment> environment = serviceInstance.get()
.getEnvironments()
.stream()
.filter(p -> p.getName().equals(environmentName))
.findFirst();
if (environment.isPresent()) {
try {
PartnerConnection connection = login(environment.get());
DescribeGlobalResult result = connection.describeGlobal();
sobjects = result.getSobjects();
//resource.setSobjects(sobjects);
// AmazonS3 s3Client = new AmazonS3Client();
// byte[] bytes = new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
// InputStream fileInputStream = new ByteArrayInputStream(bytes);
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType(MediaType.APPLICATION_JSON);
// metadata.setContentLength(bytes.length);
// PutObjectRequest putObjectRequest = new PutObjectRequest("nowellpoint-profile-photos", connection.getUserInfo().getOrganizationId(), fileInputStream, metadata);
// s3Client.putObject(putObjectRequest);
} catch (ConnectionException e) {
if (e instanceof LoginFault) {
LoginFault loginFault = (LoginFault) e;
throw new BadRequestException(loginFault.getExceptionCode().name().concat(": ").concat(loginFault.getExceptionMessage()));
} else {
throw new InternalServerErrorException(e.getMessage());
}
}
}
}
return sobjects;
}
public Field[] describeSobject(String subject, String id, String key, String environmentName, String sobject) {
SalesforceConnectorDTO resource = findSalesforceConnector(subject, id);
resource.setSubject(subject);
Field[] fields = null;
Optional<ServiceInstance> serviceInstance = resource.getServiceInstances()
.stream()
.filter(p -> p.getKey().equals(key))
.findFirst();
if (serviceInstance.isPresent()) {
Optional<Environment> environment = serviceInstance.get()
.getEnvironments()
.stream()
.filter(p -> p.getName().equals(environmentName))
.findFirst();
if (environment.isPresent()) {
try {
PartnerConnection connection = login(environment.get());
DescribeSObjectResult result = connection.describeSObject(sobject);
fields = result.getFields();
} catch (ConnectionException e) {
if (e instanceof LoginFault) {
LoginFault loginFault = (LoginFault) e;
throw new BadRequestException(loginFault.getExceptionCode().name().concat(": ").concat(loginFault.getExceptionMessage()));
} else if (e instanceof InvalidSObjectFault) {
InvalidSObjectFault fault = (InvalidSObjectFault) e;
throw new BadRequestException(fault.getExceptionCode().name().concat(": ").concat(fault.getExceptionMessage()));
} else {
throw new InternalServerErrorException(e.getMessage());
}
}
}
}
return fields;
}
public void addServiceConfiguration(String subject, String id, String key, Map<String, Object> configParams) {
SalesforceConnectorDTO salesforceConnector = findSalesforceConnector(subject, id);
Optional<ServiceInstance> serviceInstance = salesforceConnector.getServiceInstances().stream().filter(p -> p.getKey().equals(key)).findFirst();
Map<String,Object> configFile = new HashMap<String,Object>();
configFile.put("id", salesforceConnector.getIdentity().getId());
configFile.put("organizationId", salesforceConnector.getOrganization().getId());
configFile.put("instanceName", salesforceConnector.getOrganization().getInstanceName());
configFile.put("url.sobjects", salesforceConnector.getIdentity().getUrls().getSobjects());
configFile.put("url.metadata", salesforceConnector.getIdentity().getUrls().getMetadata());
configFile.put("key", serviceInstance.get().getKey());
configFile.put("providerType", serviceInstance.get().getProviderType());
configFile.putAll(configParams);
AmazonS3 s3Client = new AmazonS3Client();
try {
StringWriter sw = new StringWriter();
YamlWriter writer = new YamlWriter(sw);
writer.write(configFile);
writer.close();
byte[] bytes = sw.toString().getBytes(StandardCharsets.UTF_8);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(bytes.length);
objectMetadata.setContentType(MediaType.TEXT_PLAIN);
PutObjectRequest putObjectRequest = new PutObjectRequest("nowellpoint-configuration-files", key, new ByteArrayInputStream(bytes), objectMetadata);
s3Client.putObject(putObjectRequest);
} catch (IOException e) {
e.printStackTrace();
throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
}
}
private PartnerConnection login(Environment environment) throws IllegalArgumentException, ConnectionException {
String instance = null;
String username = null;
String password = null;
String securityToken = null;
Iterator<EnvironmentVariable> variables = environment.getEnvironmentVariables().iterator();
while (variables.hasNext()) {
EnvironmentVariable environmentVariable = variables.next();
if ("INSTANCE".equals(environmentVariable.getVariable())) {
instance = environmentVariable.getValue();
}
if ("USERNAME".equals(environmentVariable.getVariable())) {
username = environmentVariable.getValue();
}
if ("SECURITY_TOKEN".equals(environmentVariable.getVariable())) {
securityToken = environmentVariable.getValue();
}
if ("PASSWORD".equals(environmentVariable.getVariable())) {
password = environmentVariable.getValue();
}
}
if (instance == null || username == null || securityToken == null || password == null) {
throw new IllegalArgumentException();
}
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(String.format("%s/services/Soap/u/36.0", instance));
config.setUsername(username);
config.setPassword(password.concat(securityToken));
PartnerConnection connection = Connector.newConnection(config);
return connection;
}
} |
package it.unibz.krdb.obda.LUBM;
import it.unibz.krdb.obda.owlapi2.QuestPreferences;
import it.unibz.krdb.obda.owlrefplatform.core.QuestStatement;
import it.unibz.krdb.obda.owlrefplatform.questdb.QuestDBClassicStore;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.text.DecimalFormat;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
public class QuestRewritingBenchmarkTool {
int repeats = 1;
long start;
long stop;
Logger log = org.slf4j.LoggerFactory.getLogger(QuestRewritingBenchmarkTool.class);
public static void main(String args[]) {
final String queries[] = new String[] {
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
"PREFIX : <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl
try {
URI tboxuri = new File("/Users/mariano/Documents/Archive/Work/projects/semantic-index/lubm/benchmarks/quest/postgres/lubm3x-lite-rdfxml.owl")
.toURI();
Properties config = new Properties();
final PrintWriter out = new PrintWriter(new File("quest-evaluation.txt"));
final DecimalFormat format = new DecimalFormat("
config.load(new FileInputStream(new File(
"/Users/mariano/Documents/Archive/Work/projects/semantic-index/lubm/benchmarks/quest/lubmQSIEOTB.cfg")));
long start;
long stop;
QuestPreferences pref = new QuestPreferences();
pref.putAll(config);
start = System.nanoTime();
QuestDBClassicStore store = new QuestDBClassicStore("test", tboxuri, pref);
stop = System.nanoTime();
out.println("Quest initialization time: " + format.format((stop - start) / 1000000.0) + " ms");
out.println("Query,Ref.Time (ms), Size");
store.connect();
final QuestStatement st = store.getConnection().createStatement();
for (int i = 0; i < queries.length; i++) {
System.out.println("Query " + (i + 1));
final CountDownLatch latch = new CountDownLatch(1);
final int ii = i;
Thread ref = new Thread("benchmark-thread") {
@Override
public void run() {
try {
long start = System.nanoTime();
String rewriting = st.getRewriting(queries[ii]);
long stop = System.nanoTime();
String[] split = rewriting.split("\n");
String output = "%s,%s,%s";
out.println(String.format(output, ii + 1, format.format((stop - start) / 1000000.0), split.length));
out.flush();
latch.countDown();
System.out.println();
System.out.println(rewriting);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
};
ref.start();
if (latch.await(200, TimeUnit.SECONDS)) {
// normal, continue
} else {
System.err.println("Timeout");
//timeout
try {
ref.stop();
} catch (Exception e) {
}
String output = "%s,%s,%s";
out.println(String.format(output, ii + 1, 200000, -1));
}
}
st.close();
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package org.opennms.netmgt.rrd.jrobin;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Category;
import org.jrobin.core.FetchData;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdException;
import org.jrobin.core.Sample;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;
import org.opennms.core.utils.StringUtils;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdDataSource;
import org.opennms.netmgt.rrd.RrdGraphDetails;
import org.opennms.netmgt.rrd.RrdStrategy;
import org.opennms.netmgt.rrd.RrdUtils;
/**
* Provides a JRobin based implementation of RrdStrategy. It uses JRobin 1.4 in
* FILE mode (NIO is too memory consuming for the large number of files that we
* open)
*/
public class JRobinRrdStrategy implements RrdStrategy {
//Ensure that we only initialize certain things *once* per Java VM, not once per instantiation of this class
private static boolean s_initialized = false;
private boolean m_initialized = false;
/**
* Closes the JRobin RrdDb.
*/
public void closeFile(Object rrdFile) throws Exception {
((RrdDb) rrdFile).close();
}
public Object createDefinition(String creator, String directory, String rrdName, int step, List<RrdDataSource> dataSources, List<String> rraList) throws Exception {
File f = new File(directory);
f.mkdirs();
String fileName = directory + File.separator + rrdName + RrdUtils.getExtension();
if (new File(fileName).exists()) {
return null;
}
RrdDef def = new RrdDef(fileName);
// def.setStartTime(System.currentTimeMillis()/1000L - 2592000L);
def.setStartTime(1000);
def.setStep(step);
for (RrdDataSource dataSource : dataSources) {
String dsMin = dataSource.getMin();
String dsMax = dataSource.getMax();
double min = (dsMin == null || "U".equals(dsMin) ? Double.NaN : Double.parseDouble(dsMin));
double max = (dsMax == null || "U".equals(dsMax) ? Double.NaN : Double.parseDouble(dsMax));
def.addDatasource(dataSource.getName(), dataSource.getType(), dataSource.getHeartBeat(), min, max);
}
for (String rra : rraList) {
def.addArchive(rra);
}
return def;
}
/**
* Creates the JRobin RrdDb from the def by opening the file and then
* closing. TODO: Change the interface here to create the file and return it
* opened.
*/
public void createFile(Object rrdDef) throws Exception {
if (rrdDef == null) {
return;
}
RrdDb rrd = new RrdDb((RrdDef) rrdDef);
rrd.close();
}
/**
* Opens the JRobin RrdDb by name and returns it.
*/
public Object openFile(String fileName) throws Exception {
RrdDb rrd = new RrdDb(fileName);
return rrd;
}
/**
* Creates a sample from the JRobin RrdDb and passes in the data provided.
*/
public void updateFile(Object rrdFile, String owner, String data) throws Exception {
Sample sample = ((RrdDb) rrdFile).createSample();
sample.setAndUpdate(data);
}
/**
* Initialized the RrdDb to use the FILE factory because the NIO factory
* uses too much memory for our implementation.
*/
public synchronized void initialize() throws Exception {
if (!m_initialized) {
if(!s_initialized) {
RrdDb.setDefaultFactory("FILE");
String factory = RrdConfig.getProperty("org.jrobin.core.RrdBackendFactory", "FILE");
RrdDb.setDefaultFactory(factory );
s_initialized=true;
}
String home = System.getProperty("opennms.home");
System.setProperty("jrobin.fontdir", home + File.separator + "etc");
m_initialized = true;
}
}
/*
* (non-Javadoc)
*
* @see org.opennms.netmgt.rrd.RrdStrategy#graphicsInitialize()
*/
public void graphicsInitialize() throws Exception {
initialize();
}
/**
* Fetch the last value from the JRobin RrdDb file.
*/
public Double fetchLastValue(String fileName, String ds, int interval) throws NumberFormatException, org.opennms.netmgt.rrd.RrdException {
return fetchLastValue(fileName, ds, "AVERAGE", interval);
}
public Double fetchLastValue(String fileName, String ds, String consolidationFunction, int interval)
throws org.opennms.netmgt.rrd.RrdException {
RrdDb rrd = null;
try {
long now = System.currentTimeMillis();
long collectTime = (now - (now % interval)) / 1000L;
rrd = new RrdDb(fileName);
FetchData data = rrd.createFetchRequest(consolidationFunction, collectTime, collectTime).fetchData();
if(log().isDebugEnabled()) {
//The "toString" method of FetchData is quite computationally expensive;
log().debug(data.toString());
}
double[] vals = data.getValues(ds);
if (vals.length > 0) {
return new Double(vals[vals.length - 1]);
}
return null;
} catch (IOException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} catch (RrdException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} finally {
if (rrd != null) {
try {
rrd.close();
} catch (IOException e) {
log().error("Failed to close rrd file: " + fileName, e);
}
}
}
}
public Double fetchLastValueInRange(String fileName, String ds, int interval, int range) throws NumberFormatException, org.opennms.netmgt.rrd.RrdException {
RrdDb rrd = null;
try {
rrd = new RrdDb(fileName);
long now = System.currentTimeMillis();
long latestUpdateTime = (now - (now % interval)) / 1000L;
long earliestUpdateTime = ((now - (now % interval)) - range) / 1000L;
if (log().isDebugEnabled()) {
log().debug("fetchInRange: fetching data from " + earliestUpdateTime + " to " + latestUpdateTime);
}
FetchData data = rrd.createFetchRequest("AVERAGE", earliestUpdateTime, latestUpdateTime).fetchData();
double[] vals = data.getValues(ds);
long[] times = data.getTimestamps();
// step backwards through the array of values until we get something that's a number
for(int i = vals.length - 1; i >= 0; i
if ( Double.isNaN(vals[i]) ) {
if (log().isDebugEnabled()) {
log().debug("fetchInRange: Got a NaN value at interval: " + times[i] + " continuing back in time");
}
} else {
if (log().isDebugEnabled()) {
log().debug("Got a non NaN value at interval: " + times[i] + " : " + vals[i] );
}
return new Double(vals[i]);
}
}
return null;
} catch (IOException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} catch (RrdException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} finally {
if (rrd != null) {
try {
rrd.close();
} catch (IOException e) {
log().error("Failed to close rrd file: " + fileName, e);
}
}
}
}
private Color getColor(String colorValue) {
int colorVal = Integer.parseInt(colorValue, 16);
return new Color(colorVal);
}
// For compatibility with RRDtool defs, the colour value for
// LINE and AREA is optional. If it's missing, the line is rendered
// invisibly.
private Color getColorOrInvisible(String[] array, int index) {
if (array.length > index) {
return getColor(array[index]);
}
return new Color(1.0f, 1.0f, 1.0f, 0.0f);
}
public InputStream createGraph(String command, File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException {
return createGraphReturnDetails(command, workDir).getInputStream();
}
/**
* This constructs a graphDef by parsing the rrdtool style command and using
* the values to create the JRobin graphDef. It does not understand the 'AT
* style' time arguments however. Also there may be some rrdtool parameters
* that it does not understand. These will be ignored. The graphDef will be
* used to construct an RrdGraph and a PNG image will be created. An input
* stream returning the bytes of the PNG image is returned.
*/
public RrdGraphDetails createGraphReturnDetails(String command, File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException {
try {
String[] commandArray = tokenize(command, " \t", false);
RrdGraphDef graphDef = createGraphDef(workDir, commandArray);
graphDef.setSignature("OpenNMS/JRobin");
RrdGraph graph = new RrdGraph(graphDef);
/*
* We use a custom RrdGraphDetails object here instead of the
* DefaultRrdGraphDetails because we won't have an InputStream
* available if no graphing commands were used, e.g.: if we only
* use PRINT or if the user goofs up a graph definition.
*
* We want to throw an RrdException if the caller calls
* RrdGraphDetails.getInputStream and no graphing commands were
* used. If they just call RrdGraphDetails.getPrintLines, though,
* we don't want to throw an exception.
*/
return new JRobinRrdGraphDetails(graph, command);
} catch (Exception e) {
log().error("JRobin: exception occurred creating graph: " + e.getMessage(), e);
throw new org.opennms.netmgt.rrd.RrdException("An exception occurred creating the graph: " + e.getMessage(), e);
}
}
public void promoteEnqueuedFiles(Collection<String> rrdFiles) {
// no need to do anything since this strategy doesn't queue
}
protected RrdGraphDef createGraphDef(File workDir, String[] commandArray) throws RrdException {
RrdGraphDef graphDef = new RrdGraphDef();
graphDef.setImageFormat("PNG");
long start = 0;
long end = 0;
int height = 100;
int width = 400;
double lowerLimit = Double.NaN;
double upperLimit = Double.NaN;
boolean rigid = false;
for (int i = 0; i < commandArray.length; i++) {
String arg = commandArray[i];
if (arg.startsWith("--start=")) {
start = Long.parseLong(arg.substring("--start=".length()));
log().debug("JRobin start time: " + start);
} else if (arg.equals("--start")) {
if (i + 1 < commandArray.length) {
start = Long.parseLong(commandArray[++i]);
log().debug("JRobin start time: " + start);
} else {
throw new IllegalArgumentException("--start must be followed by a start time");
}
} else if (arg.startsWith("--end=")) {
end = Long.parseLong(arg.substring("--end=".length()));
log().debug("JRobin end time: " + end);
} else if (arg.equals("--end")) {
if (i + 1 < commandArray.length) {
end = Long.parseLong(commandArray[++i]);
log().debug("JRobin end time: " + end);
} else {
throw new IllegalArgumentException("--end must be followed by an end time");
}
} else if (arg.startsWith("--title=")) {
String[] title = tokenize(arg, "=", true);
graphDef.setTitle(title[1]);
} else if (arg.equals("--title")) {
if (i + 1 < commandArray.length) {
graphDef.setTitle(commandArray[++i]);
} else {
throw new IllegalArgumentException("--title must be followed by a title");
}
} else if (arg.startsWith("--color=")) {
String[] color = tokenize(arg, "=", true);
parseGraphColor(graphDef, color[1]);
} else if (arg.equals("--color") || arg.equals("-c")) {
if (i + 1 < commandArray.length) {
parseGraphColor(graphDef, commandArray[++i]);
} else {
throw new IllegalArgumentException("--color must be followed by a color");
}
} else if (arg.startsWith("--vertical-label=")) {
String[] label = tokenize(arg, "=", true);
graphDef.setVerticalLabel(label[1]);
} else if (arg.equals("--vertical-label")) {
if (i + 1 < commandArray.length) {
graphDef.setVerticalLabel(commandArray[++i]);
} else {
throw new IllegalArgumentException("--vertical-label must be followed by a label");
}
} else if (arg.startsWith("--height=")) {
String[] argParm = tokenize(arg, "=", true);
height = Integer.parseInt(argParm[1]);
log().debug("JRobin height: "+height);
} else if (arg.equals("--height")) {
if (i + 1 < commandArray.length) {
height = Integer.parseInt(commandArray[++i]);
log().debug("JRobin height: "+height);
} else {
throw new IllegalArgumentException("--height must be followed by a number");
}
} else if (arg.startsWith("--width=")) {
String[] argParm = tokenize(arg, "=", true);
width = Integer.parseInt(argParm[1]);
log().debug("JRobin width: "+height);
} else if (arg.equals("--width")) {
if (i + 1 < commandArray.length) {
width = Integer.parseInt(commandArray[++i]);
log().debug("JRobin width: "+height);
} else {
throw new IllegalArgumentException("--width must be followed by a number");
}
} else if (arg.startsWith("--units-exponent=")) {
String[] argParm = tokenize(arg, "=", true);
int exponent = Integer.parseInt(argParm[1]);
log().debug("JRobin units exponent: "+exponent);
graphDef.setUnitsExponent(exponent);
} else if (arg.equals("--units-exponent")) {
if (i + 1 < commandArray.length) {
int exponent = Integer.parseInt(commandArray[++i]);
log().debug("JRobin units exponent: "+exponent);
graphDef.setUnitsExponent(exponent);
} else {
throw new IllegalArgumentException("--units-exponent must be followed by a number");
}
} else if (arg.startsWith("--lower-limit=")) {
String[] argParm = tokenize(arg, "=", true);
lowerLimit = Double.parseDouble(argParm[1]);
log().debug("JRobin lower limit: "+lowerLimit);
} else if (arg.equals("--lower-limit")) {
if (i + 1 < commandArray.length) {
lowerLimit = Double.parseDouble(commandArray[++i]);
log().debug("JRobin lower limit: "+lowerLimit);
} else {
throw new IllegalArgumentException("--lower-limit must be followed by a number");
}
} else if (arg.startsWith("--upper-limit=")) {
String[] argParm = tokenize(arg, "=", true);
upperLimit = Double.parseDouble(argParm[1]);
log().debug("JRobin upp limit: "+upperLimit);
} else if (arg.equals("--upper-limit")) {
if (i + 1 < commandArray.length) {
upperLimit = Double.parseDouble(commandArray[++i]);
log().debug("JRobin upper limit: "+upperLimit);
} else {
throw new IllegalArgumentException("--upper-limit must be followed by a number");
}
} else if (arg.startsWith("--base=")) {
String[] argParm = tokenize(arg, "=", true);
graphDef.setBase(Double.parseDouble(argParm[1]));
} else if (arg.equals("--base")) {
if (i + 1 < commandArray.length) {
graphDef.setBase(Double.parseDouble(commandArray[++i]));
} else {
throw new IllegalArgumentException("--base must be followed by a number");
}
} else if (arg.startsWith("--font=")) {
String[] argParm = tokenize(arg, "=", true);
processRrdFontArgument(graphDef, argParm[1]);
} else if (arg.equals("--font")) {
if (i + 1 < commandArray.length) {
processRrdFontArgument(graphDef, commandArray[++i]);
} else {
throw new IllegalArgumentException("--font must be followed by an argument");
}
} else if (arg.startsWith("--imgformat=")) {
String[] argParm = tokenize(arg, "=", true);
graphDef.setImageFormat(argParm[1]);
} else if (arg.equals("--imgformat")) {
if (i + 1 < commandArray.length) {
graphDef.setImageFormat(commandArray[++i]);
} else {
throw new IllegalArgumentException("--imgformat must be followed by an argument");
}
} else if (arg.equals("--rigid")) {
rigid = true;
} else if (arg.startsWith("DEF:")) {
String definition = arg.substring("DEF:".length());
String[] def = definition.split(":");
String[] ds = def[0].split("=");
File dsFile = new File(workDir, ds[1]);
graphDef.datasource(ds[0], dsFile.getAbsolutePath(), def[1], def[2]);
} else if (arg.startsWith("CDEF:")) {
String definition = arg.substring("CDEF:".length());
String[] cdef = tokenize(definition, "=", true);
graphDef.datasource(cdef[0], cdef[1]);
} else if (arg.startsWith("LINE1:")) {
String definition = arg.substring("LINE1:".length());
String[] line1 = tokenize(definition, ":", true);
String[] color = tokenize(line1[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line1.length > 1 ? line1[1] : ""));
} else if (arg.startsWith("LINE2:")) {
String definition = arg.substring("LINE2:".length());
String[] line2 = tokenize(definition, ":", true);
String[] color = tokenize(line2[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line2.length > 1 ? line2[1] : ""), 2);
} else if (arg.startsWith("LINE3:")) {
String definition = arg.substring("LINE3:".length());
String[] line3 = tokenize(definition, ":", true);
String[] color = tokenize(line3[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line3.length > 1 ? line3[1] : ""), 3);
} else if (arg.startsWith("GPRINT:")) {
String definition = arg.substring("GPRINT:".length());
String gprint[] = tokenize(definition, ":", true);
String format = gprint[2];
//format = format.replaceAll("%(\\d*\\.\\d*)lf", "@$1");
//format = format.replaceAll("%s", "@s");
//format = format.replaceAll("%%", "%");
//log.debug("gprint: oldformat = " + gprint[2] + " newformat = " + format);
format = format.replaceAll("\\n", "\\\\l");
graphDef.gprint(gprint[0], gprint[1], format);
} else if (arg.startsWith("PRINT:")) {
String definition = arg.substring("PRINT:".length());
String print[] = tokenize(definition, ":", true);
String format = print[2];
//format = format.replaceAll("%(\\d*\\.\\d*)lf", "@$1");
//format = format.replaceAll("%s", "@s");
//format = format.replaceAll("%%", "%");
//log.debug("gprint: oldformat = " + print[2] + " newformat = " + format);
format = format.replaceAll("\\n", "\\\\l");
graphDef.print(print[0], print[1], format);
} else if (arg.startsWith("COMMENT:")) {
String comments[] = tokenize(arg, ":", true);
String format = comments[1].replaceAll("\\n", "\\\\l");
graphDef.comment(format);
} else if (arg.startsWith("AREA:")) {
String definition = arg.substring("AREA:".length());
String area[] = tokenize(definition, ":", true);
String[] color = tokenize(area[0], "#", true);
if (area.length > 1) {
graphDef.area(color[0], getColorOrInvisible(color, 1), area[1]);
} else {
graphDef.area(color[0], getColorOrInvisible(color, 1));
}
} else if (arg.startsWith("STACK:")) {
String definition = arg.substring("STACK:".length());
String stack[] = tokenize(definition, ":", true);
String[] color = tokenize(stack[0], "#", true);
graphDef.stack(color[0], getColor(color[1]), (stack.length > 1 ? stack[1] : ""));
} else {
log().warn("JRobin: Unrecognized graph argument: " + arg);
}
}
graphDef.setTimeSpan(start, end);
graphDef.setMinValue(lowerLimit);
graphDef.setMaxValue(upperLimit);
graphDef.setRigid(rigid);
graphDef.setHeight(height);
graphDef.setWidth(width);
// graphDef.setSmallFont(new Font("Monospaced", Font.PLAIN, 10));
// graphDef.setLargeFont(new Font("Monospaced", Font.PLAIN, 12));
log().debug("JRobin Finished tokenizing checking: start time: " + start + "; end time: " + end);
log().debug("large font = " + graphDef.getLargeFont() + ", small font = " + graphDef.getSmallFont());
return graphDef;
}
private void processRrdFontArgument(RrdGraphDef graphDef, String argParm) {
/*
String[] argValue = tokenize(argParm, ":", true);
if (argValue[0].equals("DEFAULT")) {
int newPointSize = Integer.parseInt(argValue[1]);
graphDef.setSmallFont(graphDef.getSmallFont().deriveFont(newPointSize));
} else if (argValue[0].equals("TITLE")) {
int newPointSize = Integer.parseInt(argValue[1]);
graphDef.setLargeFont(graphDef.getLargeFont().deriveFont(newPointSize));
} else {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File(argValue[0]));
} catch (Exception e) {
// oh well, fall back to existing font stuff
log().warn("unable to create font from font argument " + argParm, e);
}
}
*/
}
private String[] tokenize(String line, String delimiters, boolean processQuotes) {
String passthroughTokens = "lcrjgsJ"; /* see org.jrobin.graph.RrdGraphConstants.MARKERS */
return StringUtils.tokenizeWithQuotingAndEscapes(line, delimiters, processQuotes, passthroughTokens);
}
private void parseGraphColor(RrdGraphDef graphDef, String colorArg) throws IllegalArgumentException {
// Parse for format COLORTAG#RRGGBB
String[] colorArgParts = tokenize(colorArg, "#", false);
if (colorArgParts.length != 2) {
throw new IllegalArgumentException("--color must be followed by value with format COLORTAG#RRGGBB");
}
String colorTag = colorArgParts[0].toUpperCase();
String colorHex = colorArgParts[1].toUpperCase();
// validate hex color input is actually an RGB hex color value
if (colorHex.length() != 6) {
throw new IllegalArgumentException("--color must be followed by value with format COLORTAG#RRGGBB");
}
// this might throw NumberFormatException, but whoever wrote
// createGraph didn't seem to care, so I guess I don't care either.
// It'll get wrapped in an RrdException anyway.
Color color = getColor(colorHex);
// These are the documented RRD color tags
try {
if (colorTag.equals("BACK")) {
graphDef.setColor("BACK", color);
}
else if (colorTag.equals("CANVAS")) {
graphDef.setColor("CANVAS", color);
}
else if (colorTag.equals("SHADEA")) {
graphDef.setColor("SHADEA", color);
}
else if (colorTag.equals("SHADEB")) {
graphDef.setColor("SHADEB", color);
}
else if (colorTag.equals("GRID")) {
graphDef.setColor("GRID", color);
}
else if (colorTag.equals("MGRID")) {
graphDef.setColor("MGRID", color);
}
else if (colorTag.equals("FONT")) {
graphDef.setColor("FONT", color);
}
else if (colorTag.equals("FRAME")) {
graphDef.setColor("FRAME", color);
}
else if (colorTag.equals("ARROW")) {
graphDef.setColor("ARROW", color);
}
else {
throw new org.jrobin.core.RrdException("Unknown color tag " + colorTag);
}
} catch (Exception e) {
log().error("JRobin: exception occurred creating graph: " + e, e);
}
}
/**
* This implementation does not track any stats.
*/
public String getStats() {
return "";
}
/*
* These offsets work for ranger@ with Safari and JRobin 1.5.8.
*/
public int getGraphLeftOffset() {
return 74;
}
public int getGraphRightOffset() {
return -15;
}
public int getGraphTopOffsetWithText() {
return -61;
}
public String getDefaultFileExtension() {
return ".jrb";
}
private final Category log() {
return ThreadCategory.getInstance(getClass());
}
} |
package org.opennms.netmgt.rrd.jrobin;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.jrobin.core.FetchData;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdException;
import org.jrobin.core.Sample;
import org.jrobin.data.DataProcessor;
import org.jrobin.data.Plottable;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;
import org.opennms.netmgt.rrd.RrdDataSource;
import org.opennms.netmgt.rrd.RrdGraphDetails;
import org.opennms.netmgt.rrd.RrdStrategy;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdGraphDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides a JRobin based implementation of RrdStrategy. It uses JRobin 1.4 in
* FILE mode (NIO is too memory consuming for the large number of files that we
* open)
*
* @author ranger
* @version $Id: $
*/
public class JRobinRrdStrategy implements RrdStrategy<RrdDef,RrdDb> {
private static final Logger LOG = LoggerFactory.getLogger(JRobinRrdStrategy.class);
private static final String BACKEND_FACTORY_PROPERTY = "org.jrobin.core.RrdBackendFactory";
private static final String DEFAULT_BACKEND_FACTORY = "FILE";
/*
* Ensure that we only initialize certain things *once* per
* Java VM, not once per instantiation of this class.
*/
private static boolean s_initialized = false;
private Properties m_configurationProperties;
/**
* An extremely simple Plottable for holding static datasources that
* can't be represented with an SDEF -- currently used only for PERCENT
* pseudo-VDEFs
*
* @author jeffg
*
*/
static class ConstantStaticDef extends Plottable {
private double m_startTime = Double.NEGATIVE_INFINITY;
private double m_endTime = Double.POSITIVE_INFINITY;
private double m_value = Double.NaN;
ConstantStaticDef(long startTime, long endTime, double value) {
m_startTime = startTime;
m_endTime = endTime;
m_value = value;
}
@Override
public double getValue(long timestamp) {
if (m_startTime <= timestamp && m_endTime >= timestamp) {
return m_value;
} else {
return Double.NaN;
}
}
}
/**
* <p>getConfigurationProperties</p>
*
* @return a {@link java.util.Properties} object.
*/
public Properties getConfigurationProperties() {
return m_configurationProperties;
}
/** {@inheritDoc} */
@Override
public void setConfigurationProperties(final Properties configurationParameters) {
m_configurationProperties = configurationParameters;
if(!s_initialized) {
String factory = null;
if (m_configurationProperties == null) {
factory = DEFAULT_BACKEND_FACTORY;
} else {
factory = (String)m_configurationProperties.get(BACKEND_FACTORY_PROPERTY);
}
try {
RrdDb.setDefaultFactory(factory);
s_initialized=true;
} catch (RrdException e) {
LOG.error("Could not set default JRobin RRD factory", e);
}
}
}
/**
* Closes the JRobin RrdDb.
*
* @param rrdFile a {@link org.jrobin.core.RrdDb} object.
* @throws java.lang.Exception if any.
*/
@Override
public void closeFile(final RrdDb rrdFile) throws Exception {
rrdFile.close();
}
/** {@inheritDoc} */
@Override
public RrdDef createDefinition(final String creator,
final String directory, final String rrdName, int step,
final List<RrdDataSource> dataSources, final List<String> rraList) throws Exception {
File f = new File(directory);
f.mkdirs();
String fileName = directory + File.separator + rrdName + RrdUtils.getExtension();
if (new File(fileName).exists()) {
LOG.debug("createDefinition: filename [{}] already exists returning null as definition", fileName);
return null;
}
RrdDef def = new RrdDef(fileName);
// def.setStartTime(System.currentTimeMillis()/1000L - 2592000L);
def.setStartTime(1000);
def.setStep(step);
for (RrdDataSource dataSource : dataSources) {
String dsMin = dataSource.getMin();
String dsMax = dataSource.getMax();
double min = (dsMin == null || "U".equals(dsMin) ? Double.NaN : Double.parseDouble(dsMin));
double max = (dsMax == null || "U".equals(dsMax) ? Double.NaN : Double.parseDouble(dsMax));
def.addDatasource(dataSource.getName(), dataSource.getType(), dataSource.getHeartBeat(), min, max);
}
for (String rra : rraList) {
def.addArchive(rra);
}
return def;
}
/**
* Creates the JRobin RrdDb from the def by opening the file and then
* closing.
*
* @param rrdDef a {@link org.jrobin.core.RrdDef} object.
* @throws java.lang.Exception if any.
*/
@Override
public void createFile(final RrdDef rrdDef, Map<String, String> attributeMappings) throws Exception {
if (rrdDef == null) {
LOG.debug("createRRD: skipping RRD file");
return;
}
LOG.info("createRRD: creating RRD file {}", rrdDef.getPath());
RrdDb rrd = new RrdDb(rrdDef);
rrd.close();
String filenameWithoutExtension = rrdDef.getPath().replace(RrdUtils.getExtension(), "");
int lastIndexOfSeparator = filenameWithoutExtension.lastIndexOf(File.separator);
RrdUtils.createMetaDataFile(
filenameWithoutExtension.substring(0, lastIndexOfSeparator),
filenameWithoutExtension.substring(lastIndexOfSeparator),
attributeMappings
);
}
/**
* {@inheritDoc}
*
* Opens the JRobin RrdDb by name and returns it.
*/
@Override
public RrdDb openFile(final String fileName) throws Exception {
return new RrdDb(fileName);
}
/**
* {@inheritDoc}
*
* Creates a sample from the JRobin RrdDb and passes in the data provided.
*/
@Override
public void updateFile(final RrdDb rrdFile, final String owner, final String data) throws Exception {
Sample sample = rrdFile.createSample();
sample.setAndUpdate(data);
}
/**
* Initialized the RrdDb to use the FILE factory because the NIO factory
* uses too much memory for our implementation.
*
* @throws java.lang.Exception if any.
*/
public JRobinRrdStrategy() throws Exception {
String home = System.getProperty("opennms.home");
System.setProperty("jrobin.fontdir", home + File.separator + "etc");
}
/**
* {@inheritDoc}
*
* Fetch the last value from the JRobin RrdDb file.
*/
@Override
public Double fetchLastValue(final String fileName, final String ds, final int interval) throws NumberFormatException, org.opennms.netmgt.rrd.RrdException {
return fetchLastValue(fileName, ds, "AVERAGE", interval);
}
/** {@inheritDoc} */
@Override
public Double fetchLastValue(final String fileName, final String ds, final String consolidationFunction, final int interval)
throws org.opennms.netmgt.rrd.RrdException {
RrdDb rrd = null;
try {
long now = System.currentTimeMillis();
long collectTime = (now - (now % interval)) / 1000L;
rrd = new RrdDb(fileName, true);
FetchData data = rrd.createFetchRequest(consolidationFunction, collectTime, collectTime).fetchData();
LOG.debug(data.toString());
double[] vals = data.getValues(ds);
if (vals.length > 0) {
return new Double(vals[vals.length - 1]);
}
return null;
} catch (IOException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} catch (RrdException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} finally {
if (rrd != null) {
try {
rrd.close();
} catch (IOException e) {
LOG.error("Failed to close rrd file: {}", fileName, e);
}
}
}
}
/** {@inheritDoc} */
@Override
public Double fetchLastValueInRange(final String fileName, final String ds, final int interval, final int range) throws NumberFormatException, org.opennms.netmgt.rrd.RrdException {
RrdDb rrd = null;
try {
rrd = new RrdDb(fileName, true);
long now = System.currentTimeMillis();
long latestUpdateTime = (now - (now % interval)) / 1000L;
long earliestUpdateTime = ((now - (now % interval)) - range) / 1000L;
LOG.debug("fetchInRange: fetching data from {} to {}", earliestUpdateTime, latestUpdateTime);
FetchData data = rrd.createFetchRequest("AVERAGE", earliestUpdateTime, latestUpdateTime).fetchData();
double[] vals = data.getValues(ds);
long[] times = data.getTimestamps();
// step backwards through the array of values until we get something that's a number
for(int i = vals.length - 1; i >= 0; i
if ( Double.isNaN(vals[i]) ) {
LOG.debug("fetchInRange: Got a NaN value at interval: {} continuing back in time", times[i]);
} else {
LOG.debug("Got a non NaN value at interval: {} : {}", times[i], vals[i] );
return new Double(vals[i]);
}
}
return null;
} catch (IOException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} catch (RrdException e) {
throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e);
} finally {
if (rrd != null) {
try {
rrd.close();
} catch (IOException e) {
LOG.error("Failed to close rrd file: {}", fileName, e);
}
}
}
}
private Color getColor(final String colorValue) {
int rVal = Integer.parseInt(colorValue.substring(0, 2), 16);
int gVal = Integer.parseInt(colorValue.substring(2, 4), 16);
int bVal = Integer.parseInt(colorValue.substring(4, 6), 16);
if (colorValue.length() == 6) {
return new Color(rVal, gVal, bVal);
}
int aVal = Integer.parseInt(colorValue.substring(6, 8), 16);
return new Color(rVal, gVal, bVal, aVal);
}
// For compatibility with RRDtool defs, the colour value for
// LINE and AREA is optional. If it's missing, the line is rendered
// invisibly.
private Color getColorOrInvisible(final String[] array, final int index) {
if (array.length > index) {
return getColor(array[index]);
}
return new Color(1.0f, 1.0f, 1.0f, 0.0f);
}
/** {@inheritDoc} */
@Override
public InputStream createGraph(final String command, final File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException {
return createGraphReturnDetails(command, workDir).getInputStream();
}
/**
* {@inheritDoc}
*
* This constructs a graphDef by parsing the rrdtool style command and using
* the values to create the JRobin graphDef. It does not understand the 'AT
* style' time arguments however. Also there may be some rrdtool parameters
* that it does not understand. These will be ignored. The graphDef will be
* used to construct an RrdGraph and a PNG image will be created. An input
* stream returning the bytes of the PNG image is returned.
*/
@Override
public RrdGraphDetails createGraphReturnDetails(final String command, final File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException {
try {
String[] commandArray = tokenize(command, " \t", false);
RrdGraphDef graphDef = createGraphDef(workDir, commandArray);
graphDef.setSignature("OpenNMS/JRobin");
RrdGraph graph = new RrdGraph(graphDef);
/*
* We use a custom RrdGraphDetails object here instead of the
* DefaultRrdGraphDetails because we won't have an InputStream
* available if no graphing commands were used, e.g.: if we only
* use PRINT or if the user goofs up a graph definition.
*
* We want to throw an RrdException if the caller calls
* RrdGraphDetails.getInputStream and no graphing commands were
* used. If they just call RrdGraphDetails.getPrintLines, though,
* we don't want to throw an exception.
*/
return new JRobinRrdGraphDetails(graph, command);
} catch (Throwable e) {
LOG.error("JRobin: exception occurred creating graph", e);
throw new org.opennms.netmgt.rrd.RrdException("An exception occurred creating the graph: " + e.getMessage(), e);
}
}
/** {@inheritDoc} */
@Override
public void promoteEnqueuedFiles(Collection<String> rrdFiles) {
// no need to do anything since this strategy doesn't queue
}
/**
* <p>createGraphDef</p>
*
* @param workDir a {@link java.io.File} object.
* @param commandArray an array of {@link java.lang.String} objects.
* @return a {@link org.jrobin.graph.RrdGraphDef} object.
* @throws org.jrobin.core.RrdException if any.
*/
protected RrdGraphDef createGraphDef(final File workDir, final String[] inputArray) throws RrdException {
RrdGraphDef graphDef = new RrdGraphDef();
graphDef.setImageFormat("PNG");
long start = 0;
long end = 0;
int height = 100;
int width = 400;
double lowerLimit = Double.NaN;
double upperLimit = Double.NaN;
boolean rigid = false;
Map<String,List<String>> defs = new LinkedHashMap<String,List<String>>();
// Map<String,List<String>> cdefs = new HashMap<String,List<String>>();
final String[] commandArray;
if (inputArray[0].contains("rrdtool") && inputArray[1].equals("graph") && inputArray[2].equals("-")) {
commandArray = Arrays.copyOfRange(inputArray, 3, inputArray.length);
} else {
commandArray = inputArray;
}
LOG.debug("command array = {}", Arrays.toString(commandArray));
for (int i = 0; i < commandArray.length; i++) {
String arg = commandArray[i];
if (arg.startsWith("--start=")) {
start = Long.parseLong(arg.substring("--start=".length()));
LOG.debug("JRobin start time: {}", start);
} else if (arg.equals("--start")) {
if (i + 1 < commandArray.length) {
start = Long.parseLong(commandArray[++i]);
LOG.debug("JRobin start time: {}", start);
} else {
throw new IllegalArgumentException("--start must be followed by a start time");
}
} else if (arg.startsWith("--end=")) {
end = Long.parseLong(arg.substring("--end=".length()));
LOG.debug("JRobin end time: {}", end);
} else if (arg.equals("--end")) {
if (i + 1 < commandArray.length) {
end = Long.parseLong(commandArray[++i]);
LOG.debug("JRobin end time: {}", end);
} else {
throw new IllegalArgumentException("--end must be followed by an end time");
}
} else if (arg.startsWith("--title=")) {
String[] title = tokenize(arg, "=", true);
graphDef.setTitle(title[1]);
} else if (arg.equals("--title")) {
if (i + 1 < commandArray.length) {
graphDef.setTitle(commandArray[++i]);
} else {
throw new IllegalArgumentException("--title must be followed by a title");
}
} else if (arg.startsWith("--color=")) {
String[] color = tokenize(arg, "=", true);
parseGraphColor(graphDef, color[1]);
} else if (arg.equals("--color") || arg.equals("-c")) {
if (i + 1 < commandArray.length) {
parseGraphColor(graphDef, commandArray[++i]);
} else {
throw new IllegalArgumentException("--color must be followed by a color");
}
} else if (arg.startsWith("--vertical-label=")) {
String[] label = tokenize(arg, "=", true);
graphDef.setVerticalLabel(label[1]);
} else if (arg.equals("--vertical-label")) {
if (i + 1 < commandArray.length) {
graphDef.setVerticalLabel(commandArray[++i]);
} else {
throw new IllegalArgumentException("--vertical-label must be followed by a label");
}
} else if (arg.startsWith("--height=")) {
String[] argParm = tokenize(arg, "=", true);
height = Integer.parseInt(argParm[1]);
LOG.debug("JRobin height: {}", height);
} else if (arg.equals("--height")) {
if (i + 1 < commandArray.length) {
height = Integer.parseInt(commandArray[++i]);
LOG.debug("JRobin height: {}", height);
} else {
throw new IllegalArgumentException("--height must be followed by a number");
}
} else if (arg.startsWith("--width=")) {
String[] argParm = tokenize(arg, "=", true);
width = Integer.parseInt(argParm[1]);
LOG.debug("JRobin width: {}", width);
} else if (arg.equals("--width")) {
if (i + 1 < commandArray.length) {
width = Integer.parseInt(commandArray[++i]);
LOG.debug("JRobin width: {}", width);
} else {
throw new IllegalArgumentException("--width must be followed by a number");
}
} else if (arg.startsWith("--units-exponent=")) {
String[] argParm = tokenize(arg, "=", true);
int exponent = Integer.parseInt(argParm[1]);
LOG.debug("JRobin units exponent: {}", exponent);
graphDef.setUnitsExponent(exponent);
} else if (arg.equals("--units-exponent")) {
if (i + 1 < commandArray.length) {
int exponent = Integer.parseInt(commandArray[++i]);
LOG.debug("JRobin units exponent: {}", exponent);
graphDef.setUnitsExponent(exponent);
} else {
throw new IllegalArgumentException("--units-exponent must be followed by a number");
}
} else if (arg.startsWith("--lower-limit=")) {
String[] argParm = tokenize(arg, "=", true);
lowerLimit = Double.parseDouble(argParm[1]);
LOG.debug("JRobin lower limit: {}", lowerLimit);
} else if (arg.equals("--lower-limit")) {
if (i + 1 < commandArray.length) {
lowerLimit = Double.parseDouble(commandArray[++i]);
LOG.debug("JRobin lower limit: {}", lowerLimit);
} else {
throw new IllegalArgumentException("--lower-limit must be followed by a number");
}
} else if (arg.startsWith("--upper-limit=")) {
String[] argParm = tokenize(arg, "=", true);
upperLimit = Double.parseDouble(argParm[1]);
LOG.debug("JRobin upper limit: {}", upperLimit);
} else if (arg.equals("--upper-limit")) {
if (i + 1 < commandArray.length) {
upperLimit = Double.parseDouble(commandArray[++i]);
LOG.debug("JRobin upper limit: {}", upperLimit);
} else {
throw new IllegalArgumentException("--upper-limit must be followed by a number");
}
} else if (arg.startsWith("--base=")) {
String[] argParm = tokenize(arg, "=", true);
graphDef.setBase(Double.parseDouble(argParm[1]));
} else if (arg.equals("--base")) {
if (i + 1 < commandArray.length) {
graphDef.setBase(Double.parseDouble(commandArray[++i]));
} else {
throw new IllegalArgumentException("--base must be followed by a number");
}
} else if (arg.startsWith("--font=")) {
String[] argParm = tokenize(arg, "=", true);
processRrdFontArgument(graphDef, argParm[1]);
} else if (arg.equals("--font")) {
if (i + 1 < commandArray.length) {
processRrdFontArgument(graphDef, commandArray[++i]);
} else {
throw new IllegalArgumentException("--font must be followed by an argument");
}
} else if (arg.startsWith("--imgformat=")) {
String[] argParm = tokenize(arg, "=", true);
graphDef.setImageFormat(argParm[1]);
} else if (arg.equals("--imgformat")) {
if (i + 1 < commandArray.length) {
graphDef.setImageFormat(commandArray[++i]);
} else {
throw new IllegalArgumentException("--imgformat must be followed by an argument");
}
} else if (arg.equals("--rigid")) {
rigid = true;
} else if (arg.startsWith("DEF:")) {
String definition = arg.substring("DEF:".length());
String[] def = splitDef(definition);
String[] ds = def[0].split("=");
// LOG.debug("ds = {}", Arrays.toString(ds));
final String replaced = ds[1].replaceAll("\\\\(.)", "$1");
// LOG.debug("replaced = {}", replaced);
final File dsFile;
File rawPathFile = new File(replaced);
if (rawPathFile.isAbsolute()) {
dsFile = rawPathFile;
} else {
dsFile = new File(workDir, replaced);
}
// LOG.debug("dsFile = {}, ds[1] = {}", dsFile, ds[1]);
final String absolutePath = (File.separatorChar == '\\')? dsFile.getAbsolutePath().replace("\\", "\\\\") : dsFile.getAbsolutePath();
// LOG.debug("absolutePath = {}", absolutePath);
graphDef.datasource(ds[0], absolutePath, def[1], def[2]);
List<String> defBits = new ArrayList<String>();
defBits.add(absolutePath);
defBits.add(def[1]);
defBits.add(def[2]);
defs.put(ds[0], defBits);
} else if (arg.startsWith("CDEF:")) {
String definition = arg.substring("CDEF:".length());
String[] cdef = tokenize(definition, "=", true);
graphDef.datasource(cdef[0], cdef[1]);
List<String> cdefBits = new ArrayList<String>();
cdefBits.add(cdef[1]);
defs.put(cdef[0], cdefBits);
} else if (arg.startsWith("VDEF:")) {
String definition = arg.substring("VDEF:".length());
String[] vdef = tokenize(definition, "=", true);
String[] expressionTokens = tokenize(vdef[1], ",", false);
addVdefDs(graphDef, vdef[0], expressionTokens, start, end, defs);
} else if (arg.startsWith("LINE1:")) {
String definition = arg.substring("LINE1:".length());
String[] line1 = tokenize(definition, ":", true);
String[] color = tokenize(line1[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line1.length > 1 ? line1[1] : ""));
} else if (arg.startsWith("LINE2:")) {
String definition = arg.substring("LINE2:".length());
String[] line2 = tokenize(definition, ":", true);
String[] color = tokenize(line2[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line2.length > 1 ? line2[1] : ""), 2);
} else if (arg.startsWith("LINE3:")) {
String definition = arg.substring("LINE3:".length());
String[] line3 = tokenize(definition, ":", true);
String[] color = tokenize(line3[0], "#", true);
graphDef.line(color[0], getColorOrInvisible(color, 1), (line3.length > 1 ? line3[1] : ""), 3);
} else if (arg.startsWith("GPRINT:")) {
String definition = arg.substring("GPRINT:".length());
String[] gprint = tokenize(definition, ":", true);
String format = gprint[2];
//format = format.replaceAll("%(\\d*\\.\\d*)lf", "@$1");
//format = format.replaceAll("%s", "@s");
//format = format.replaceAll("%%", "%");
//LOG.debug("gprint: oldformat = {} newformat = {}", gprint[2], format);
format = format.replaceAll("\\n", "\\\\l");
graphDef.gprint(gprint[0], gprint[1], format);
} else if (arg.startsWith("PRINT:")) {
String definition = arg.substring("PRINT:".length());
String[] print = tokenize(definition, ":", true);
String format = print[2];
//format = format.replaceAll("%(\\d*\\.\\d*)lf", "@$1");
//format = format.replaceAll("%s", "@s");
//format = format.replaceAll("%%", "%");
//LOG.debug("gprint: oldformat = {} newformat = {}", print[2], format);
format = format.replaceAll("\\n", "\\\\l");
graphDef.print(print[0], print[1], format);
} else if (arg.startsWith("COMMENT:")) {
String[] comments = tokenize(arg, ":", true);
String format = comments[1].replaceAll("\\n", "\\\\l");
graphDef.comment(format);
} else if (arg.startsWith("AREA:")) {
String definition = arg.substring("AREA:".length());
String[] area = tokenize(definition, ":", true);
String[] color = tokenize(area[0], "#", true);
if (area.length > 1) {
graphDef.area(color[0], getColorOrInvisible(color, 1), area[1]);
} else {
graphDef.area(color[0], getColorOrInvisible(color, 1));
}
} else if (arg.startsWith("STACK:")) {
String definition = arg.substring("STACK:".length());
String[] stack = tokenize(definition, ":", true);
String[] color = tokenize(stack[0], "#", true);
graphDef.stack(color[0], getColor(color[1]), (stack.length > 1 ? stack[1] : ""));
} else if (arg.startsWith("HRULE:")) {
String definition = arg.substring("HRULE:".length());
String[] hrule = tokenize(definition, ":", true);
String[] color = tokenize(hrule[0], "#", true);
Double value = Double.valueOf(color[0]);
graphDef.hrule(value, getColor(color[1]), (hrule.length > 1 ? hrule[1] : ""));
} else if (arg.endsWith("/rrdtool") || arg.equals("graph") || arg.equals("-")) {
// ignore, this is just a leftover from the rrdtool-specific options
} else if (arg.trim().isEmpty()) {
// ignore empty whitespace arguments
} else {
LOG.warn("JRobin: Unrecognized graph argument: {}", arg);
}
}
graphDef.setTimeSpan(start, end);
graphDef.setMinValue(lowerLimit);
graphDef.setMaxValue(upperLimit);
graphDef.setRigid(rigid);
graphDef.setHeight(height);
graphDef.setWidth(width);
// graphDef.setSmallFont(new Font("Monospaced", Font.PLAIN, 10));
// graphDef.setLargeFont(new Font("Monospaced", Font.PLAIN, 12));
LOG.debug("JRobin Finished tokenizing checking: start time: {}, end time: {}", start, end);
LOG.debug("large font = {}, small font = {}", graphDef.getLargeFont(), graphDef.getSmallFont());
return graphDef;
}
private String[] splitDef(final String definition) {
// LOG.debug("splitDef({})", definition);
final String[] def;
if (File.separatorChar == '\\') {
// LOG.debug("windows");
// Windows, make sure the beginning isn't eg: C:\\foo\\bar
if (definition.matches("[^=]*=[a-zA-Z]:.*")) {
final String[] tempDef = definition.split("(?<!\\\\):");
def = new String[tempDef.length - 1];
def[0] = tempDef[0] + ':' + tempDef[1];
if (tempDef.length > 2) {
for (int i = 2; i < tempDef.length; i++) {
def[i-1] = tempDef[i];
}
}
} else {
// LOG.debug("no match");
def = definition.split("(?<!\\\\):");
}
} else {
def = definition.split("(?<!\\\\):");
}
// LOG.debug("returning: {}", Arrays.toString(def));
return def;
}
private void processRrdFontArgument(final RrdGraphDef graphDef, final String argParm) {
final String[] argValue = tokenize(argParm, ":", false);
if (argValue.length < 2) {
LOG.warn("Argument '{}' does not specify font size", argParm);
return;
}
if (argValue.length > 3) {
LOG.debug("Argument '{}' includes extra data, ignoring the extra data.", argParm);
}
float newPointSize = 0f;
try {
newPointSize = Integer.parseInt(argValue[1]) * 1.5f;
} catch (final NumberFormatException e) {
LOG.warn("Failed to parse {} as an integer: {}", argValue[1], e.getMessage(), e);
}
int fontTag;
Font font;
if (argValue[0].equals("DEFAULT")) {
fontTag = RrdGraphDef.FONTTAG_DEFAULT;
} else if (argValue[0].equals("TITLE")) {
fontTag = RrdGraphDef.FONTTAG_TITLE;
} else if (argValue[0].equals("AXIS")) {
fontTag = RrdGraphDef.FONTTAG_AXIS;
} else if (argValue[0].equals("UNIT")) {
fontTag = RrdGraphDef.FONTTAG_UNIT;
} else if (argValue[0].equals("LEGEND")) {
fontTag = RrdGraphDef.FONTTAG_LEGEND;
} else if (argValue[0].equals("WATERMARK")) {
fontTag = RrdGraphDef.FONTTAG_WATERMARK;
} else {
LOG.warn("invalid font tag {}", argValue[0]);
return;
}
try {
font = graphDef.getFont(fontTag);
// If we have a font specified, try to get a font object for it.
if (argValue.length == 3 && argValue[2] != null && argValue[2].length() > 0) {
final float origPointSize = font.getSize2D();
// Get our new font
font = Font.decode(argValue[2]);
// Font.decode() returns a 12 px font size, by default unless you specify
// a font size in the font name pattern.
if (newPointSize > 0) {
font = font.deriveFont(newPointSize);
} else {
font = font.deriveFont(origPointSize);
}
} else {
// If we don't have a font name specified, then we just adjust the font size.
font = font.deriveFont(newPointSize);
}
if (fontTag == RrdGraphDef.FONTTAG_DEFAULT) {
graphDef.setFont(fontTag, font, true, newPointSize == 0);
} else {
graphDef.setFont(fontTag, font);
}
} catch (final Throwable e) {
LOG.warn("unable to create font from font argument {}", argParm, e);
}
}
private String[] tokenize(final String line, final String delimiters, final boolean processQuotes) {
String passthroughTokens = "lcrjgsJ"; /* see org.jrobin.graph.RrdGraphConstants.MARKERS */
return tokenizeWithQuotingAndEscapes(line, delimiters, processQuotes, passthroughTokens);
}
private void parseGraphColor(final RrdGraphDef graphDef, final String colorArg) throws IllegalArgumentException {
// Parse for format COLORTAG#RRGGBB[AA]
String[] colorArgParts = tokenize(colorArg, "#", false);
if (colorArgParts.length != 2) {
throw new IllegalArgumentException("--color must be followed by value with format COLORTAG#RRGGBB[AA]");
}
String colorTag = colorArgParts[0].toUpperCase();
String colorHex = colorArgParts[1].toUpperCase();
// validate hex color input is actually an RGB hex color value
if (colorHex.length() != 6 && colorHex.length() != 8) {
throw new IllegalArgumentException("--color must be followed by value with format COLORTAG#RRGGBB[AA]");
}
// this might throw NumberFormatException, but whoever wrote
// createGraph didn't seem to care, so I guess I don't care either.
// It'll get wrapped in an RrdException anyway.
Color color = getColor(colorHex);
// These are the documented RRD color tags
try {
if (colorTag.equals("BACK")) {
graphDef.setColor("BACK", color);
}
else if (colorTag.equals("CANVAS")) {
graphDef.setColor("CANVAS", color);
}
else if (colorTag.equals("SHADEA")) {
graphDef.setColor("SHADEA", color);
}
else if (colorTag.equals("SHADEB")) {
graphDef.setColor("SHADEB", color);
}
else if (colorTag.equals("GRID")) {
graphDef.setColor("GRID", color);
}
else if (colorTag.equals("MGRID")) {
graphDef.setColor("MGRID", color);
}
else if (colorTag.equals("FONT")) {
graphDef.setColor("FONT", color);
}
else if (colorTag.equals("FRAME")) {
graphDef.setColor("FRAME", color);
}
else if (colorTag.equals("ARROW")) {
graphDef.setColor("ARROW", color);
}
else {
throw new org.jrobin.core.RrdException("Unknown color tag " + colorTag);
}
} catch (Throwable e) {
LOG.error("JRobin: exception occurred creating graph", e);
}
}
/**
* This implementation does not track any stats.
*
* @return a {@link java.lang.String} object.
*/
@Override
public String getStats() {
return "";
}
/*
* These offsets work for ranger@ with Safari and JRobin 1.5.8.
*/
/**
* <p>getGraphLeftOffset</p>
*
* @return a int.
*/
@Override
public int getGraphLeftOffset() {
return 74;
}
/**
* <p>getGraphRightOffset</p>
*
* @return a int.
*/
@Override
public int getGraphRightOffset() {
return -15;
}
/**
* <p>getGraphTopOffsetWithText</p>
*
* @return a int.
*/
@Override
public int getGraphTopOffsetWithText() {
return -61;
}
/**
* <p>getDefaultFileExtension</p>
*
* @return a {@link java.lang.String} object.
*/
@Override
public String getDefaultFileExtension() {
return ".jrb";
}
/**
* <p>tokenizeWithQuotingAndEscapes</p>
*
* @param line a {@link java.lang.String} object.
* @param delims a {@link java.lang.String} object.
* @param processQuoted a boolean.
* @return an array of {@link java.lang.String} objects.
*/
public static String[] tokenizeWithQuotingAndEscapes(String line, String delims, boolean processQuoted) {
return tokenizeWithQuotingAndEscapes(line, delims, processQuoted, "");
}
/**
* Tokenize a {@link String} into an array of {@link String}s.
*
* @param line
* the string to tokenize
* @param delims
* a string containing zero or more characters to treat as a delimiter
* @param processQuoted
* whether or not to process escaped values inside quotes
* @param tokens
* custom escaped tokens to pass through, escaped. For example, if tokens contains "lsg", then \l, \s, and \g
* will be passed through unescaped.
* @return an array of {@link java.lang.String} objects.
*/
public static String[] tokenizeWithQuotingAndEscapes(final String line, final String delims, final boolean processQuoted, final String tokens) {
List<String> tokenList = new LinkedList<String>();
StringBuffer currToken = new StringBuffer();
boolean quoting = false;
boolean escaping = false;
boolean debugTokens = Boolean.getBoolean("org.opennms.netmgt.rrd.debugTokens");
if (!LOG.isDebugEnabled())
debugTokens = false;
if (debugTokens)
LOG.debug("tokenize: line={}, delims={}", line, delims);
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (debugTokens)
LOG.debug("tokenize: checking char: {}", ch);
if (escaping) {
if (ch == 'n') {
currToken.append(escapeIfNotPathSepInDEF(ch, '\n', currToken));
} else if (ch == 'r') {
currToken.append(escapeIfNotPathSepInDEF(ch, '\r', currToken));
} else if (ch == 't') {
currToken.append(escapeIfNotPathSepInDEF(ch, '\t', currToken));
} else {
if (tokens.indexOf(ch) >= 0) {
currToken.append('\\').append(ch);
} else if (currToken.toString().startsWith("DEF:")) {
currToken.append('\\').append(ch);
} else {
// silently pass through the character *without* the \ in front of it
currToken.append(ch);
}
}
escaping = false;
if (debugTokens)
LOG.debug("tokenize: escaped. appended to {}", currToken);
} else if (ch == '\\') {
if (debugTokens)
LOG.debug("tokenize: found a backslash... escaping currToken = {}", currToken);
if (quoting && !processQuoted)
currToken.append(ch);
else
escaping = true;
} else if (ch == '\"') {
if (!processQuoted)
currToken.append(ch);
if (quoting) {
if (debugTokens)
LOG.debug("tokenize: found a quote ending quotation currToken = {}", currToken);
quoting = false;
} else {
if (debugTokens)
LOG.debug("tokenize: found a quote beginning quotation currToken = {}", currToken);
quoting = true;
}
} else if (!quoting && delims.indexOf(ch) >= 0) {
if (debugTokens)
LOG.debug("tokenize: found a token: {} ending token [{}] and starting a new one", ch, currToken);
tokenList.add(currToken.toString());
currToken = new StringBuffer();
} else {
if (debugTokens)
LOG.debug("tokenize: appending {} to token: {}", ch, currToken);
currToken.append(ch);
}
}
if (escaping || quoting) {
if (debugTokens)
LOG.debug("tokenize: ended string but escaping = {} and quoting = {}", escaping, quoting);
throw new IllegalArgumentException("unable to tokenize string " + line + " with token chars " + delims);
}
if (debugTokens)
LOG.debug("tokenize: reached end of string. completing token {}", currToken);
tokenList.add(currToken.toString());
return (String[]) tokenList.toArray(new String[tokenList.size()]);
}
/**
* <p>escapeIfNotPathSepInDEF</p>
*
* @param encountered a char.
* @param escaped a char.
* @param currToken a {@link java.lang.StringBuffer} object.
* @return an array of char.
*/
public static char[] escapeIfNotPathSepInDEF(final char encountered, final char escaped, final StringBuffer currToken) {
if ( ('\\' != File.separatorChar) || (! currToken.toString().startsWith("DEF:")) ) {
return new char[] { escaped };
} else {
return new char[] { '\\', encountered };
}
}
protected void addVdefDs(RrdGraphDef graphDef, String sourceName, String[] rhs, double start, double end, Map<String,List<String>> defs) throws RrdException {
if (rhs.length == 2) {
graphDef.datasource(sourceName, rhs[0], rhs[1]);
} else if (rhs.length == 3 && "PERCENT".equals(rhs[2])) {
// Is there a better way to do this than with a separate DataProcessor?
final double pctRank = Double.valueOf(rhs[1]);
final DataProcessor dataProcessor = new DataProcessor((int)start, (int)end);
for (final Entry<String, List<String>> entry : defs.entrySet()) {
final String dsName = entry.getKey();
final List<String> thisDef = entry.getValue();
if (thisDef.size() == 3) {
dataProcessor.addDatasource(dsName, thisDef.get(0), thisDef.get(1), thisDef.get(2));
} else if (thisDef.size() == 1) {
dataProcessor.addDatasource(dsName, thisDef.get(0));
}
}
try {
dataProcessor.processData();
} catch (IOException e) {
throw new RrdException("Caught IOException: " + e.getMessage());
}
double result = dataProcessor.getPercentile(rhs[0], pctRank);
ConstantStaticDef csDef = new ConstantStaticDef((long)start, (long)end, result);
graphDef.datasource(sourceName, csDef);
}
}
} |
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2006 Apr 27: Added support for pathOutageEnabled
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.poller.remote.support;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.core.utils.TimeKeeper;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.PollerConfig;
import org.opennms.netmgt.config.poller.Package;
import org.opennms.netmgt.config.poller.Parameter;
import org.opennms.netmgt.config.poller.Service;
import org.opennms.netmgt.dao.LocationMonitorDao;
import org.opennms.netmgt.dao.MonitoredServiceDao;
import org.opennms.netmgt.eventd.EventIpcManager;
import org.opennms.netmgt.model.OnmsLocationMonitor;
import org.opennms.netmgt.model.OnmsLocationSpecificStatus;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.netmgt.model.OnmsMonitoringLocationDefinition;
import org.opennms.netmgt.model.PollStatus;
import org.opennms.netmgt.model.ServiceSelector;
import org.opennms.netmgt.model.OnmsLocationMonitor.MonitorStatus;
import org.opennms.netmgt.poller.DistributionContext;
import org.opennms.netmgt.poller.ServiceMonitorLocator;
import org.opennms.netmgt.poller.remote.OnmsPollModel;
import org.opennms.netmgt.poller.remote.PolledService;
import org.opennms.netmgt.poller.remote.PollerBackEnd;
import org.opennms.netmgt.poller.remote.PollerConfiguration;
import org.opennms.netmgt.utils.EventBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.util.Assert;
/**
*
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
*
*/
public class DefaultPollerBackEnd implements PollerBackEnd, InitializingBean {
private LocationMonitorDao m_locMonDao;
private MonitoredServiceDao m_monSvcDao;
private EventIpcManager m_eventIpcManager;
private PollerConfig m_pollerConfig;
private TimeKeeper m_timeKeeper;
private int m_unresponsiveTimeout;
private Date m_configurationTimestamp = null;
public Collection<OnmsMonitoringLocationDefinition> getMonitoringLocations() {
return m_locMonDao.findAllMonitoringLocationDefinitions();
}
public PollerConfiguration getPollerConfiguration(int locationMonitorId) {
OnmsLocationMonitor mon = m_locMonDao.get(locationMonitorId);
Package pkg = getPollingPackageForMonitor(mon);
ServiceSelector selector = m_pollerConfig.getServiceSelectorForPackage(pkg);
Collection<OnmsMonitoredService> services = m_monSvcDao.findMatchingServices(selector);
List<PolledService> configs = new ArrayList<PolledService>(services.size());
for (OnmsMonitoredService monSvc : services) {
Service serviceConfig = m_pollerConfig.getServiceInPackage(monSvc.getServiceName(), pkg);
long interval = serviceConfig.getInterval();
Map parameters = getParameterMap(serviceConfig);
configs.add(new PolledService(monSvc, parameters, new OnmsPollModel(interval)));
}
PolledService[] polledSvcs = (PolledService[]) configs.toArray(new PolledService[configs.size()]);
return new SimplePollerConfiguration(getConfigurationTimestamp(), polledSvcs);
}
private Package getPollingPackageForMonitor(OnmsLocationMonitor mon) {
OnmsMonitoringLocationDefinition def = m_locMonDao.findMonitoringLocationDefinition(mon.getDefinitionName());
if (def == null) {
throw new IllegalStateException("Location definition '" + mon.getDefinitionName() + "' could not be found for location monitor ID " + mon.getId());
}
String pollingPackageName = def.getPollingPackageName();
Package pkg = m_pollerConfig.getPackage(pollingPackageName);
if (pkg == null) {
throw new IllegalStateException("Package "+pollingPackageName+" does not exist as defined for monitoring location "+mon.getDefinitionName());
}
return pkg;
}
private static class SimplePollerConfiguration implements PollerConfiguration, Serializable {
private static final long serialVersionUID = 1L;
private Date m_timestamp;
private PolledService[] m_polledServices;
SimplePollerConfiguration(Date timestamp, PolledService[] polledSvcs) {
m_timestamp = timestamp;
m_polledServices = polledSvcs;
}
public Date getConfigurationTimestamp() {
return m_timestamp;
}
public PolledService[] getPolledServices() {
return m_polledServices;
}
}
@SuppressWarnings("unchecked")
private Map getParameterMap(Service serviceConfig) {
Map<String, String> paramMap = new HashMap<String, String>();
Enumeration<Parameter> serviceParms = serviceConfig.enumerateParameter();
while(serviceParms.hasMoreElements()) {
Parameter serviceParm = serviceParms.nextElement();
paramMap.put(serviceParm.getKey(), serviceParm.getValue());
}
return paramMap;
}
public boolean pollerCheckingIn(int locationMonitorId, Date currentConfigurationVersion) {
OnmsLocationMonitor mon = m_locMonDao.get(locationMonitorId);
if (mon == null) {
return false;
}
MonitorStatus oldStatus = mon.getStatus();
mon.setStatus(MonitorStatus.STARTED);
mon.setLastCheckInTime(m_timeKeeper.getCurrentDate());
m_locMonDao.update(mon);
if (MonitorStatus.UNRESPONSIVE.equals(oldStatus)) {
// the monitor has reconnected!
EventBuilder eventBuilder = createEventBuilder(locationMonitorId, EventConstants.LOCATION_MONITOR_RECONNECTED_UEI);
m_eventIpcManager.sendNow(eventBuilder.getEvent());
}
return m_configurationTimestamp.after(currentConfigurationVersion);
}
public boolean pollerStarting(int locationMonitorId, Map<String, String> pollerDetails) {
OnmsLocationMonitor mon = m_locMonDao.get(locationMonitorId);
if (mon == null) {
return false;
}
mon.setStatus(MonitorStatus.STARTED);
mon.setLastCheckInTime(m_timeKeeper.getCurrentDate());
mon.setDetails(pollerDetails);
m_locMonDao.update(mon);
EventBuilder eventBuilder = createEventBuilder(locationMonitorId, EventConstants.LOCATION_MONITOR_STARTED_UEI);
m_eventIpcManager.sendNow(eventBuilder.getEvent());
return true;
}
private EventBuilder createEventBuilder(int locationMonitorId, String uei) {
EventBuilder eventBuilder = new EventBuilder(uei, "PollerBackEnd")
.addParam(EventConstants.PARM_LOCATION_MONITOR_ID, locationMonitorId);
return eventBuilder;
}
public void pollerStopping(int locationMonitorId) {
System.err.println("Looking up monitor "+locationMonitorId);
OnmsLocationMonitor mon = m_locMonDao.get(locationMonitorId);
System.err.println("Found monitor "+mon);
mon.setStatus(MonitorStatus.STOPPED);
mon.setLastCheckInTime(m_timeKeeper.getCurrentDate());
m_locMonDao.update(mon);
EventBuilder eventBuilder = createEventBuilder(locationMonitorId, EventConstants.LOCATION_MONITOR_STOPPED_UEI);
m_eventIpcManager.sendNow(eventBuilder.getEvent());
}
public int registerLocationMonitor(String monitoringLocationId) {
OnmsMonitoringLocationDefinition def = m_locMonDao.findMonitoringLocationDefinition(monitoringLocationId);
if (def == null) {
throw new ObjectRetrievalFailureException(OnmsMonitoringLocationDefinition.class, monitoringLocationId, "Location monitor definition with the id '" + monitoringLocationId + "' not found", null);
}
OnmsLocationMonitor mon = new OnmsLocationMonitor();
mon.setDefinitionName(def.getName());
mon.setStatus(MonitorStatus.REGISTERED);
m_locMonDao.save(mon);
return mon.getId();
}
public String getMonitorName(int locationMonitorId) {
OnmsLocationMonitor locationMonitor = m_locMonDao.get(locationMonitorId);
return locationMonitor.getName();
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(m_locMonDao, "The LocationMonitorDao must be set");
Assert.notNull(m_monSvcDao, "The MonitoredServiceDao must be set");
Assert.notNull(m_pollerConfig, "The PollerConfig must be set");
Assert.notNull(m_timeKeeper, "The timeKeeper must be set");
Assert.notNull(m_eventIpcManager, "The eventIpcManager must be set");
Assert.state(m_unresponsiveTimeout > 0, "the unresponsiveTimeout property must be set");
m_configurationTimestamp = m_timeKeeper.getCurrentDate();
}
public void setLocationMonitorDao(LocationMonitorDao locMonDao) {
m_locMonDao = locMonDao;
}
public void setMonitoredServiceDao(MonitoredServiceDao monSvcDao) {
m_monSvcDao = monSvcDao;
}
public void setPollerConfig(PollerConfig pollerConfig) {
m_pollerConfig = pollerConfig;
}
public void setEventIpcManager(EventIpcManager eventIpcManager) {
m_eventIpcManager = eventIpcManager;
}
public void reportResult(int locationMonitorID, int serviceId, PollStatus pollResult) {
OnmsLocationMonitor locationMonitor = m_locMonDao.get(locationMonitorID);
OnmsMonitoredService monSvc = m_monSvcDao.get(serviceId);
OnmsLocationSpecificStatus newStatus = new OnmsLocationSpecificStatus(locationMonitor, monSvc, pollResult);
if (newStatus.getPollResult().getResponseTime() >= 0) {
Package pkg = getPollingPackageForMonitor(locationMonitor);
m_pollerConfig.saveResponseTimeData(Integer.toString(locationMonitorID), monSvc, newStatus.getPollResult().getResponseTime(), pkg);
}
OnmsLocationSpecificStatus currentStatus = m_locMonDao.getMostRecentStatusChange(locationMonitor, monSvc);
processStatusChange(currentStatus, newStatus);
}
private void processStatusChange(OnmsLocationSpecificStatus currentStatus, OnmsLocationSpecificStatus newStatus) {
if (databaseStatusChanged(currentStatus, newStatus)) {
m_locMonDao.saveStatusChange(newStatus);
PollStatus pollResult = newStatus.getPollResult();
// if we don't know the current status only send an event if it is not up
if (logicalStatusChanged(currentStatus, newStatus)) {
String uei = pollResult.isAvailable()
? EventConstants.REMOTE_NODE_REGAINED_SERVICE_UEI
: EventConstants.REMOTE_NODE_LOST_SERVICE_UEI;
EventBuilder builder = createEventBuilder(newStatus.getLocationMonitor().getId(), uei)
.setMonitoredService(newStatus.getMonitoredService());
if (!pollResult.isAvailable() && pollResult.getReason() != null) {
builder.addParam(EventConstants.PARM_LOSTSERVICE_REASON, pollResult.getReason());
}
m_eventIpcManager.sendNow(builder.getEvent());
}
}
}
private boolean logicalStatusChanged(OnmsLocationSpecificStatus currentStatus, OnmsLocationSpecificStatus newStatus) {
return currentStatus != null || (currentStatus == null && !newStatus.getPollResult().isAvailable());
}
private boolean databaseStatusChanged(OnmsLocationSpecificStatus currentStatus, OnmsLocationSpecificStatus newStatus) {
return currentStatus == null || !currentStatus.getPollResult().equals(newStatus.getPollResult());
}
public void setTimeKeeper(TimeKeeper timeKeeper) {
m_timeKeeper = timeKeeper;
}
public void checkforUnresponsiveMonitors() {
log().debug("Checking for Unresponsive monitors: UnresponsiveTimeout = "+m_unresponsiveTimeout);
Date now = m_timeKeeper.getCurrentDate();
Date earliestAcceptable = new Date(now.getTime() - m_unresponsiveTimeout);
Collection<OnmsLocationMonitor> monitors = m_locMonDao.findAll();
log().debug("Found "+monitors.size()+" monitors");
for (OnmsLocationMonitor monitor : monitors) {
if (monitor.getStatus() == MonitorStatus.STARTED && monitor.getLastCheckInTime().before(earliestAcceptable)) {
log().debug("Monitor "+monitor.getName()+" has stopped responding");
monitor.setStatus(MonitorStatus.UNRESPONSIVE);
m_locMonDao.update(monitor);
EventBuilder eventBuilder = createEventBuilder(monitor.getId(), EventConstants.LOCATION_MONITOR_DISCONNECTED_UEI);
m_eventIpcManager.sendNow(eventBuilder.getEvent());
} else {
log().debug("Monitor "+monitor.getName()+"("+monitor.getStatus()+") last responded at "+monitor.getLastCheckInTime());
}
}
}
private Category log() {
return ThreadCategory.getInstance(getClass());
}
public void setUnresponsiveTimeout(int unresponsiveTimeout) {
m_unresponsiveTimeout = unresponsiveTimeout;
}
private Date getConfigurationTimestamp() {
return m_configurationTimestamp;
}
public void configurationUpdated() {
m_configurationTimestamp = m_timeKeeper.getCurrentDate();
}
public Collection<ServiceMonitorLocator> getServiceMonitorLocators(DistributionContext context) {
return m_pollerConfig.getServiceMonitorLocators(context);
}
} |
package org.eclipse.emf.emfstore.client.model.util;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.emfstore.client.model.Activator;
import org.eclipse.emf.emfstore.client.model.WorkspaceManager;
import org.eclipse.emf.emfstore.client.model.observers.ExceptionObserver;
/**
* Workspace utility class.
*
* @author koegel
*/
public final class WorkspaceUtil {
/**
* Private constructor.
*/
private WorkspaceUtil() {
// nothing to do
}
/**
* Log an exception to the error log.
*
* @param message the message
* @param e the exception
*/
public static void logException(String message, Exception e) {
log(message, e, IStatus.ERROR);
}
/**
* Log a warning to the error log.
*
* @param message the message
* @param e the exception
*/
public static void logWarning(String message, Exception e) {
log(message, e, IStatus.WARNING);
}
/**
* Log a warning to the error log.
*
* @param message the message
* @param exception the exception or null f not applicable
* @param statusInt the status constant as defined in {@link IStatus}
*/
public static void log(String message, Exception exception, int statusInt) {
Activator activator = Activator.getDefault();
Status status = new Status(statusInt, activator.getBundle().getSymbolicName(), statusInt, message, exception);
activator.getLog().log(status);
}
/**
* Handles the given exception by wrapping it in a {@link RuntimeException} and propagating it to all registered
* exception handlers. If no exception handler did handle the exception
* a the wrapped exception will be re-thrown.
*
* @param errorMessage
* the error message that should be used for propagating the exception
* @param exception
* the actual exception
*/
public static void handleException(String errorMessage, Exception exception) {
RuntimeException runtimeException = new RuntimeException(exception);
Boolean errorHandeled = WorkspaceManager.getObserverBus().notify(ExceptionObserver.class)
.handleError(runtimeException);
logException("An error occured.", exception);
if (!errorHandeled.booleanValue()) {
throw runtimeException;
}
}
} |
package org.eclipse.mylyn.internal.context.ui;
import org.eclipse.mylyn.internal.context.ui.actions.FocusOutlineAction;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
/**
* @author Mik Kersten
*/
public class ContentOutlineManager implements IPartListener {
public void partBroughtToTop(final IWorkbenchPart part) {
// use the display async due to bug 261977: [context] outline view does not filter contents when new editor is opened
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (part instanceof IEditorPart) {
IEditorPart editorPart = (IEditorPart) part;
FocusOutlineAction applyAction = FocusOutlineAction.getOutlineActionForEditor(editorPart);
if (applyAction != null) {
applyAction.update(editorPart);
}
}
}
});
}
public void partActivated(IWorkbenchPart part) {
// ignore
}
public void partOpened(IWorkbenchPart part) {
// ignore
}
public void partClosed(IWorkbenchPart partRef) {
// ignore
}
public void partDeactivated(IWorkbenchPart partRef) {
// ignore
}
} |
package org.eclipse.mylyn.resources.ui;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.ui.AbstractAutoFocusViewAction;
import org.eclipse.mylyn.context.ui.InterestFilter;
import org.eclipse.mylyn.internal.context.ui.ContextUiPlugin;
import org.eclipse.mylyn.internal.resources.ui.ResourcesUiBridgePlugin;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.internal.navigator.NavigatorContentService;
import org.eclipse.ui.internal.navigator.actions.LinkEditorAction;
import org.eclipse.ui.internal.navigator.filters.CommonFilterDescriptor;
import org.eclipse.ui.internal.navigator.filters.CommonFilterDescriptorManager;
import org.eclipse.ui.internal.navigator.filters.CoreExpressionFilter;
import org.eclipse.ui.internal.navigator.filters.SelectFiltersAction;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.ILinkHelper;
/**
* @author Mik Kersten
* @since 3.0
*/
public abstract class FocusCommonNavigatorAction extends AbstractAutoFocusViewAction {
private Object linkService;
private Method linkServiceMethod;
private boolean resolveFailed;
private CommonNavigator commonNavigator;
private CommonFilterDescriptor[] filterDescriptors;
private Field filterExpressionField1;
private Field filterExpressionField2;
public FocusCommonNavigatorAction(InterestFilter interestFilter, boolean manageViewer, boolean manageFilters,
boolean manageLinking) {
super(interestFilter, manageViewer, manageFilters, manageLinking);
}
@Override
protected boolean installInterestFilter(StructuredViewer viewer) {
if (commonNavigator == null) {
commonNavigator = (CommonNavigator) super.getPartForAction();
}
try {
// XXX: reflection
Class<?> clazz2 = CoreExpressionFilter.class;
filterExpressionField1 = clazz2.getDeclaredField("filterExpression"); //$NON-NLS-1$
filterExpressionField1.setAccessible(true);
Class<?> clazz1 = CommonFilterDescriptor.class;
filterExpressionField2 = clazz1.getDeclaredField("filterExpression"); //$NON-NLS-1$
filterExpressionField2.setAccessible(true);
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ResourcesUiBridgePlugin.ID_PLUGIN,
"Could not determine filter", e)); //$NON-NLS-1$
}
filterDescriptors = CommonFilterDescriptorManager.getInstance().findVisibleFilters(
commonNavigator.getNavigatorContentService());
return super.installInterestFilter(viewer);
}
@Override
protected ISelection resolveSelection(IEditorPart editor, ITextSelection changedSelection, StructuredViewer viewer)
throws CoreException {
if (resolveFailed) {
return null;
}
if (linkServiceMethod == null) {
// TODO e3.5 replace with call to CommonNavigator.getLinkHelperService()
try {
try {
// e3.5: get helper from common navigator
Method method = CommonNavigator.class.getDeclaredMethod("getLinkHelperService"); //$NON-NLS-1$
method.setAccessible(true);
linkService = method.invoke(commonNavigator);
} catch (NoSuchMethodException e) {
// e3.3, e3.4: instantiate helper
Class<?> clazz = Class.forName("org.eclipse.ui.internal.navigator.extensions.LinkHelperService"); //$NON-NLS-1$
Constructor<?> constructor = clazz.getConstructor(NavigatorContentService.class);
linkService = constructor.newInstance((NavigatorContentService) commonNavigator.getCommonViewer()
.getNavigatorContentService());
}
linkServiceMethod = linkService.getClass().getDeclaredMethod("getLinkHelpersFor", IEditorInput.class); //$NON-NLS-1$
} catch (Throwable e) {
resolveFailed = true;
StatusHandler.log(new Status(IStatus.ERROR, ResourcesUiBridgePlugin.ID_PLUGIN,
"Initialization of LinkHelperService failed", e)); //$NON-NLS-1$
}
}
IEditorInput input = editor.getEditorInput();
// TODO e3.5 replace with call to linkService.getLinkHelpersFor(editor.getEditorInput());
ILinkHelper[] helpers;
try {
helpers = (ILinkHelper[]) linkServiceMethod.invoke(linkService, editor.getEditorInput());
} catch (Exception e) {
return null;
}
IStructuredSelection selection = StructuredSelection.EMPTY;
IStructuredSelection newSelection = StructuredSelection.EMPTY;
for (ILinkHelper helper : helpers) {
selection = helper.findSelection(input);
if (selection != null && !selection.isEmpty()) {
newSelection = mergeSelection(newSelection, selection);
}
}
if (!newSelection.isEmpty()) {
return newSelection;
}
return null;
}
@Override
protected void select(StructuredViewer viewer, ISelection toSelect) {
if (commonNavigator == null) {
commonNavigator = (CommonNavigator) super.getPartForAction();
}
if (commonNavigator != null) {
commonNavigator.selectReveal(toSelect);
}
}
// TODO: should have better way of doing this
@Override
protected void setManualFilteringAndLinkingEnabled(boolean on) {
IViewPart part = super.getPartForAction();
if (part instanceof CommonNavigator) {
for (IContributionItem item : ((CommonNavigator) part).getViewSite()
.getActionBars()
.getToolBarManager()
.getItems()) {
if (item instanceof ActionContributionItem) {
ActionContributionItem actionItem = (ActionContributionItem) item;
if (actionItem.getAction() instanceof LinkEditorAction) {
actionItem.getAction().setEnabled(on);
}
}
}
for (IContributionItem item : ((CommonNavigator) part).getViewSite()
.getActionBars()
.getMenuManager()
.getItems()) {
if (item instanceof ActionContributionItem) {
ActionContributionItem actionItem = (ActionContributionItem) item;
if (actionItem.getAction() instanceof SelectFiltersAction) {
actionItem.getAction().setEnabled(on);
}
}
}
}
}
@Override
protected void setDefaultLinkingEnabled(boolean on) {
IViewPart part = super.getPartForAction();
if (part instanceof CommonNavigator) {
((CommonNavigator) part).setLinkingEnabled(on);
}
}
@Override
protected boolean isDefaultLinkingEnabled() {
IViewPart part = super.getPartForAction();
if (part instanceof CommonNavigator) {
return ((CommonNavigator) part).isLinkingEnabled();
}
return false;
}
@Override
protected boolean isPreservedFilter(ViewerFilter filter) {
if (filter instanceof CoreExpressionFilter) {
CoreExpressionFilter expressionFilter = (CoreExpressionFilter) filter;
Set<String> preservedIds = ContextUiPlugin.getDefault().getPreservedFilterIds(viewPart.getSite().getId());
if (!preservedIds.isEmpty()) {
try {
Expression expression2 = (Expression) filterExpressionField1.get(expressionFilter);
for (CommonFilterDescriptor commonFilterDescriptor : filterDescriptors) {
if (preservedIds.contains(commonFilterDescriptor.getId())) {
Expression expression1 = (Expression) filterExpressionField2.get(commonFilterDescriptor);
if (expression1 != null && expression1.equals(expression2)) {
return true;
}
}
}
} catch (IllegalArgumentException e) {
StatusHandler.log(new Status(IStatus.ERROR, ResourcesUiBridgePlugin.ID_PLUGIN,
"Could not determine filter", e)); //$NON-NLS-1$
} catch (IllegalAccessException e) {
StatusHandler.log(new Status(IStatus.ERROR, ResourcesUiBridgePlugin.ID_PLUGIN,
"Could not determine filter", e)); //$NON-NLS-1$
}
}
}
return false;
}
/**
* Copied from
*
* @{link LinkEditorAction}
*/
@SuppressWarnings("unchecked")
private IStructuredSelection mergeSelection(IStructuredSelection aBase, IStructuredSelection aSelectionToAppend) {
if (aBase == null || aBase.isEmpty()) {
return (aSelectionToAppend != null) ? aSelectionToAppend : StructuredSelection.EMPTY;
} else if (aSelectionToAppend == null || aSelectionToAppend.isEmpty()) {
return aBase;
} else {
List newItems = new ArrayList(aBase.toList());
newItems.addAll(aSelectionToAppend.toList());
return new StructuredSelection(newItems);
}
}
} |
package org.eclipse.scanning.sequencer.nexus;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.dawnsci.nexus.INexusDevice;
import org.eclipse.dawnsci.nexus.NXdata;
import org.eclipse.dawnsci.nexus.NXentry;
import org.eclipse.dawnsci.nexus.NXobject;
import org.eclipse.dawnsci.nexus.NexusBaseClass;
import org.eclipse.dawnsci.nexus.NexusException;
import org.eclipse.dawnsci.nexus.NexusScanInfo;
import org.eclipse.dawnsci.nexus.NexusScanInfo.ScanRole;
import org.eclipse.dawnsci.nexus.builder.CustomNexusEntryModification;
import org.eclipse.dawnsci.nexus.builder.NexusEntryBuilder;
import org.eclipse.dawnsci.nexus.builder.NexusFileBuilder;
import org.eclipse.dawnsci.nexus.builder.NexusObjectProvider;
import org.eclipse.dawnsci.nexus.builder.NexusScanFile;
import org.eclipse.dawnsci.nexus.builder.data.AxisDataDevice;
import org.eclipse.dawnsci.nexus.builder.data.DataDevice;
import org.eclipse.dawnsci.nexus.builder.data.DataDeviceBuilder;
import org.eclipse.dawnsci.nexus.builder.data.NexusDataBuilder;
import org.eclipse.dawnsci.nexus.builder.data.PrimaryDataDevice;
import org.eclipse.dawnsci.nexus.builder.impl.MapBasedMetadataProvider;
import org.eclipse.scanning.api.INameable;
import org.eclipse.scanning.api.IScannable;
import org.eclipse.scanning.api.MonitorRole;
import org.eclipse.scanning.api.device.AbstractRunnableDevice;
import org.eclipse.scanning.api.device.IScannableDeviceService;
import org.eclipse.scanning.api.points.AbstractPosition;
import org.eclipse.scanning.api.points.IDeviceDependentIterable;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.scan.ScanningException;
import org.eclipse.scanning.api.scan.models.ScanDataModel;
import org.eclipse.scanning.api.scan.models.ScanDeviceModel;
import org.eclipse.scanning.api.scan.models.ScanDeviceModel.ScanFieldModel;
import org.eclipse.scanning.api.scan.models.ScanMetadata;
import org.eclipse.scanning.api.scan.models.ScanMetadata.MetadataType;
import org.eclipse.scanning.api.scan.models.ScanModel;
import org.eclipse.scanning.sequencer.ServiceHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builds and manages the NeXus file for a scan given a {@link ScanModel}.
*/
public class NexusScanFileManager implements INexusScanFileManager {
private static final Logger logger = LoggerFactory.getLogger(NexusScanFileManager.class);
private final AbstractRunnableDevice<ScanModel> scanDevice;
private ScanModel model;
private NexusScanInfo scanInfo;
private NexusFileBuilder fileBuilder;
private NexusScanFile nexusScanFile;
private SolsticeScanMonitor solsticeScanMonitor;
// we need to cache various things as they are used more than once
/**
* A list of the nexus devices for each category of device.
*/
private Map<ScanRole, Collection<INexusDevice<?>>> nexusDevices = null;
/**
* A list of the nexus object providers for each category of device.
*/
private Map<ScanRole, List<NexusObjectProvider<?>>> nexusObjectProviders = null;
/**
* A map from nexus object provider to the axis data device for that.
* This is used for devices added to an NXdata group other than the primary device
* (the one that supplies the signal field.)
*/
private Map<NexusObjectProvider<?>, AxisDataDevice<?>> dataDevices = new HashMap<>();
/**
* A map from scannable name to the index of the scan for that scannable,
* or <code>null</code> if none
*/
private Map<String, Integer> defaultAxisIndexForScannable = null;
public NexusScanFileManager(AbstractRunnableDevice<ScanModel> scanDevice) {
this.scanDevice = scanDevice;
}
/**
* Creates the nexus file for the given {@link ScanModel}.
* The structure of the nexus file is determined by model and the
* devices that the model references - these are retrieved from the
* {@link IScannableDeviceService}.
*
* @param model model of scan
* @throws ScanningException
*/
public void configure(ScanModel model) throws ScanningException {
if (fileBuilder != null) {
throw new IllegalStateException("The nexus file has already been created");
}
this.model = model;
final List<String> scannableNames = getScannableNames(model.getPositionIterable());
setMetadataScannables(model, scannableNames);
this.scanInfo = createScanInfo(model, scannableNames);
// create the scan points writer and add it to the scan as a monitor
solsticeScanMonitor = createSolsticeScanMonitor(model);
nexusDevices = extractNexusDevices(model);
// convert this to a map of nexus object providers for each type
nexusObjectProviders = extractNexusProviders();
solsticeScanMonitor.setNexusObjectProviders(nexusObjectProviders);
}
/**
*
* @return the paths of all the external files to which we will be writing.
*/
public Set<String> getExternalFilePaths() {
Set<String> paths = new HashSet<>();
// Big looking loop over small number of things.
for (List<NexusObjectProvider<?>> provList : nexusObjectProviders.values()) {
for (NexusObjectProvider<?> prov : provList) {
paths.addAll(prov.getExternalFileNames());
}
}
return paths;
}
public String createNexusFile(boolean async) throws ScanningException {
// We use the new nexus framework to join everything up into the scan
// Create a builder
fileBuilder = ServiceHolder.getFactory().newNexusFileBuilder(model.getFilePath());
try {
createEntry(fileBuilder);
// create the file from the builder and open it
nexusScanFile = fileBuilder.createFile(async);
nexusScanFile.openToWrite();
return model.getFilePath();
} catch (NexusException e) {
throw new ScanningException("Cannot create nexus file", e);
}
}
/**
* Flushes the wrapped nexus file.
* @throws ScanningException if the nexus file could not be flushed for any reason
*/
public void flushNexusFile() throws ScanningException {
try {
int code = nexusScanFile.flush();
if (code < 0) {
logger.warn("Problem flushing during scan! Flush code is "+code);
}
} catch (NexusException e) {
throw new ScanningException("Cannot create nexus file", e);
}
}
/**
* Writes scan finished and closes the wrapped nexus file.
* @throws ScanningException
*/
public void scanFinished() throws ScanningException {
solsticeScanMonitor.scanFinished();
try {
nexusScanFile.close();
} catch (NexusException e) {
throw new ScanningException("Could not close nexus file", e);
}
}
public boolean isNexusWritingEnabled() {
return true;
}
public NexusScanInfo getNexusScanInfo() {
return scanInfo;
}
protected Map<ScanRole, Collection<INexusDevice<?>>> extractNexusDevices(ScanModel model) throws ScanningException {
final IPosition firstPosition = model.getPositionIterable().iterator().next();
final Collection<String> scannableNames = firstPosition.getNames();
Map<ScanRole, Collection<INexusDevice<?>>> nexusDevices = new EnumMap<>(ScanRole.class);
nexusDevices.put(ScanRole.DETECTOR, getNexusDevices(model.getDetectors()));
nexusDevices.put(ScanRole.SCANNABLE, getNexusScannables(scannableNames));
if (model.getMonitors()!=null) {
Collection<IScannable<?>> perPoint = model.getMonitors().stream().filter(scannable -> scannable.getMonitorRole()==MonitorRole.PER_POINT).collect(Collectors.toList());
Collection<IScannable<?>> perScan = model.getMonitors().stream().filter(scannable -> scannable.getMonitorRole()==MonitorRole.PER_SCAN).collect(Collectors.toList());
nexusDevices.put(ScanRole.MONITOR, getNexusDevices(perPoint));
nexusDevices.put(ScanRole.METADATA, getNexusDevices(perScan));
}
return nexusDevices;
}
protected Map<ScanRole, List<NexusObjectProvider<?>>> extractNexusProviders() throws ScanningException {
Map<ScanRole, List<NexusObjectProvider<?>>> nexusObjectProviders = new EnumMap<>(ScanRole.class);
for (ScanRole deviceType: ScanRole.values()) {
final Collection<INexusDevice<?>> nexusDevicesForType = nexusDevices.get(deviceType);
final List<NexusObjectProvider<?>> nexusObjectProvidersForType =
new ArrayList<>(nexusDevicesForType.size());
for (INexusDevice<?> nexusDevice : nexusDevicesForType) {
try {
NexusObjectProvider<?> nexusProvider = nexusDevice.getNexusProvider(scanInfo);
if (nexusProvider != null) {
nexusObjectProvidersForType.add(nexusProvider);
}
} catch (NexusException e) {
throw new ScanningException("Cannot create device: " + e);
}
}
nexusObjectProviders.put(deviceType, nexusObjectProvidersForType);
}
return nexusObjectProviders;
}
/**
* Augments the set of metadata scannables in the model with: <ul>
* <li>any scannables from the legacy spring configuration;</li>
* <li>the required scannables of any scannables in the scan;</li>
* </ul>
* @param model
* @throws ScanningException
*/
@SuppressWarnings("deprecation")
private void setMetadataScannables(ScanModel model, Collection<String> scannableNames) throws ScanningException {
final IScannableDeviceService deviceConnectorService = scanDevice.getConnectorService();
// build up the set of all metadata scannables
final Set<String> metadataScannableNames = new HashSet<>();
// add the metadata scannables in the model
if (model.getMonitors()!=null) {
Collection<IScannable<?>> perScan = model.getMonitors().stream().filter(scannable -> scannable.getMonitorRole()==MonitorRole.PER_SCAN).collect(Collectors.toList());
metadataScannableNames.addAll(perScan.stream().map(m -> m.getName()).collect(Collectors.toSet()));
}
// add the global metadata scannables, and the required metadata scannables for
// each scannable in the scan
metadataScannableNames.addAll(deviceConnectorService.getGlobalMetadataScannableNames());
// the set of scannable names to check for dependencies
Set<String> scannableNamesToCheck = new HashSet<>();
scannableNamesToCheck.addAll(metadataScannableNames);
scannableNamesToCheck.addAll(scannableNames);
do {
// check the given set of scannable names for dependencies
// each iteration checks the scannable names added in the previous one
Set<String> requiredScannables = scannableNamesToCheck.stream().flatMap(
name -> deviceConnectorService.getRequiredMetadataScannableNames(name).stream())
.filter(name -> !metadataScannableNames.contains(name))
.collect(Collectors.toSet());
metadataScannableNames.addAll(requiredScannables);
scannableNamesToCheck = requiredScannables;
} while (!scannableNamesToCheck.isEmpty());
// remove any scannable names in the scan from the list of metadata scannables
metadataScannableNames.removeAll(scannableNames);
// get the metadata scannables for the given names
final List<IScannable<?>> monitors = new ArrayList<>(model.getMonitors());
for (String scannableName : metadataScannableNames) {
IScannable<?> metadataScannable = deviceConnectorService.getScannable(scannableName);
try {
metadataScannable.setMonitorRole(MonitorRole.PER_SCAN);
} catch (IllegalArgumentException ne) {
continue;
}
monitors.add(metadataScannable);
}
model.setMonitors(monitors);
}
private List<String> getScannableNames(Iterable<IPosition> gen) {
List<String> names = null;
if (gen instanceof IDeviceDependentIterable) {
names = ((IDeviceDependentIterable)gen).getScannableNames();
}
if (names==null) {
names = model.getPositionIterable().iterator().next().getNames();
}
return names;
}
private NexusScanInfo createScanInfo(ScanModel scanModel, List<String> scannableNames) throws ScanningException {
final NexusScanInfo nexusScanInfo = new NexusScanInfo(scannableNames);
final int scanRank = getScanRank(scanModel);
nexusScanInfo.setRank(scanRank);
nexusScanInfo.setShape(scanModel.getScanInformation().getShape());
nexusScanInfo.setDetectorNames(getDeviceNames(scanModel.getDetectors()));
Collection<IScannable<?>> perPoint = model.getMonitors().stream().filter(scannable -> scannable.getMonitorRole()==MonitorRole.PER_POINT).collect(Collectors.toList());
Collection<IScannable<?>> perScan = model.getMonitors().stream().filter(scannable -> scannable.getMonitorRole()==MonitorRole.PER_SCAN).collect(Collectors.toList());
nexusScanInfo.setMonitorNames(getDeviceNames(perPoint));
nexusScanInfo.setMetadataScannableNames(getDeviceNames(perScan));
return nexusScanInfo;
}
protected int getScanRank(ScanModel model) throws ScanningException {
return getScanRank(model.getPositionIterable());
}
protected int getScanRank(Iterable<IPosition> gen) {
int scanRank = -1;
if (gen instanceof IDeviceDependentIterable) {
scanRank = ((IDeviceDependentIterable)gen).getScanRank();
}
if (scanRank < 0) {
scanRank = gen.iterator().next().getScanRank();
}
if (scanRank < 0) {
scanRank = 1;
}
return scanRank;
}
private Set<String> getDeviceNames(Collection<? extends INameable> devices) {
return devices.stream().map(d -> d.getName()).collect(Collectors.toSet());
}
protected SolsticeScanMonitor createSolsticeScanMonitor(ScanModel scanModel) {
SolsticeScanMonitor solsticeScanMonitor = new SolsticeScanMonitor(model);
// add the solstice scan monitor to the list of monitors in the scan
List<IScannable<?>> monitors = scanModel.getMonitors();
if (monitors == null || monitors.isEmpty()) {
scanModel.setMonitors(solsticeScanMonitor);
} else {
monitors.add(solsticeScanMonitor);
}
return solsticeScanMonitor;
}
/**
* Creates and populates the {@link NXentry} for the NeXus file.
* @param fileBuilder a {@link NexusFileBuilder}
* @throws NexusException
*/
private void createEntry(NexusFileBuilder fileBuilder) throws NexusException {
final NexusEntryBuilder entryBuilder = fileBuilder.newEntry();
entryBuilder.addDefaultGroups();
addScanMetadata(entryBuilder, model.getScanMetadata());
// add all the devices to the entry. Metadata scannables are added first.
for (ScanRole deviceType : EnumSet.allOf(ScanRole.class)) {
addDevicesToEntry(entryBuilder, deviceType);
}
// create the NXdata groups
createNexusDataGroups(entryBuilder);
}
private void addDevicesToEntry(NexusEntryBuilder entryBuilder, ScanRole deviceType) throws NexusException {
entryBuilder.addAll(nexusObjectProviders.get(deviceType));
List<CustomNexusEntryModification> customModifications =
nexusDevices.get(deviceType).stream().
map(d -> d.getCustomNexusModification()).
filter(Objects::nonNull).
collect(Collectors.toList());
for (CustomNexusEntryModification customModification : customModifications) {
entryBuilder.modifyEntry(customModification);
}
}
private void addScanMetadata(NexusEntryBuilder entryBuilder, List<ScanMetadata> scanMetadataList) throws NexusException {
if (scanMetadataList != null) {
for (ScanMetadata scanMetadata : scanMetadataList) {
// convert the ScanMetadata into a MapBasedMetadataProvider and add to the entry builder
NexusBaseClass category = getBaseClassForMetadataType(scanMetadata.getType());
MapBasedMetadataProvider metadataProvider = new MapBasedMetadataProvider(category);
Map<String, Object> metadataFields = scanMetadata.getFields();
for (String metadataFieldName : metadataFields.keySet()) {
Object value = scanMetadata.getFieldValue(metadataFieldName);
metadataProvider.addMetadataEntry(metadataFieldName, value);
}
entryBuilder.addMetadata(metadataProvider);
}
}
}
private NexusBaseClass getBaseClassForMetadataType(MetadataType metadataType) {
if (metadataType == null) {
return null;
}
switch (metadataType) {
case ENTRY:
return NexusBaseClass.NX_ENTRY;
case INSTRUMENT:
return NexusBaseClass.NX_INSTRUMENT;
case SAMPLE:
return NexusBaseClass.NX_SAMPLE;
case USER:
return NexusBaseClass.NX_USER;
default:
throw new IllegalArgumentException("Unknown metadata type : " + metadataType);
}
}
private List<INexusDevice<?>> getNexusDevices(Collection<?> devices) {
return devices.stream().filter(d -> d instanceof INexusDevice<?>).map(
d -> (INexusDevice<?>) d).collect(Collectors.toList());
}
protected Collection<INexusDevice<?>> getNexusScannables(Collection<String> scannableNames) throws ScanningException {
try {
return scannableNames.stream().map(name -> getNexusScannable(name)).
filter(s -> s != null).collect(Collectors.toList());
} catch (Exception e) {
if (e.getCause() instanceof ScanningException) {
throw (ScanningException) e.getCause();
} else {
throw e;
}
}
}
protected INexusDevice<?> getNexusScannable(String scannableName) {
try {
IScannable<?> scannable = scanDevice.getConnectorService().getScannable(scannableName);
if (scannable == null) {
throw new IllegalArgumentException("No such scannable: " + scannableName);
}
if (scannable instanceof INexusDevice<?>) {
return (INexusDevice<?>) scannable;
}
return null;
} catch (ScanningException e) {
throw new RuntimeException("Error getting scannable with name: " + scannableName, e);
}
}
/**
* Create the {@link NXdata} groups for the scan
* @param entryBuilder
* @throws NexusException
*/
private void createNexusDataGroups(final NexusEntryBuilder entryBuilder) throws NexusException {
Set<ScanRole> deviceTypes = EnumSet.of(ScanRole.DETECTOR, ScanRole.SCANNABLE, ScanRole.MONITOR);
if (deviceTypes.stream().allMatch(t -> nexusObjectProviders.get(t).isEmpty())) {
throw new NexusException("The scan must include at least one device in order to write a NeXus file.");
}
List<NexusObjectProvider<?>> detectors = nexusObjectProviders.get(ScanRole.DETECTOR);
if (detectors.isEmpty()) {
// create a NXdata groups when there is no detector
// (uses first monitor, or first scannable if there is no monitor either)
createNXDataGroups(entryBuilder, null);
} else {
// create NXdata groups for each detector
for (NexusObjectProvider<?> detector : detectors) {
createNXDataGroups(entryBuilder, detector);
}
}
}
private void createNXDataGroups(NexusEntryBuilder entryBuilder, NexusObjectProvider<?> detector) throws NexusException {
List<NexusObjectProvider<?>> scannables = nexusObjectProviders.get(ScanRole.SCANNABLE);
List<NexusObjectProvider<?>> monitors = new LinkedList<>(nexusObjectProviders.get(ScanRole.MONITOR));
monitors.remove(solsticeScanMonitor.getNexusProvider(scanInfo));
// determine the primary device - i.e. the device whose primary dataset to make the @signal field
NexusObjectProvider<?> primaryDevice = null;
final ScanRole primaryDeviceType;
if (detector != null) {
// if there's a detector then it is the primary device
primaryDevice = detector;
primaryDeviceType = ScanRole.DETECTOR;
} else if (!monitors.isEmpty()) {
// otherwise the first monitor is the primary device (and therefore is not a data device)
primaryDevice = monitors.remove(0);
primaryDeviceType = ScanRole.MONITOR;
} else if (!scannables.isEmpty()) {
// if there are no monitors either (a rare edge case), where we use the first scannable
// note that this scannable is also added as data device
for (NexusObjectProvider<?> scannable : scannables) {
if (scannable.getPrimaryDataFieldName() != null) {
primaryDevice = scannable;
break;
}
if (primaryDevice == null) {
// Could not device with a dataset to use as the @signal field
logger.error("Could not create an NXdata group for the nexus file as no suitable dataset could be found.");
return;
}
}
primaryDeviceType = ScanRole.SCANNABLE;
} else {
// the scan has no devices at all (sanity check as this should already have been checked for)
throw new IllegalStateException("There must be at least one device to create a Nexus file.");
}
// create the NXdata group for the primary data field
String primaryDeviceName = primaryDevice.getName();
String primaryDataFieldName = primaryDevice.getPrimaryDataFieldName();
createNXDataGroup(entryBuilder, primaryDevice, primaryDeviceType, monitors,
scannables, primaryDeviceName, primaryDataFieldName);
// create an NXdata group for each additional primary data field (if any)
for (String dataFieldName : primaryDevice.getAdditionalPrimaryDataFieldNames()) {
String dataGroupName = primaryDeviceName + "_" + dataFieldName;
createNXDataGroup(entryBuilder, primaryDevice, primaryDeviceType, monitors,
scannables, dataGroupName, dataFieldName);
}
}
/**
* Create the {@link NXdata} groups for the given primary device.
* @param entryBuilder the entry builder to add to
* @param primaryDevice the primary device (e.g. a detector or monitor)
* @param primaryDeviceType the type of the primary device
* @param monitors the monitors
* @param scannable the scannables
* @param dataGroupName the name of the {@link NXdata} group within the parent {@link NXentry}
* @param primaryDataFieldName the name that the primary data field name
* (i.e. the <code>@signal</code> field) should have within the NXdata group
* @throws NexusException
*/
private void createNXDataGroup(NexusEntryBuilder entryBuilder,
NexusObjectProvider<?> primaryDevice,
ScanRole primaryDeviceType,
List<NexusObjectProvider<?>> monitors,
List<NexusObjectProvider<?>> scannables,
String dataGroupName,
String primaryDataFieldName)
throws NexusException {
if (entryBuilder.getNXentry().containsNode(dataGroupName)) {
dataGroupName += "_data"; // append _data if the node already exists
}
// create the data builder and add the primary device
final NexusDataBuilder dataBuilder = entryBuilder.newData(dataGroupName);
PrimaryDataDevice<?> primaryDataDevice = createPrimaryDataDevice(
primaryDevice, primaryDeviceType, primaryDataFieldName);
dataBuilder.setPrimaryDevice(primaryDataDevice);
// add the monitors (excludes the first monitor if the scan has no detectors)
for (NexusObjectProvider<?> monitor : monitors) {
dataBuilder.addAxisDevice(getAxisDataDevice(monitor, null));
}
// Create the map from scannable name to default index of that scannable in the scan
if (defaultAxisIndexForScannable == null) {
defaultAxisIndexForScannable = createDefaultAxisMap(scannables);
}
// add the scannables to the data builder
Iterator<NexusObjectProvider<?>> scannablesIter = scannables.iterator();
while (scannablesIter.hasNext()) {
final NexusObjectProvider<?> scannable = scannablesIter.next();
final Integer defaultAxisForDimensionIndex =
defaultAxisIndexForScannable.get(scannable.getName());
dataBuilder.addAxisDevice(getAxisDataDevice(scannable, defaultAxisForDimensionIndex));
}
}
/**
* Creates a map from scannable names to the index of the scan
* (and therefore the index of the signal dataset of each NXdata) that this
* scannable is the default axis for.
*
* @param scannables list of scannables
* @return map from scannable name to index that this scannable is the index for
*/
private Map<String, Integer> createDefaultAxisMap(List<NexusObjectProvider<?>> scannables) {
final Map<String, Integer> defaultAxisIndexForScannableMap = new HashMap<>();
AbstractPosition firstPosition = (AbstractPosition) model.getPositionIterable().iterator().next();
// A collection of dimension (scannable) names for each index of the scan
List<Collection<String>> dimensionNames = firstPosition.getDimensionNames();
// Convert the list into a map from scannable name to index in scan, only including
// scannable names which are the dimension name for exactly one index of the scan
int dimensionIndex = 0;
Iterator<Collection<String>> dimensionNamesIter = dimensionNames.iterator();
while (dimensionNamesIter.hasNext()) {
Collection<String> dimensionNamesForIndex = dimensionNamesIter.next();
//need to iterate or the _indices attibute defaults to [0]
Iterator<String> it = dimensionNamesForIndex.iterator();
while (it.hasNext()){
String scannableName = it.next();
if (defaultAxisIndexForScannableMap.containsKey(scannableName)) {
// already seen this scannable name for another index,
// so this scannable should not be the default axis for any index
// note: we put null instead of removing the entry in case the scannable
// because we don't want to add it again if the scannable is encountered again
defaultAxisIndexForScannableMap.put(scannableName, null);
}else {
defaultAxisIndexForScannableMap.put(scannableName, dimensionIndex);
}
}
dimensionIndex++;
}
return defaultAxisIndexForScannableMap;
}
private <N extends NXobject> PrimaryDataDevice<N> createPrimaryDataDevice(
NexusObjectProvider<N> nexusObjectProvider,
ScanRole primaryDeviceType, String signalDataFieldName) throws NexusException {
if (primaryDeviceType == ScanRole.SCANNABLE) {
// using scannable as primary device as well as a scannable
// only use main data field (e.g. value for an NXpositioner)
DataDeviceBuilder<N> dataDeviceBuilder = DataDeviceBuilder.newPrimaryDataDeviceBuilder(
nexusObjectProvider);
dataDeviceBuilder.setAxisFields();
return (PrimaryDataDevice<N>) dataDeviceBuilder.build();
}
return DataDeviceBuilder.newPrimaryDataDevice(nexusObjectProvider, signalDataFieldName);
}
/**
* Gets the data device for the given {@link NexusObjectProvider},
* creating it if it doesn't exist.
*
* @param nexusObjectProvider nexus object provider
* @param scannableIndex index in scan for {@link IScannable}s, or <code>null</code>
* if the scannable is being scanned (i.e. is a monitor or metadata scannable).
* @param isPrimaryDevice <code>true</code> if this is the primary device for
* the scan, <code>false</code> otherwise
* @return the data device
* @throws NexusException
*/
private AxisDataDevice<?> getAxisDataDevice(NexusObjectProvider<?> nexusObjectProvider,
Integer scannableIndex) throws NexusException {
AxisDataDevice<?> dataDevice = dataDevices.get(nexusObjectProvider);
if (dataDevice == null) {
dataDevice = createAxisDataDevice(nexusObjectProvider, scannableIndex);
// cache the non-primary devices for any other NXdata groups
dataDevices.put(nexusObjectProvider, dataDevice);
}
return dataDevice;
}
/**
* Creates the {@link DataDevice} for the given {@link NexusObjectProvider},
* @param nexusObjectProvider
* @param scannableIndex if the {@link NexusObjectProvider} represents an
* {@link IScannable} then the index of that scannable in the list of scannables,
* otherwise <code>null</code>
* @return
* @throws NexusException
*/
private <N extends NXobject> AxisDataDevice<N> createAxisDataDevice(
NexusObjectProvider<N> nexusObjectProvider, Integer scannableIndex) throws NexusException {
if (model instanceof ScanDataModel) {
// using a ScanDataModel allows for customization of how the data fields
// of the device are added to the NXdata
ScanDeviceModel scanDeviceModel = ((ScanDataModel) model).getScanDevice(
nexusObjectProvider.getName());
if (scanDeviceModel != null) {
createCustomAxisDataDevice(nexusObjectProvider, scanDeviceModel, scannableIndex);
}
}
return DataDeviceBuilder.newAxisDataDevice(nexusObjectProvider, scannableIndex);
}
/**
* Configures the {@link DataDevice} according to the given {@link ScanDeviceModel}.
* @param nexusObjectProvider
* @param scanDeviceModel scan device model
*/
private <N extends NXobject> void createCustomAxisDataDevice(
NexusObjectProvider<N> nexusObjectProvider, ScanDeviceModel scanDeviceModel,
Integer scannableIndex) {
DataDeviceBuilder<N> builder = DataDeviceBuilder.newAxisDataDeviceBuilder(
nexusObjectProvider, scannableIndex);
// add named fields only means only add fields
if (scanDeviceModel.getAddNamedFieldsOnly()) {
builder.clearAxisFields();
}
// set the default dimension mappings
builder.setDefaultDimensionMappings(scanDeviceModel.getDefaultDimensionMappings());
builder.setDefaultAxisDimension(scanDeviceModel.getDefaultAxisDimension());
// configure the information for any fields
Map<String, ScanFieldModel> fieldDimensionModels = scanDeviceModel.getFieldDimensionModels();
for (String sourceFieldName : fieldDimensionModels.keySet()) {
ScanFieldModel fieldDimensionModel = fieldDimensionModels.get(sourceFieldName);
builder.addAxisField(sourceFieldName);
if (fieldDimensionModel != null) {
// add the field info from the ScanModel to the DataDevice
// the name of the field in the NXdata
String destinationFieldName = scanDeviceModel.getDestinationFieldName(sourceFieldName);
if (destinationFieldName != null) {
builder.setDestinationFieldName(sourceFieldName, destinationFieldName);
}
// the index of the dimension of the signal field that this field is a default axis for
Integer fieldDefaultAxisDimension = fieldDimensionModel.getDefaultAxisDimension();
if (fieldDefaultAxisDimension != null) {
builder.setDefaultAxisDimension(fieldDefaultAxisDimension);
}
// the dimension mappings between this field and the signal field
int[] dimensionMappings = fieldDimensionModel.getDimensionMappings();
if (dimensionMappings != null) {
builder.setDimensionMappings(sourceFieldName, dimensionMappings);
}
}
}
}
} |
package org.spoofax.jsglr2.integrationtest;
import static java.util.Collections.sort;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr.client.imploder.IToken;
import org.spoofax.jsglr2.JSGLR2;
import org.spoofax.jsglr2.JSGLR2Result;
import org.spoofax.jsglr2.JSGLR2Success;
import org.spoofax.jsglr2.integration.IntegrationVariant;
import org.spoofax.jsglr2.integration.ParseTableVariant;
import org.spoofax.jsglr2.integration.WithParseTable;
import org.spoofax.jsglr2.parseforest.ParseForestRepresentation;
import org.spoofax.jsglr2.parser.IParser;
import org.spoofax.jsglr2.parser.ParseException;
import org.spoofax.jsglr2.parser.Position;
import org.spoofax.jsglr2.parser.result.ParseResult;
import org.spoofax.jsglr2.util.AstUtilities;
import org.spoofax.terms.TermFactory;
import org.spoofax.terms.io.binary.TermReader;
public abstract class BaseTest implements WithParseTable {
private static TermReader termReader = new TermReader(new TermFactory());
private static AstUtilities astUtilities = new AstUtilities();
protected BaseTest() {
}
public TermReader getTermReader() {
return termReader;
}
protected Iterable<ParseTableWithOrigin> getParseTablesOrFailOnException(ParseTableVariant variant) {
try {
return getParseTables(variant);
} catch(Exception e) {
e.printStackTrace();
fail("Exception during reading parse table: " + e.getMessage());
return null;
}
}
class TestVariant {
IntegrationVariant variant;
ParseTableWithOrigin parseTableWithOrigin;
TestVariant(IntegrationVariant variant, ParseTableWithOrigin parseTableWithOrigin) {
this.variant = variant;
this.parseTableWithOrigin = parseTableWithOrigin;
}
String name() {
return variant.name() + "(parseTableOrigin:" + parseTableWithOrigin.origin + ")";
}
IParser<?> parser() {
return variant.parser.getParser(parseTableWithOrigin.parseTable);
}
JSGLR2<IStrategoTerm> jsglr2() {
return variant.jsglr2.getJSGLR2(parseTableWithOrigin.parseTable);
}
}
protected Iterable<TestVariant> getTestVariants(Predicate<TestVariant> filter) {
List<TestVariant> testVariants = new ArrayList<>();
for(IntegrationVariant variant : IntegrationVariant.testVariants()) {
for(ParseTableWithOrigin parseTableWithOrigin : getParseTablesOrFailOnException(variant.parseTable)) {
TestVariant testVariant = new TestVariant(variant, parseTableWithOrigin);
// data-dependent, layout-sensitive, and composite parsers are incompatible with Aterm parse table
if((variant.parser.parseForestRepresentation.equals(ParseForestRepresentation.DataDependent)
|| variant.parser.parseForestRepresentation.equals(ParseForestRepresentation.LayoutSensitive)
|| variant.parser.parseForestRepresentation.equals(ParseForestRepresentation.Composite))
&& parseTableWithOrigin.origin.equals(ParseTableOrigin.ATerm)) {
continue;
}
if(filter.test(testVariant))
testVariants.add(testVariant);
}
}
return testVariants;
}
protected Iterable<TestVariant> getTestVariants() {
return getTestVariants(testVariant -> true);
}
protected void testParseSuccess(String inputString) {
for(TestVariant variant : getTestVariants()) {
ParseResult<?> parseResult = variant.parser().parse(inputString);
assertEquals("Variant '" + variant.name() + "' failed parsing: ", true, parseResult.isSuccess());
}
}
protected void testParseFailure(String inputString) {
for(TestVariant variant : getTestVariants()) {
ParseResult<?> parseResult = variant.parser().parse(inputString);
assertEquals("Variant '" + variant.name() + "' should fail: ", false, parseResult.isSuccess());
}
}
protected void testSuccessByAstString(String inputString, String expectedOutputAstString) {
testSuccess(inputString, expectedOutputAstString, null, false);
}
protected void testSuccessByExpansions(String inputString, String expectedOutputAstString) {
testSuccess(inputString, expectedOutputAstString, null, true);
}
protected void testIncrementalSuccessByExpansions(String[] inputStrings, String[] expectedOutputAstStrings) {
testIncrementalSuccess(inputStrings, expectedOutputAstStrings, null, true);
}
protected void testSuccessByAstString(String startSymbol, String inputString, String expectedOutputAstString) {
testSuccess(inputString, expectedOutputAstString, startSymbol, false);
}
protected void testSuccessByExpansions(String startSymbol, String inputString, String expectedOutputAstString) {
testSuccess(inputString, expectedOutputAstString, startSymbol, true);
}
private void testSuccess(String inputString, String expectedOutputAstString, String startSymbol,
boolean equalityByExpansions) {
for(TestVariant variant : getTestVariants()) {
IStrategoTerm actualOutputAst = testSuccess(variant, startSymbol, inputString);
assertEqualAST("Variant '" + variant.name() + "' has incorrect AST", expectedOutputAstString,
actualOutputAst, equalityByExpansions);
}
}
protected IStrategoTerm testSuccess(TestVariant variant, String startSymbol, String inputString) {
return testSuccess("Variant '" + variant.name() + "' failed parsing: ",
"Variant '" + variant.name() + "' failed imploding: ", variant.jsglr2(), "", startSymbol, inputString);
}
private IStrategoTerm testSuccess(String parseFailMessage, String implodeFailMessage, JSGLR2<IStrategoTerm> jsglr2,
String filename, String startSymbol, String inputString) {
try {
IStrategoTerm result = jsglr2.parseUnsafe(inputString, filename, startSymbol);
// Fail here if imploding or tokenization failed
assertNotNull(implodeFailMessage, result);
return result;
} catch(ParseException e) {
// Fail here if parsing failed
fail(parseFailMessage + e.failureType);
}
return null;
}
private void testIncrementalSuccess(String[] inputStrings, String[] expectedOutputAstStrings, String startSymbol,
boolean equalityByExpansions) {
for(TestVariant variant : getTestVariants(
testVariant -> testVariant.variant.parser.parseForestRepresentation == ParseForestRepresentation.Incremental)) {
IStrategoTerm actualOutputAst;
String filename = "" + System.nanoTime(); // To ensure the results will be cached
for(int i = 0; i < expectedOutputAstStrings.length; i++) {
String inputString = inputStrings[i];
actualOutputAst = testSuccess("Variant '" + variant.name() + "' failed parsing at update " + i + ": ",
"Variant '" + variant.name() + "' failed imploding at update " + i + ": ", variant.jsglr2(),
filename, startSymbol, inputString);
assertEqualAST("Variant '" + variant.name() + "' has incorrect AST at update " + i + ": ",
expectedOutputAstStrings[i], actualOutputAst, equalityByExpansions);
}
}
}
protected void assertEqualAST(String message, String expectedOutputAstString, IStrategoTerm actualOutputAst,
boolean equalityByExpansions) {
if(equalityByExpansions) {
IStrategoTerm expectedOutputAst = termReader.parseFromString(expectedOutputAstString);
assertEqualTermExpansions(message, expectedOutputAst, actualOutputAst);
} else {
assertEquals(message, expectedOutputAstString, actualOutputAst.toString());
}
}
protected static void assertEqualTermExpansions(IStrategoTerm expected, IStrategoTerm actual) {
assertEqualTermExpansions(null, expected, actual);
}
protected static void assertEqualTermExpansions(String message, IStrategoTerm expected, IStrategoTerm actual) {
List<String> expectedExpansion = toSortedStringList(astUtilities.expand(expected));
List<String> actualExpansion = toSortedStringList(astUtilities.expand(actual));
assertEquals(message, expectedExpansion, actualExpansion);
}
private static List<String> toSortedStringList(List<IStrategoTerm> astExpansion) {
List<String> result = new ArrayList<>(astExpansion.size());
for(IStrategoTerm ast : astExpansion) {
result.add(ast.toString());
}
sort(result);
return result;
}
protected void testTokens(String inputString, List<TokenDescriptor> expectedTokens) {
for(TestVariant variant : getTestVariants()) {
JSGLR2Result<?> jsglr2Result = variant.jsglr2().parseResult(inputString, "", null);
String variantPrefix = "Variant '" + variant.name() + "' failed";
assertTrue(variantPrefix, jsglr2Result.isSuccess());
JSGLR2Success<?> jsglr2Success = (JSGLR2Success<?>) jsglr2Result;
List<TokenDescriptor> actualTokens = new ArrayList<>();
for(IToken token : jsglr2Success.tokens) {
actualTokens.add(TokenDescriptor.from(inputString, token));
}
TokenDescriptor expectedStartToken = new TokenDescriptor("", IToken.TK_RESERVED, 0, 1, 1);
TokenDescriptor actualStartToken = actualTokens.get(0);
assertEquals(variantPrefix + "\nStart token incorrect:", expectedStartToken, actualStartToken);
Position endPosition = Position.atEnd(inputString);
int endLine = endPosition.line;
int endColumn = endPosition.column;
TokenDescriptor expectedEndToken =
new TokenDescriptor("", IToken.TK_EOF, inputString.length(), endLine, endColumn - 1);
TokenDescriptor actualEndToken = actualTokens.get(actualTokens.size() - 1);
List<TokenDescriptor> actualTokensWithoutStartAndEnd = actualTokens.subList(1, actualTokens.size() - 1);
assertThat(variantPrefix + "\nToken lists don't match:", actualTokensWithoutStartAndEnd,
is(expectedTokens));
assertEquals(variantPrefix + "\nEnd token incorrect:", expectedEndToken, actualEndToken);
}
}
protected String getFileAsString(String filename) throws IOException {
byte[] encoded =
Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("samples/" + filename).getPath()));
return new String(encoded, StandardCharsets.UTF_8);
}
protected IStrategoTerm getFileAsAST(String filename) throws IOException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("samples/" + filename);
return termReader.parseFromStream(inputStream);
}
} |
package net.fortuna.ical4j.model;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Iterator;
import net.fortuna.ical4j.model.component.CalendarComponent;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.model.property.XProperty;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.ComponentValidator;
import net.fortuna.ical4j.util.PropertyValidator;
import net.fortuna.ical4j.util.Strings;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* $Id$ [Apr 5, 2004]
*
* Defines an iCalendar calendar.
*
* <pre>
* 4.6 Calendar Components
*
* The body of the iCalendar object consists of a sequence of calendar
* properties and one or more calendar components. The calendar
* properties are attributes that apply to the calendar as a whole. The
* calendar components are collections of properties that express a
* particular calendar semantic. For example, the calendar component can
* specify an event, a to-do, a journal entry, time zone information, or
* free/busy time information, or an alarm.
*
* The body of the iCalendar object is defined by the following
* notation:
*
* icalbody = calprops component
*
* calprops = 2*(
*
* ; 'prodid' and 'version' are both REQUIRED,
* ; but MUST NOT occur more than once
*
* prodid /version /
*
* ; 'calscale' and 'method' are optional,
* ; but MUST NOT occur more than once
*
* calscale /
* method /
*
* x-prop
*
* )
*
* component = 1*(eventc / todoc / journalc / freebusyc /
* / timezonec / iana-comp / x-comp)
*
* iana-comp = "BEGIN" ":" iana-token CRLF
*
* 1*contentline
*
* "END" ":" iana-token CRLF
*
* x-comp = "BEGIN" ":" x-name CRLF
*
* 1*contentline
*
* "END" ":" x-name CRLF
* </pre>
*
* Example 1 - Creating a new calendar:
*
* <pre><code>
* Calendar calendar = new Calendar();
* calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
* calendar.getProperties().add(Version.VERSION_2_0);
* calendar.getProperties().add(CalScale.GREGORIAN);
*
* // Add events, etc..
* </code></pre>
*
* @author Ben Fortuna
*/
public class Calendar implements Serializable {
private static final long serialVersionUID = -1654118204678581940L;
public static final String BEGIN = "BEGIN";
public static final String VCALENDAR = "VCALENDAR";
public static final String END = "END";
private PropertyList properties;
private ComponentList components;
/**
* Default constructor.
*/
public Calendar() {
this(new PropertyList(), new ComponentList());
}
/**
* Constructs a new calendar with no properties and the specified components.
* @param components a list of components to add to the calendar
*/
public Calendar(final ComponentList components) {
this(new PropertyList(), components);
}
/**
* Constructor.
* @param p a list of properties
* @param c a list of components
*/
public Calendar(final PropertyList p, final ComponentList c) {
this.properties = p;
this.components = c;
}
/**
* Creates a deep copy of the specified calendar.
* @param c the calendar to copy
*/
public Calendar(Calendar c) throws ParseException, IOException,
URISyntaxException {
this(new PropertyList(c.getProperties()), new ComponentList(c
.getComponents()));
}
/**
* @see java.lang.Object#toString()
*/
public final String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(BEGIN);
buffer.append(':');
buffer.append(VCALENDAR);
buffer.append(Strings.LINE_SEPARATOR);
buffer.append(getProperties());
buffer.append(getComponents());
buffer.append(END);
buffer.append(':');
buffer.append(VCALENDAR);
buffer.append(Strings.LINE_SEPARATOR);
return buffer.toString();
}
/**
* @return Returns the components.
*/
public final ComponentList getComponents() {
return components;
}
/**
* Convenience method for retrieving a list of named components.
* @param name name of components to retrieve
* @return a component list containing only components with the specified name
*/
public final ComponentList getComponents(final String name) {
return getComponents().getComponents(name);
}
/**
* Convenience method for retrieving a named component.
* @param name name of the component to retrieve
* @return the first matching component in the component list with the specified name
*/
public final Component getComponent(final String name) {
return getComponents().getComponent(name);
}
/**
* @return Returns the properties.
*/
public final PropertyList getProperties() {
return properties;
}
/**
* Convenience method for retrieving a list of named properties.
* @param name name of properties to retrieve
* @return a property list containing only properties with the specified name
*/
public final PropertyList getProperties(final String name) {
return getProperties().getProperties(name);
}
/**
* Convenience method for retrieving a named property.
* @param name name of the property to retrieve
* @return the first matching property in the property list with the specified name
*/
public final Property getProperty(final String name) {
return getProperties().getProperty(name);
}
/**
* Perform validation on the calendar, its properties and its components in its current state.
* @throws ValidationException where the calendar is not in a valid state
*/
public final void validate() throws ValidationException {
validate(true);
}
/**
* Perform validation on the calendar in its current state.
* @param recurse indicates whether to validate the calendar's properties and components
* @throws ValidationException where the calendar is not in a valid state
*/
public void validate(final boolean recurse) throws ValidationException {
// 'prodid' and 'version' are both REQUIRED,
// but MUST NOT occur more than once
PropertyValidator.getInstance().assertOne(Property.PRODID, properties);
PropertyValidator.getInstance().assertOne(Property.VERSION, properties);
if (!Version.VERSION_2_0.equals(getProperty(Property.VERSION))) {
throw new ValidationException("Unsupported Version: " + getProperty(Property.VERSION).getValue());
}
// 'calscale' and 'method' are optional,
// but MUST NOT occur more than once
PropertyValidator.getInstance().assertOneOrLess(Property.CALSCALE,
properties);
PropertyValidator.getInstance().assertOneOrLess(Property.METHOD,
properties);
// must contain at least one component
if (getComponents().isEmpty()) {
throw new ValidationException(
"Calendar must contain at least one component");
}
// validate properties..
for (final Iterator i = getProperties().iterator(); i.hasNext();) {
final Property property = (Property) i.next();
if (!(property instanceof XProperty)
&& !property.isCalendarProperty()) {
throw new ValidationException("Invalid property: "
+ property.getName());
}
}
// validate components..
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final Component component = (Component) i.next();
if (!(component instanceof CalendarComponent)) {
throw new ValidationException("Not a valid calendar component: " + component.getName());
}
}
// if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// validate method..
if (Method.PUBLISH.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
}
else if (getComponent(Component.VFREEBUSY) != null) {
ComponentValidator.assertNone(Component.VTODO, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
// ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
else if (getComponent(Component.VJOURNAL) != null) {
// ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
// ComponentValidator.assertNone(Component.VTODO, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validatePublish();
}
}
else if (Method.REQUEST.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VFREEBUSY) != null) {
ComponentValidator.assertNone(Component.VTODO, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
// ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateRequest();
}
}
else if (Method.REPLY.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertOneOrLess(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VFREEBUSY) != null) {
ComponentValidator.assertNone(Component.VTODO, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertOneOrLess(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
// ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateReply();
}
}
else if (Method.ADD.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
else if (getComponent(Component.VJOURNAL) != null) {
ComponentValidator.assertOneOrLess(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
// ComponentValidator.assertNone(Component.VTODO, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateAdd();
}
}
else if (Method.CANCEL.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertOneOrLess(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
else if (getComponent(Component.VJOURNAL) != null) {
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
// ComponentValidator.assertNone(Component.VTODO, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateCancel();
}
}
else if (Method.REFRESH.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTIMEZONE, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateRefresh();
}
}
else if (Method.COUNTER.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertOneOrLess(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateCounter();
}
}
else if (Method.DECLINE_COUNTER.equals(getProperty(Property.METHOD))) {
if (getComponent(Component.VEVENT) != null) {
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
ComponentValidator.assertNone(Component.VTODO, getComponents());
ComponentValidator.assertNone(Component.VTIMEZONE, getComponents());
ComponentValidator.assertNone(Component.VALARM, getComponents());
}
else if (getComponent(Component.VTODO) != null) {
ComponentValidator.assertNone(Component.VALARM, getComponents());
ComponentValidator.assertNone(Component.VFREEBUSY, getComponents());
// ComponentValidator.assertNone(Component.VEVENT, getComponents());
ComponentValidator.assertNone(Component.VJOURNAL, getComponents());
}
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final CalendarComponent component = (CalendarComponent) i.next();
component.validateDeclineCounter();
}
}
if (recurse) {
validateProperties();
validateComponents();
}
}
/**
* Invoke validation on the calendar properties in its current state.
* @throws ValidationException where any of the calendar properties is not in a valid state
*/
private void validateProperties() throws ValidationException {
for (final Iterator i = getProperties().iterator(); i.hasNext();) {
final Property property = (Property) i.next();
property.validate();
}
}
/**
* Invoke validation on the calendar components in its current state.
* @throws ValidationException where any of the calendar components is not in a valid state
*/
private void validateComponents() throws ValidationException {
for (final Iterator i = getComponents().iterator(); i.hasNext();) {
final Component component = (Component) i.next();
component.validate();
}
}
/**
* Returns the mandatory prodid property.
* @return
*/
public final ProdId getProductId() {
return (ProdId) getProperty(Property.PRODID);
}
/**
* Returns the mandatory version property.
* @return
*/
public final Version getVersion() {
return (Version) getProperty(Property.VERSION);
}
/**
* Returns the optional calscale property.
* @return
*/
public final CalScale getCalendarScale() {
return (CalScale) getProperty(Property.CALSCALE);
}
/**
* Returns the optional method property.
* @return
*/
public final Method getMethod() {
return (Method) getProperty(Property.METHOD);
}
/**
* Uses {@link EqualsBuilder} to test equality. Two calendars are equal if and only if their property lists and
* component lists are equal.
*/
public final boolean equals(final Object arg0) {
if (arg0 instanceof Calendar) {
final Calendar calendar = (Calendar) arg0;
return new EqualsBuilder().append(getProperties(), calendar.getProperties())
.append(getComponents(), calendar.getComponents()).isEquals();
}
return super.equals(arg0);
}
/**
* Uses {@link HashCodeBuilder} to build hashcode.
*/
public final int hashCode() {
return new HashCodeBuilder().append(getProperties()).append(
getComponents()).toHashCode();
}
} |
package net.fortuna.ical4j.model;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.Dates;
import net.fortuna.ical4j.util.TimeZones;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class DateTime extends Date {
private static final long serialVersionUID = -6407231357919440387L;
private static final String DEFAULT_PATTERN = "yyyyMMdd'T'HHmmss";
private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss'Z'";
private static final String RELAXED_PATTERN = "yyyyMMdd";
/**
* Used for parsing times in a UTC date-time representation.
*/
private static final ThreadLocal utc_format =
new ThreadLocal () {
protected Object initialValue() {
DateFormat format = new SimpleDateFormat(UTC_PATTERN);
format.setTimeZone(TimeZone.getTimeZone(TimeZones.UTC_ID));
format.setLenient(false);
return (Object)format;
}
};
/**
* Used for parsing times in a local date-time representation.
*/
private static final ThreadLocal default_format =
new ThreadLocal () {
protected Object initialValue() {
DateFormat format = new SimpleDateFormat(DEFAULT_PATTERN);
format.setLenient(false);
return (Object)format;
}
};
private static final ThreadLocal lenient_default_format =
new ThreadLocal () {
protected Object initialValue() {
return (Object)new SimpleDateFormat(DEFAULT_PATTERN);
}
};
private static final ThreadLocal relaxed_format =
new ThreadLocal () {
protected Object initialValue() {
return (Object)new SimpleDateFormat(RELAXED_PATTERN);
}
};
private Time time;
private TimeZone timezone;
/**
* Default constructor.
*/
public DateTime() {
super(Dates.PRECISION_SECOND);
this.time = new Time(System.currentTimeMillis(), getFormat()
.getTimeZone());
}
/**
* @param utc
*/
public DateTime(final boolean utc) {
this();
setUtc(utc);
}
/**
* @param time
*/
public DateTime(final long time) {
super(time, Dates.PRECISION_SECOND);
this.time = new Time(time, getFormat().getTimeZone());
}
/**
* @param date
*/
public DateTime(final java.util.Date date) {
super(date.getTime(), Dates.PRECISION_SECOND);
this.time = new Time(date.getTime(), getFormat().getTimeZone());
// copy timezone information if applicable..
if (date instanceof DateTime) {
DateTime dateTime = (DateTime) date;
if (dateTime.isUtc()) {
setUtc(true);
}
else {
setTimeZone(dateTime.getTimeZone());
}
}
}
/**
* Constructs a new DateTime instance from parsing the specified string representation in the default (local)
* timezone.
* @param value
*/
public DateTime(final String value) throws ParseException {
this(value, null);
/*
* long time = 0; try { synchronized (UTC_FORMAT) { time = UTC_FORMAT.parse(value).getTime(); } setUtc(true); }
* catch (ParseException pe) { synchronized (DEFAULT_FORMAT) {
* DEFAULT_FORMAT.setTimeZone(getFormat().getTimeZone()); time = DEFAULT_FORMAT.parse(value).getTime(); }
* this.time = new Time(time, getFormat().getTimeZone()); } setTime(time);
*/
}
/**
* Creates a new date-time instance from the specified value in the given timezone. If a timezone is not specified,
* the default timezone (as returned by {@link java.util.TimeZone#getDefault()}) is used.
* @param value
* @throws ParseException
*/
public DateTime(final String value, final TimeZone timezone)
throws ParseException {
this();
try {
setTime(value, (DateFormat)utc_format.get(), null);
setUtc(true);
}
catch (ParseException pe) {
try {
if (timezone != null) {
setTime(value, (DateFormat)default_format.get(), timezone);
}
else {
// Use lenient parsing for floating times. This is to overcome
// the problem of parsing VTimeZone dates that specify dates
// that the strict parser does not accept.
setTime(value, (DateFormat)lenient_default_format.get(), getFormat()
.getTimeZone());
}
}
catch (ParseException pe2) {
if (CompatibilityHints
.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING)) {
setTime(value, (DateFormat)relaxed_format.get(), timezone);
}
else {
throw pe2;
}
}
setTimeZone(timezone);
}
}
/**
* Internal set of time by parsing value string.
* @param value
* @param format a {@code DateFormat}, protected by the use of a ThreadLocal.
* @param tz
* @throws ParseException
*/
private void setTime(final String value, final DateFormat format, final java.util.TimeZone tz)
throws ParseException {
if (tz != null) {
format.setTimeZone(tz);
}
setTime(format.parse(value).getTime());
}
/*
* (non-Javadoc)
* @see java.util.Date#setTime(long)
*/
public final void setTime(final long time) {
super.setTime(time);
this.time.setTime(time);
}
/**
* @return Returns the utc.
*/
public final boolean isUtc() {
return time.isUtc();
}
/**
* Updates this date-time to display in UTC time if the argument is true. Otherwise, resets to the default timezone.
* @param utc The utc to set.
*/
public final void setUtc(final boolean utc) {
// reset the timezone associated with this instance..
this.timezone = null;
if (utc) {
getFormat().setTimeZone(TimeZone.getTimeZone(TimeZones.UTC_ID));
}
else {
resetTimeZone();
}
time = new Time(time, getFormat().getTimeZone(), utc);
}
/**
* Sets the timezone associated with this date-time instance. If the specified timezone is null, it will reset
* to the default timezone. If the date-time instance is utc, it will turn into
* either a floating (no timezone) date-time, or a date-time with a timezone.
* @param timezone
*/
public final void setTimeZone(final TimeZone timezone) {
this.timezone = timezone;
if (timezone != null) {
getFormat().setTimeZone(timezone);
}
else {
resetTimeZone();
}
time = new Time(time, getFormat().getTimeZone(), false);
}
/**
* Reset the timezone to default.
*/
private void resetTimeZone() {
// use GMT timezone to avoid daylight savings rules affecting floating
// time values..
getFormat().setTimeZone(TimeZone.getDefault());
// getFormat().setTimeZone(TimeZone.getTimeZone(TimeZones.GMT_ID));
}
/**
* Returns the current timezone associated with this date-time value.
* @return a Java timezone
*/
public final TimeZone getTimeZone() {
return timezone;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public final String toString() {
final StringBuffer b = new StringBuffer(super.toString());
b.append('T');
b.append(time.toString());
return b.toString();
}
/**
* Uses {@link EqualsBuilder} to test equality.
*/
public boolean equals(final Object arg0) {
// TODO: what about compareTo, before, after, etc.?
if (arg0 instanceof DateTime) {
return new EqualsBuilder().append(time, ((DateTime) arg0).time).isEquals();
}
return super.equals(arg0);
}
/**
* Uses {@link HashCodeBuilder} to build hashcode.
*/
public int hashCode() {
return new HashCodeBuilder().append(time).append(timezone).toHashCode();
}
} |
package org.jasig.portal.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A thread pool implementation with a few extra kinks,
* such as ThreadPoolReceipt.
* @author Peter Kharchenko <a href="mailto:">pkharchenko@interactivebusiness.com</a>
* @version $Revision$
*/
public class ThreadPool extends ThreadGroup {
private static final Log log = LogFactory.getLog(ThreadPool.class);
BlockingStack idleWorkers;
List workers;
ResourceLimits limits;
public ThreadPool(String name,ResourceLimits rl) {
super(name);
if(rl==null) {
// use default resource limits
limits=new ResourceLimits();
rl.maxSize=10;
rl.optimalSize=3;
} else {
limits=rl;
}
idleWorkers = new BlockingStack(); // doesn't make sense to put an upper limit on this stack
// workers = new Vector(limits.optimalSize);
workers = Collections.synchronizedList(new ArrayList(limits.optimalSize));
// initialize some workers
for (int i=0; i<limits.optimalSize; i++) {
ThreadPoolWorker w=new ThreadPoolWorker(this);
workers.add(w);
w.start();
}
}
public ThreadPoolReceipt execute(Runnable target) throws InterruptedException {
// try growing workers if the stack is empty
if(idleWorkers.empty()) addWorker();
// block on waiting for the next available worker
// ThreadPoolWorker worker = (ThreadPoolWorker) idleWorkers.pop();
// start the process and return a receipt
return(((ThreadPoolWorker)idleWorkers.pop()).process(target));
}
/**
* Adjust the size of the worker pool.
* Adjustment is done by growing/shrinking the idle worker pool.
* Active workers will not be affected by this
*/
protected synchronized void adjustSize(int newSize) {
// see if an adjustment can be done
if(newSize<=limits.maxSize) {
synchronized(workers) {
// determine the adjustment
int adjustment=newSize-workers.size();
// System.out.println("ThreadPool:adjustSize() : requested="+newSize+", current="+workers.size()+", adj="+adjustment);
if(adjustment<0) {
// prune some idle workers
while(adjustment++<0) {
if(!idleWorkers.empty()) {
try {
releaseWorker((ThreadPoolWorker)idleWorkers.nonBlockingPop());
} catch (EmptyStackException ese) {
adjustment
}
} else {
// signal some active workers to go
for(int i=0;i<workers.size() && adjustment<0;i++) {
ThreadPoolWorker w=(ThreadPoolWorker)workers.get(i);
if(releaseWorker(w)) adjustment++;
}
break;
}
}
}
if(adjustment>0) {
// add some idle workers
for(int i=0;i<adjustment;i++)
addNewWorker();
}
}
}
}
/**
* Grow the size of the worker pool.
* This will "attempt" to add another worker, but
* unlike addNewWorker(), the resource limits are checked.
*/
protected synchronized void addWorker() {
adjustSize(workers.size()+1);
}
/**
* Signals the worker that it try to interrupt
* the current job and quit.
*/
protected void stopWorker(ThreadPoolWorker worker) {
// System.out.println("ThreadPool::stopWorker()");
worker.stopRequest();
}
/**
* Signals the worker that it should quite as soon
* as a job (if any) is complete
* @return false if the worker has already been released
*/
protected boolean releaseWorker(ThreadPoolWorker worker) {
// System.out.println("ThreadPool::releaseWorker()");
return worker.completeRequest();
}
/**
* Adds a new worker. Doesn't check anything, just adds.
*/
protected void addNewWorker() {
// System.out.println("ThreadPool::addNewWorker()");
ThreadPoolWorker w= new ThreadPoolWorker(this);
workers.add(w);
w.start();
}
/**
* Clears all of the idle workers
*/
public void clearIdle() {
try {
Object[] idle=new Object[idleWorkers.size()-idleWorkers.getMinSize()];
int index=0;
while(index<idle.length) {
idle[index++]=idleWorkers.pop();
}
for ( int i = 0; i < idle.length; i++ ) {
( (ThreadPoolWorker) idle[i] ).stopRequest();
}
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // re-assert
}
}
/**
* Clears all of the workers.
*/
public void clear() {
// Stop the idle one's first since that won't interfere with anything
// productive.
clearIdle();
// give the idle workers a quick chance to die
try { Thread.sleep(250); } catch ( InterruptedException x ) { }
// Step through the list of ALL workers that are still alive.
for ( int i = 0; i < workers.size(); i++ ) {
if ( ((ThreadPoolWorker)workers.get(i)).isAlive() ) {
((ThreadPoolWorker)workers.get(i)).stopRequest();
}
}
}
/**
* Handle the case when some worker crashes
*/
public void uncaughtException(Thread t, Throwable e) {
log.error("Registered an uncaught exception by thread "+t.getName(), e);
if(t instanceof ThreadPoolWorker && !(e instanceof ThreadDeath)) {
ThreadPoolWorker w=(ThreadPoolWorker) t;
// clean up currentReceipt if the thread didn't do it
try {
if(w.currentReceipt!=null) {
w.currentReceipt.updateStatus(null,true,false,e);
}
} catch (Exception bad) {};
notifyWorkerRestart(w);
}
}
/**
* Notifies the pool that a certain worker is done and
* wants to have a replacement started.
*/
protected void notifyWorkerRestart(ThreadPoolWorker pw) {
notifyWorkerFinished(pw);
this.addWorker();
}
protected void killWorkerThread(ThreadPoolWorker pw) {
// check the receipt
try {
if(pw.currentReceipt!=null) {
pw.currentReceipt.updateStatus(null,true,false,null);
}
} catch (Exception bad) {};
notifyWorkerFinished(pw);
// hopefully all of the locks are released
pw.interrupt();
// pw.stop();
this.addWorker();
// System.out.println("Removed and stopped worker "+pw.getName());
}
/**
* Notifies the pool that a certain worker has finished.
*/
protected void notifyWorkerFinished(ThreadPoolWorker pw) {
// clean up
// System.out.println("ThreadPool::notifyWorkerFinished().");
idleWorkers.remove(pw);
synchronized(workers) {
int index=workers.indexOf(pw);
if(index!=-1)
workers.remove(index);
}
}
} |
package scalac.transformer.matching;
import ch.epfl.lamp.util.Position;
import scalac.*;
import scalac.ast.*;
import scalac.util.*;
import scalac.symtab.*;
import scalac.typechecker.*;
import PatternNode.*;
import Tree.*;
class CodeFactory extends PatternTool {
static final Name SEQ_N = Name.fromString("scala.Sequence");
static final Name SEQ_ITER_N = Name.fromString("scala.SequenceIterator");
static final Name NEW_ITERATOR_N = Name.fromString("newIterator");
static final Name HAS_CUR_N = Name.fromString("hasCur");
static final Name CUR_N = Name.fromString("cur");
static final Name NEXT_N = Name.fromString("next");
/** symbol of `scala.SequenceIterator'
*/
Symbol seqIterSym;
/** symbol of `scala.Sequence.newIterator'
*/
Symbol newIterSym;
Symbol curSym;
Symbol hasCurSym;
Symbol nextSym;
public CodeFactory( Unit unit, Infer infer ) {
super( unit, infer );
// get `Sequence:newIterator'
Symbol sequenceSym = defs.getClass( SEQ_N );
Scope scp = sequenceSym.members();
this.newIterSym = scp.lookup/*Term */( NEW_ITERATOR_N );
assert !( newIterSym == Symbol.NONE ) : " did not find newIterator ";
this.seqIterSym = defs.getType( SEQ_ITER_N ).symbol();
scp = seqIterSym.members();
curSym = scp.lookup/*Term*/ ( CUR_N );
assert !( curSym == Symbol.NONE ) : "did not find cur";
}
/** If ... pos, type is copied from thenBody
*/
Tree If( Tree cond, Tree thenBody, Tree elseBody ) {
//assert( thenBody.type().equals( elseBody.type() )
// || thenBody.type().isSubType( elseBody.type() )
// /*|| elseBody.type().isSubType( thenBody.type() BUG */)
// : "you try to construct a naughty if "
// + "thenBody: "+thenBody.type+" elseBody:"+elseBody.type;
assert cond != null:"cond is null";
assert thenBody != null:"thenBody is null";
assert elseBody != null:"elseBody is null";
return make.If( thenBody.pos,
cond,
thenBody,
elseBody ).setType( elseBody.type() );
}
Tree Switch( Tree selector,
Tree condition[],
Tree body[],
Tree defaultBody ) {
assert selector != null:"selector is null";
assert condition != null:"cond is null";
assert body != null:"body is null";
assert defaultBody != null:"defaultBody is null";
Tree result = defaultBody;
for( int i = condition.length-1; i >= 0; i
result = If( condition[ i ],
body[ i ],
result
).setType( result.type );
return result ;
}
/** `SequenceIterator[ elemType ]' // TODO: Move to TypeFactory
*/
Type _seqIterType( Type elemType ) {
return Type.TypeRef( defs.SCALA_TYPE/*PREFIX*/,
seqIterSym,
new Type[] { elemType });
}
/** returns code `<seqObj>.newIterator'
* the parameter needs to have type attribute `Sequence[<elemType>]'
* it is not checked whether seqObj really has type `Sequence'
*/
Tree newIterator( Tree seqObj ) {
Type args[] = seqObj.type().typeArgs();
assert ( args.length== 1 ) : "seqObj does not have right type";
Type elemType = args[ 0 ];
//System.out.println( "elemType:"+elemType );
//Tree t1 = gen.Select(seqObj, newIterSym);
Tree t1 = make.Select( Position.NOPOS, seqObj, newIterSym.name )
.setSymbol( newIterSym )
.setType( Type.MethodType(new Symbol[] {},_seqIterType( elemType )));
//System.out.println( "t1.type:"+t1.type() );
Tree theIterator = gen.Apply(seqObj.pos,
t1,
Tree.EMPTY_ARRAY)
.setType( _seqIterType( elemType ) );
//System.out.println( "theit.type:"+theIterator.type() );
return theIterator;
}
// the caller needs to set the type !
Tree _applyNone( Tree arg ) {
return make.Apply(Position.NOPOS, arg, Tree.EMPTY_ARRAY );
}
// todo: more defensive checking
Type getElemType( Type seqType ) {
Type[] args = seqType.typeArgs(); /*use typeArgs instead of args*/
assert (args.length==1);
return args[ 0 ];
}
/** `it.cur()'
*/
Tree _cur( Tree iter ) {
Type elemType = getElemType( iter.type() );
return _applyNone( gen.Select( iter, curSym ).setType( elemType ))
.setType( elemType );
}
/** `it.next()'
*/
public Tree _next( Tree iter ) {
Type elemType = getElemType( iter.type() );
return _applyNone( gen.Select( iter, nextSym ))
.setType( iter.type() );
}
/** `it.hasCur()'
*/
public Tree _hascur( Tree iter ) {
return _applyNone( gen.Select( iter, hasCurSym ))
.setType( defs.BOOLEAN_TYPE );
}
/** `!it.hasCur()'
*/
public Tree _noMoreCur( Tree iter ) {
return _applyNone( gen.Select( _hascur( iter ), notSym ))
.setType( defs.BOOLEAN_TYPE );
}
/** return the analyzed type
*/
public Type typeOf(Symbol sym) {
return sym.type();
//return sym.typeAt(unit.global.ANALYZER_PHASE.id);
}
/** return the analyzed type
*/
public Type typeOf0(Symbol sym) {
return sym.typeAt(unit.global.PHASE.ANALYZER.id);
}
protected Tree Block(int pos, Tree[] ts, Type tpe) {
if (ts.length == 1)
return ts[0];
else if (ts.length > 1)
switch (ts[ts.length - 1]) {
case Block(Tree[] ts0):
Tree[] ts1 = new Tree[ts0.length + ts.length - 1];
System.arraycopy(ts, 0, ts1, 0, ts.length - 1);
System.arraycopy(ts0, 0, ts1, ts.length - 1, ts0.length);
return Block(pos, ts1, tpe);
}
return make.Block(pos, ts).setType(tpe);
}
/* // unused
protected Tree Negate(Tree tree) {
switch (tree) {
case Literal(Object value):
return gen.mkBooleanLit(tree.pos, !((Boolean)value).booleanValue());
}
return make.Apply(
tree.pos,
gen.Select(tree, NOT_N),
Tree.EMPTY_ARRAY).setType(defs.BOOLEAN_TYPE);
}
*/
protected Tree And(Tree left, Tree right) {
switch (left) {
case Literal(Object value):
return ((Boolean)value).booleanValue() ? right : left;
}
switch (right) {
case Literal(Object value):
if (((Boolean)value).booleanValue()) return left;
}
Symbol fun = left.type.lookup(AND_N);
return make.Apply(
left.pos,
make.Select(
left.pos,
left,
AND_N).setType(typeOf(fun)).setSymbol(fun),
new Tree[]{right}).setType(defs.BOOLEAN_TYPE);
}
protected Tree Or(Tree left, Tree right) {
switch (left) {
case Literal(Object value):
return ((Boolean)value).booleanValue() ? left : right;
}
switch (right) {
case Literal(Object value):
if (!((Boolean)value).booleanValue()) return left;
}
Symbol fun = left.type.lookup(OR_N);
return make.Apply(
left.pos,
make.Select(
left.pos,
left,
OR_N).setType(typeOf(fun)).setSymbol(fun),
new Tree[]{right}).setType(defs.BOOLEAN_TYPE);
}
protected Tree Is(Tree tree, Type type) {
return
make.Apply(
tree.pos,
make.TypeApply(
tree.pos,
make.Select(
tree.pos,
tree,
defs.IS.name).setType(typeOf(defs.IS)).setSymbol(defs.IS),
new Tree[]{gen.mkType(tree.pos, type)})
.setType(Type.MethodType(Symbol.EMPTY_ARRAY, defs.BOOLEAN_TYPE)),
Tree.EMPTY_ARRAY).setType(defs.BOOLEAN_TYPE);
}
protected Tree As(Tree tree, Type type) {
return
make.Apply(
tree.pos,
make.TypeApply(
tree.pos,
make.Select(
tree.pos,
tree,
defs.AS.name).setType(typeOf(defs.AS)).setSymbol(defs.AS),
new Tree[]{gen.mkType(tree.pos, type)})
.setType(Type.MethodType(Symbol.EMPTY_ARRAY, type)),
Tree.EMPTY_ARRAY).setType(type);
}
protected Tree Equals(Tree left, Tree right) {
Symbol fun = left.type.lookup(EQUALS_N);
switch (typeOf(fun)) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
Tree t = make.Select(left.pos, left, EQUALS_N);
//for (int i = 0; i < alttypes.length; i++)
// System.out.println(alts[i] + ": " + alttypes[i]);
infer.methodAlternative(t, alts, alttypes,
new Type[]{right.type}, defs.BOOLEAN_TYPE);
return make.Apply(left.pos, t, new Tree[]{right}).setType(defs.BOOLEAN_TYPE);
default:
//System.out.println("
return make.Apply(
left.pos,
make.Select(
left.pos,
left,
EQUALS_N).setType(typeOf(fun)).setSymbol(fun),
new Tree[]{right}).setType(defs.BOOLEAN_TYPE);
}
}
protected Tree ThrowMatchError(int pos, Type type) {
Symbol matchErrorModule = defs.SCALA.members().lookup(MATCHERROR_N);
outer: switch (typeOf(matchErrorModule)) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
for (int i = 0; i < alts.length; i++)
switch (alttypes[i]) {
case TypeRef(_, _, _):
matchErrorModule = alts[i];
break outer;
}
}
Symbol failMethod = typeOf(matchErrorModule).lookup(FAIL_N);
return
make.Apply(
pos,
make.TypeApply(
pos,
make.Select(
pos,
make.Select(
pos,
make.Ident(pos, Names.scala).setType(typeOf(defs.SCALA)).setSymbol(defs.SCALA),
MATCHERROR_N)
.setSymbol(matchErrorModule)
.setType(typeOf(matchErrorModule)),
FAIL_N).setType(typeOf(failMethod)).setSymbol(failMethod),
new Tree[]{gen.mkType(pos, type)})
.setType(((Type.PolyType) typeOf(failMethod)).result.subst(
typeOf(failMethod).typeParams(),
new Type[]{type})),
new Tree[]{
make.Literal(pos, unit.toString()).setType(defs.STRING_TYPE),
make.Literal(pos, new Integer(Position.line(pos))).setType(defs.INT_TYPE)
}).setType(type);
}
} |
// $OldId: AddInterfaces.java,v 1.40 2002/11/08 11:56:47 schinz Exp $
package scalac.transformer;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import Tree.*;
import java.util.*;
// TODO see why lambda-lifted functions end up in the interface
/**
* Add, for each class, an interface with the same name, to be used
* later by mixin expansion. More specifically:
*
* - at the end of the name of every class, the string "$class" is
* added,
*
* - an interface with the original name of the class is created, and
* contains all directly bound members of the class (as abstract
* members),
*
* - the interface is added to the mixin base classes of the class.
*
* @author Michel Schinz
* @version 1.0
*/
class AddInterfaces extends SubstTransformer {
/** Mapping from class symbols to their interface symbol. */
public final Map/*<Symbol,Symbol>*/ classToInterface;
protected final Map/*<Symbol,Symbol>*/ ifaceToClass;
protected final SymbolMapApplier ifaceToClassApplier;
protected final Map/*<Symbol,Symbol>*/ ifaceMemberToClass;
// Mapping from class symbol to its type parameters mapping.
protected final Map/*<Symbol,Map<Symbol,Symbol>>*/ typeParamsMaps;
// Mapping from a class member symbol to its value and type
// parameters mapping.
protected final Map/*<Symbol,Map<Symbol,Symbol>>*/ funParamsMaps;
protected final Set/*<Symbol>*/ createdIFaces = new HashSet();
public AddInterfaces(Global global, AddInterfacesPhase descr) {
super(global, global.make);
classToInterface = descr.classToInterface;
ifaceToClass = descr.interfaceToClass;
ifaceMemberToClass = descr.ifaceMemberToClass;
ifaceToClassApplier = new SymbolMapApplier(ifaceToClass);
typeParamsMaps = new HashMap();
funParamsMaps = new HashMap();
}
public void apply() {
// Phase 1: create all new symbols
ClassSymCreator creator = new ClassSymCreator(global);
for (int i = 0; i < global.units.length; ++i)
creator.traverse(global.units[i].body);
// Phase 2: transform the tree to add interfaces and use the
// new symbols where needed.
super.apply();
}
protected final static Tree.ValDef[][] EMPTY_PARAMS =
new Tree.ValDef[][]{ new Tree.ValDef[0] };
protected void uniqueName(Symbol sym, StringBuffer buf) {
Symbol owner = sym.owner();
if (owner != Symbol.NONE) {
uniqueName(owner, buf);
buf.append('$');
}
buf.append(sym.name.toString());
}
protected Name uniqueName(Symbol sym) {
StringBuffer buf = new StringBuffer();
uniqueName(sym, buf);
Name newName = Name.fromString(buf.toString());
if (sym.name.isTypeName()) return newName.toTypeName();
else if (sym.name.isConstrName()) return newName.toConstrName();
else return newName;
}
protected final static String CLASS_SUFFIX = "$class";
protected boolean hasClassSuffix(Name name) {
return name.toString().endsWith(CLASS_SUFFIX);
}
protected Name className(Name interfaceName) {
assert !hasClassSuffix(interfaceName) : interfaceName;
String interfaceStr = interfaceName.toString();
Name className = Name.fromString(interfaceStr + CLASS_SUFFIX);
if (interfaceName.isTypeName()) return className.toTypeName();
else if (interfaceName.isConstrName()) return className.toConstrName();
else return className;
}
// Modifiers added to interfaces
// TODO we should put ABSTRACT_CLASS too but that doesn't work now.
protected int INTERFACE_MODS = Modifiers.INTERFACE | Modifiers.STATIC;
// Modifiers for which we do not create interfaces.
protected int NO_INTERFACE_MODS =
(Modifiers.MODUL | Modifiers.SYNTHETIC | Modifiers.JAVA);
protected boolean needInterface(Symbol sym) {
return (sym != Symbol.NONE)
&& ((sym.primaryConstructorClass().flags & NO_INTERFACE_MODS) == 0);
}
protected boolean memberGoesInInterface(Symbol member) {
switch (member.kind) {
case Kinds.TYPE: case Kinds.ALIAS:
return true;
case Kinds.CLASS:
return needInterface(member);
case Kinds.VAL:
return member.isMethod() && !member.isPrimaryConstructor();
default:
throw Debug.abort("unknown kind: " + member.kind);
}
}
protected Type removeValueParams(Type tp) {
switch (tp) {
case MethodType(Symbol[] vparams, Type result):
return new Type.MethodType(Symbol.EMPTY_ARRAY, result);
case PolyType(Symbol[] tps, Type result):
return new Type.PolyType(tps, removeValueParams(result));
default:
return tp;
}
}
protected Tree mkAbstract(Tree tree) {
Symbol symbol = tree.symbol();
if (symbol.isMethod())
return gen.DefDef(symbol, Tree.Empty);
else switch (symbol.kind) {
case Kinds.TYPE: case Kinds.ALIAS:
return tree;
case Kinds.CLASS:
return classInterface((ClassDef)tree);
default:
throw new ApplicationError("invalid symbol kind for me", symbol);
}
}
protected Symbol getClassSym(Symbol ifaceSym) {
assert !hasClassSuffix(ifaceSym.name) : ifaceSym.name;
if (!needInterface(ifaceSym))
return ifaceSym;
else {
assert ifaceToClass.containsKey(ifaceSym);
return (Symbol)ifaceToClass.get(ifaceSym);
}
}
protected Symbol[] vparams(Type tp) {
switch (tp) {
case MethodType(Symbol[] vparams, _):
return vparams;
case PolyType(_, Type result):
return vparams(result);
case OverloadedType(_, _):
throw global.fail("can't get vparams of this type", tp);
default:
return Symbol.EMPTY_ARRAY;
}
}
protected Type cloneSymbolsInMethodType(Type type,
Symbol newOwner,
SymbolMapApplier smApplier,
Map symbolMap) {
switch (type) {
case NoType:
case ThisType(_):
case TypeRef(_, _, _):
case SingleType(_, _):
case CompoundType(_, _):
return type;
case MethodType(Symbol[] vparams, Type result): {
Symbol[] newVParams = new Symbol[vparams.length];
for (int i = 0; i < vparams.length; ++i) {
newVParams[i] = vparams[i].cloneSymbol();
newVParams[i].setOwner(newOwner);
newVParams[i].setType(smApplier.apply(newVParams[i].info()));
symbolMap.put(vparams[i], newVParams[i]);
}
return new Type.MethodType(newVParams,
cloneSymbolsInMethodType(result,
newOwner,
smApplier,
symbolMap));
}
case PolyType(Symbol[] tparams, Type result): {
Symbol[] newTParams = new Symbol[tparams.length];
for (int i = 0; i < tparams.length; ++i) {
newTParams[i] = tparams[i].cloneSymbol();
newTParams[i].setOwner(newOwner);
symbolMap.put(tparams[i], newTParams[i]);
}
return new Type.PolyType(newTParams,
cloneSymbolsInMethodType(result,
newOwner,
smApplier,
symbolMap));
}
default:
throw global.fail("unexpected method type: " + Debug.toString(type));
}
}
protected static class ThisTypeSubst {
Symbol fromSym;
Type toType;
ThisTypeSubst outer;
public ThisTypeSubst(Symbol fromSym, Type toType, ThisTypeSubst outer) {
this.fromSym = fromSym;
this.toType = toType;
this.outer = outer;
}
public Type apply(Type tp) {
switch (tp) {
case ThisType(Symbol sym):
if (sym == fromSym)
return toType;
else if (outer != null)
return outer.apply(tp);
else
return tp;
case TypeRef(Type pre, Symbol sym, Type[] args):
return new Type.TypeRef(apply(pre), sym, apply(args));
case SingleType(Type pre, Symbol sym):
return Type.singleType(apply(pre), sym);
case CompoundType(Type[] parts, Scope members):
return Type.compoundType(apply(parts), members, tp.symbol());
case MethodType(Symbol[] vparams, Type result):
return new Type.MethodType(vparams, apply(result));
case PolyType(Symbol[] tparams, Type result):
return new Type.PolyType(tparams, apply(result));
case OverloadedType(Symbol[] alts, Type[] alttypes):
return new Type.OverloadedType(alts, apply(alttypes));
case CovarType(Type t):
return new Type.CovarType(apply(t));
case NoType:
return tp;
default:
throw Debug.abort("unknown type",tp);
}
}
public Type[] apply(Type[] tps) {
Type[] newTps = new Type[tps.length];
for (int i = 0; i < newTps.length; ++i)
newTps[i] = apply(tps[i]);
return newTps;
}
}
// Return the interface corresponding to the given class.
protected Tree classInterface(ClassDef classDef) {
Template impl = classDef.impl;
Symbol ifaceSym = classDef.symbol();
// Create tree for interface.
List/*<Tree>*/ ifaceBody = new ArrayList();
Tree[] body = impl.body;
for (int i = 0; i < body.length; ++i) {
Tree elem = body[i];
if (elem.hasSymbol() && elem.symbol().owner() == ifaceSym) {
if (memberGoesInInterface(elem.symbol()))
ifaceBody.add(mkAbstract(elem));
}
}
Tree[] parentConstr =
gen.mkParentConstrs(impl.pos, ifaceSym.nextInfo().parents());
Template ifaceTmpl =
make.Template(impl.pos,
parentConstr,
(Tree[])ifaceBody.toArray(new Tree[ifaceBody.size()]));
ifaceTmpl.setSymbol(impl.symbol().cloneSymbol());
ifaceTmpl.setType(ifaceSym.nextInfo());
int ifaceMods = classDef.mods | INTERFACE_MODS;
ClassDef interfaceDef = (ClassDef)make.ClassDef(classDef.pos,
ifaceMods,
classDef.name,
classDef.tparams,
EMPTY_PARAMS,
classDef.tpe,
ifaceTmpl);
interfaceDef.setType(Type.NoType);
interfaceDef.setSymbol(ifaceSym);
createdIFaces.add(ifaceSym);
return interfaceDef;
}
protected Type fixClassSymbols(Type type) {
switch (type) {
case Type.NoType:
case ThisType(_):
return type;
case TypeRef(Type pre, Symbol sym, Type[] args):
return new Type.TypeRef(fixClassSymbols(pre), getClassSym(sym), args);
case SingleType(Type pre, Symbol sym):
return Type.singleType(fixClassSymbols(pre), sym);
case CompoundType(Type[] parts, Scope members):
return Type.compoundType(fixClassSymbols(parts),
members,
getClassSym(type.symbol()));
case MethodType(Symbol[] vparams, Type result):
return new Type.MethodType(vparams, fixClassSymbols(result));
case PolyType(Symbol[] tparams, Type result):
return new Type.PolyType(tparams, fixClassSymbols(result));
default:
throw global.fail("unexpected type ",type);
}
}
protected Type[] fixClassSymbols(Type[] types) {
Type[] newTypes = new Type[types.length];
for (int i = 0; i < types.length; ++i)
newTypes[i] = fixClassSymbols(types[i]);
return newTypes;
}
protected Tree fixClassSymbols(Tree tree) {
switch (tree) {
case Apply(Tree fun, Tree[] args):
return copy.Apply(tree, fixClassSymbols(fun), args);
case TypeApply(Tree fun, Tree[] args):
return copy.TypeApply(tree, fixClassSymbols(fun), args);
case Select(Tree qualifier, Name selector): {
Symbol classSym = getClassSym(tree.symbol());
return copy.Select(tree, qualifier, classSym.name).setSymbol(classSym);
}
case Ident(Name name): {
Symbol classSym = getClassSym(tree.symbol());
return copy.Ident(tree, classSym.name).setSymbol(classSym);
}
default:
throw global.fail("unexpected tree",tree);
}
}
protected LinkedList/*<List<Tree>>*/ bodyStack = new LinkedList();
protected ThisTypeSubst thisTypeSubst = null;
public Tree[] transform(Tree[] trees) {
List newTrees = new ArrayList();
bodyStack.addFirst(newTrees);
for (int i = 0; i < trees.length; ++i)
newTrees.add(transform(trees[i]));
bodyStack.removeFirst();
return (Tree[]) newTrees.toArray(new Tree[newTrees.size()]);
}
public TypeDef[] transform(TypeDef[] ts) {
return super.transform(ts);
}
public Tree transform(Tree tree) {
if (thisTypeSubst != null) {
if (tree.definesSymbol()) {
Symbol sym = tree.symbol();
sym.updateInfo(thisTypeSubst.apply(sym.nextInfo()));
}
tree.setType(thisTypeSubst.apply(tree.type()));
}
switch (tree) {
case ClassDef(int mods,
Name name,
TypeDef[] tparams,
ValDef[][] vparams,
Tree tpe,
Template impl) : {
global.log("adding interface for " + tree.symbol()
+ " (need one? " + needInterface(tree.symbol()) + ")");
Symbol interfaceSym = tree.symbol();
if (needInterface(interfaceSym)) {
ClassDef classDef = (ClassDef) tree;
// First insert interface for class in enclosing body...
if (! createdIFaces.contains(interfaceSym)) {
Tree interfaceDef = classInterface(classDef);
List/*<Tree>*/ enclosingBody = (List)bodyStack.getFirst();
enclosingBody.add(interfaceDef);
}
// ...then transform the class.
Symbol classSym = getClassSym(interfaceSym);
assert typeParamsMaps.containsKey(classSym) : classSym;
Map/*<Symbol,Symbol>*/ tparamsMap = (Map)typeParamsMaps.get(classSym);
SymbolMapApplier tparamsSM = new SymbolMapApplier(tparamsMap);
// Make the class implement the interface, and make sure
// to use class symbols for base classes.
Type interfaceBaseType = tparamsSM.apply(interfaceSym.type());
Type[] newBaseTypes;
// 1. modify type of class symbol
Type newClassInfo;
switch (classSym.nextInfo()) {
case CompoundType(Type[] baseTypes, Scope members): {
newBaseTypes = new Type[baseTypes.length + 1];
newBaseTypes[0] = fixClassSymbols(baseTypes[0]);
newBaseTypes[1] = interfaceBaseType;
for (int i = 2; i < newBaseTypes.length; ++i)
newBaseTypes[i] = fixClassSymbols(baseTypes[i-1]);
newClassInfo = Type.compoundType(newBaseTypes, members, classSym);
classSym.updateInfo(newClassInfo);
} break;
default:
throw global.fail("invalid info() for class", classSym);
}
// 2. modify tree accordingly
pushSymbolSubst(tparamsMap);
thisTypeSubst = new ThisTypeSubst(interfaceSym,
classSym.thisType(),
thisTypeSubst);
Tree[] parents = transform(impl.parents);
Tree[] newParents = new Tree[parents.length + 1];
newParents[0] = parents[0];
newParents[1] = gen.mkParentConstr(impl.pos, interfaceBaseType);
for (int i = 2; i < newParents.length; ++i)
newParents[i] = parents[i-1];
// Use new member symbols for class members.
Tree[] body = impl.body;
for (int i = 0; i < body.length; ++i) {
Tree member = body[i];
if (member.hasSymbol()) {
Symbol sym = member.symbol();
if (sym.kind != Kinds.CLASS
&& ifaceMemberToClass.containsKey(sym)) {
Symbol cSym = (Symbol)ifaceMemberToClass.get(sym);
member.setSymbol(cSym);
}
}
}
// Transform body
List newBody = new LinkedList();
for (int i = 0; i < body.length; ++i) {
switch (body[i]) {
case TypeDef(_, _, _):
break;
default:
newBody.add(transform(body[i]));
}
}
Template newImpl =
copy.Template(impl,
newParents,
(Tree[])newBody.toArray(new Tree[newBody.size()]));
newImpl.setType(newClassInfo);
Tree newTree =
copy.ClassDef(classDef,
classSym.flags,
classSym.name.toTypeName(),
transform(tparams),
transform(vparams),
transform(tpe),
newImpl)
.setSymbol(classSym);
thisTypeSubst = thisTypeSubst.outer;
popSymbolSubst();
return newTree;
} else {
// No interface needed, we just adapt the class type
// to use class symbols.
Symbol classSym = interfaceSym;
classSym.updateInfo(fixClassSymbols(classSym.info()));
return super.transform(tree);
}
}
case Template(Tree[] parents, Tree[] body): {
return copy.Template(tree, transform(parents), transform(body))
.setType(fixClassSymbols(tree.type));
}
case DefDef(_, _, _, _, _, _): {
Symbol sym = tree.symbol();
if (funParamsMaps.containsKey(sym)) {
Map funParamsMap = (Map)funParamsMaps.get(sym);
pushSymbolSubst(funParamsMap);
Tree newTree = super.transform(tree);
popSymbolSubst();
return newTree;
}
return super.transform(tree);
}
case ValDef(_, _, _, _): {
Symbol sym = tree.symbol();
Symbol owner = sym.owner();
if (!sym.isParameter() && ifaceMemberToClass.containsKey(owner)) {
Symbol newOwner = (Symbol)ifaceMemberToClass.get(owner);
sym.setOwner(newOwner);
global.log("new owner for " + Debug.show(sym) + " => " + newOwner);
}
return super.transform(tree);
}
case This(Ident qualifier): {
Symbol qualSym = qualifier.symbol();
if (needInterface(qualSym))
return gen.This(tree.pos, getClassSym(qualSym));
else
return super.transform(tree);
}
case Select(Super(_), Name selector): {
// Use class member symbol for "super" references.
Symbol sym = tree.symbol();
if (needInterface(sym.classOwner())) {
assert ifaceMemberToClass.containsKey(sym);
Symbol classSym = (Symbol)ifaceMemberToClass.get(sym);
return super.transform(tree).setSymbol(classSym);
} else
return super.transform(tree);
}
default: {
Tree newTree = super.transform(tree);
// Use class symbols for constructor calls.
switch (newTree) {
case New(Template templ):
return copy.New(newTree, templ)
.setType(templ.parents[0].type);
case Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs): {
Tree tFun = ((Tree.Apply)newTree).fun;
if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor())
return copy.Apply(newTree, tFun, vargs)
.setType(fixClassSymbols(newTree.type));
else
return newTree;
}
case Apply(Tree fun, Tree[] args): {
if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor()) {
fun.setSymbol(getClassSym(fun.symbol()));
fun.setType(fixClassSymbols(fun.type));
return (copy.Apply(newTree, super.syncTree(fun), args))
.setType(fixClassSymbols(newTree.type));
} else
return newTree;
}
case TypeApply(Tree fun, Tree[] args): {
if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor()) {
fun.setSymbol(getClassSym(fun.symbol()));
fun.setType(fixClassSymbols(fun.type));
return (copy.TypeApply(newTree, super.syncTree(fun), args))
.setType(fixClassSymbols(newTree.type));
} else
return newTree;
}
default:
return newTree;
}
}
}
}
// Class
protected class ClassSymCreator extends Traverser {
// Mapping from interface type parameters to class type
// parameters.
final HashMap/*<Symbol,Symbol>*/ tparamsMap = new HashMap();
public ClassSymCreator(Global global) {
super(global);
}
protected Symbol cloneAndMaybeRenameSymbol(Symbol sym) {
assert !sym.isPrimaryConstructor() : sym;
Symbol clone = sym.cloneSymbol();
if (clone.kind == Kinds.CLASS) {
clone.name = className(clone.name);
Symbol constrClone = clone.constructor();
constrClone.name = className(constrClone.name);
}
return clone;
}
protected void makeClassSymbol(Symbol ifaceSym) {
Symbol classSym = cloneAndMaybeRenameSymbol(ifaceSym);
ifaceToClass.put(ifaceSym, classSym);
ifaceToClass.put(ifaceSym.constructor(), classSym.constructor());
ifaceSym.owner().members().enter(classSym);
}
public void traverse(Tree tree) {
switch(tree) {
case ClassDef(_, _, _, _, _, Template impl): {
Symbol ifaceSym = tree.symbol();
if (!needInterface(ifaceSym)) {
super.traverse(impl);
break;
}
// The class needs an interface. Create new symbols
// for the class itself, its constructor, its type
// parameters and its members. Then modify what was
// the class symbol to turn it into an interface
// symbol.
// At the end of this part, one inconsistency remains:
// the base types of the new class symbols still refer
// to interface symbols. This is fixed later, when
// symbols exist for *all* classes.
Symbol ifaceConstrSym = ifaceSym.constructor();
ifaceConstrSym.updateInfo(removeValueParams(ifaceConstrSym.info()));
if (! ifaceToClass.containsKey(ifaceSym))
makeClassSymbol(ifaceSym);
Symbol classSym = (Symbol)ifaceToClass.get(ifaceSym);
Symbol classConstrSym = classSym.constructor();
if (ifaceToClass.containsKey(classSym.owner())) {
Symbol newOwner = (Symbol)ifaceToClass.get(classSym.owner());
classSym.setOwner(newOwner);
classConstrSym.setOwner(newOwner);
}
Symbol[] ifaceTParams = ifaceSym.typeParams();
if (ifaceTParams.length > 0) {
for (int i = 0; i < ifaceTParams.length; ++i) {
Symbol classTParam = ifaceTParams[i].cloneSymbol();
classTParam.setOwner(classConstrSym);
tparamsMap.put(ifaceTParams[i], classTParam);
}
}
assert !typeParamsMaps.containsKey(classSym);
Map cloneMap = new HashMap();
cloneMap.putAll(tparamsMap);
typeParamsMaps.put(classSym, cloneMap);
SymbolMapApplier tparamsSM = new SymbolMapApplier(cloneMap);
classConstrSym.setInfo(tparamsSM.apply(classConstrSym.info()));
Symbol[] vparams = vparams(classConstrSym.nextInfo());
for (int i = 0; i < vparams.length; ++i) {
vparams[i].setOwner(classConstrSym);
vparams[i].updateInfo(tparamsSM.apply(vparams[i].info()));
}
Scope newIFaceMembers = new Scope();
Scope classMembers = new Scope();
Scope.SymbolIterator symIt =
new Scope.UnloadIterator(ifaceSym.members().iterator());
while (symIt.hasNext()) {
Symbol ifaceMemberSym = symIt.next();
ifaceMemberSym.updateInfo(tparamsSM.apply(ifaceMemberSym.info()));
if (! memberGoesInInterface(ifaceMemberSym)) {
ifaceMemberSym.setOwner(classSym);
classMembers.enterOrOverload(ifaceMemberSym);
continue;
}
// When encountering a constructor of a nested
// class, clone its class to make sure the
// constructor is cloned correctly.
if (ifaceMemberSym.isPrimaryConstructor()
&& !ifaceToClass.containsKey(ifaceMemberSym)) {
makeClassSymbol(ifaceMemberSym.primaryConstructorClass());
}
// Make private members public and give them a
// unique name.
if (Modifiers.Helper.isPrivate(ifaceMemberSym.flags)) {
ifaceMemberSym.name = uniqueName(ifaceMemberSym);
ifaceMemberSym.flags ^= Modifiers.PRIVATE;
}
ifaceMemberSym.flags &= ~Modifiers.PROTECTED;
// Type members are moved to the interface.
// Therefore, no symbol has to be created for
// their class equivalent.
if (ifaceMemberSym.kind == Kinds.TYPE
|| ifaceMemberSym.kind == Kinds.ALIAS) {
newIFaceMembers.enterOrOverload(ifaceMemberSym);
continue;
}
if (Modifiers.Helper.isPrivate(ifaceMemberSym.flags)) {
ifaceMemberSym.name = uniqueName(ifaceMemberSym);
ifaceMemberSym.flags ^= Modifiers.PRIVATE;
}
ifaceMemberSym.flags &= ~Modifiers.PROTECTED;
Symbol classMemberSym;
if (ifaceToClass.containsKey(ifaceMemberSym))
classMemberSym = (Symbol)ifaceToClass.get(ifaceMemberSym);
else
classMemberSym = cloneAndMaybeRenameSymbol(ifaceMemberSym);
ifaceMemberSym.updateInfo(tparamsSM.apply(ifaceMemberSym.info()));
classMemberSym.setInfo(tparamsSM.apply(classMemberSym.info()));
Symbol[] vpms = vparams(ifaceMemberSym.nextInfo());
for (int p = 0; p < vpms.length; ++p)
vpms[p].updateInfo(tparamsSM.apply(vpms[p].info()));
// Clone parameter symbols for methods.
if (classMemberSym.isMethod()) {
Map funSymMap = new HashMap();
Type newInfo = cloneSymbolsInMethodType(classMemberSym.info(),
classMemberSym,
tparamsSM,
funSymMap);
if (! funSymMap.isEmpty())
funParamsMaps.put(classMemberSym, funSymMap);
}
classMemberSym.setOwner(classSym);
if (ifaceMemberSym.kind == Kinds.CLASS) {
ifaceToClass.put(ifaceMemberSym, classMemberSym);
ifaceToClass.put(ifaceMemberSym.constructor(),
classMemberSym.constructor());
} else {
ifaceMemberSym.flags |= Modifiers.DEFERRED;
ifaceMemberToClass.put(ifaceMemberSym, classMemberSym);
}
newIFaceMembers.enterOrOverload(ifaceMemberSym);
if (!ifaceMemberToClass.containsKey(ifaceMemberSym)
&& ifaceMemberSym.kind != Kinds.CLASS)
ifaceMemberToClass.put(ifaceMemberSym, classMemberSym);
classMembers.enterOrOverload(classMemberSym);
}
switch (classSym.info()) {
case CompoundType(Type[] parts, Scope members):
classSym.setInfo(Type.compoundType(tparamsSM.apply(parts),
classMembers,
classSym));
break;
default:
global.fail("unexpected type for class", ifaceSym.info());
}
Type cConstrType = classConstrSym.info();
classConstrSym.updateInfo(cConstrType.subst(new Symbol[]{ifaceSym},
new Symbol[]{classSym}));
ifaceSym.flags |= INTERFACE_MODS;
classToInterface.put(classSym, ifaceSym);
super.traverse(impl);
if (ifaceTParams.length > 0)
for (int i = 0; i < ifaceTParams.length; ++i)
tparamsMap.remove(ifaceTParams[i]);
// Remove Java classes from interface base classes.
switch (ifaceSym.info()) {
case CompoundType(Type[] basetypes, Scope members):
ArrayList newBT_L = new ArrayList(basetypes.length);
for (int i = 0; i < basetypes.length; ++i)
if (! basetypes[i].symbol().isJava())
newBT_L.add(basetypes[i]);
Type[] newBT;
if (newBT_L.size() != basetypes.length)
newBT = (Type[]) newBT_L.toArray(new Type[newBT_L.size()]);
else
newBT = basetypes;
ifaceSym.updateInfo(Type.compoundType(newBT,
newIFaceMembers,
ifaceSym));
break;
default:
Debug.abort("unexpected type for class", ifaceSym.info());
}
} break;
default:
super.traverse(tree);
}
}
}
} |
package com.rox.emu.p6502;
import com.rox.emu.UnknownOpCodeException;
import com.rox.emu.p6502.op.AddressingMode;
import com.rox.emu.p6502.op.OpCode;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* # - Memory
* $ - Value
*
* #$V - Immediate
* #VV - Accumulator
* $V / $ VV - Zero Page
* $V,X / $VV,X - Zero Page[X]
* $V,Y / $VV,Y - Zero Page[Y]
* $VVV / $VVVV - Absolute
* $VVV,X / $VVVV,X - Absolute[X]
* $VVV,Y / $VVVV,Y - Absolute[Y]
* ($V,X) / ($VV,X) - Indirect, X
* ($V),Y / ($VV),Y - Indirect, Y
*
* | $[ V_Z | V_ABS ] ]
*/
public class CompilerTest {
@Test
public void testImpliedInstructions(){
OpCode.streamOf(AddressingMode.IMPLIED).forEach((opcode)->{
Compiler compiler = new Compiler(opcode.getOpCodeName());
int[] bytes = compiler.getBytes();
assertEquals("Wrong byte value for " + opcode.getOpCodeName() + "(" + opcode.getByteValue() + ")", opcode.getByteValue(), bytes[0]);
});
}
@Test
public void testImmediateInstructions(){
OpCode.streamOf(AddressingMode.IMMEDIATE).forEach((opcode)->{
Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_PREFIX + "10");
int[] bytes = compiler.getBytes();
assertArrayEquals(new int[] {opcode.getByteValue(), 10}, bytes);
});
}
@Test
public void testZeroPageInstructions(){
//TODO Test single character argument
OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{
Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "10");
int[] bytes = compiler.getBytes();
assertArrayEquals(new int[] {opcode.getByteValue(), 10}, bytes);
});
}
@Test
public void testAbsoluteInstructions(){
//TODO test three character argument
OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{
Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "1234");
int[] bytes = compiler.getBytes();
assertArrayEquals(new int[] {opcode.getByteValue(), 1234}, bytes);
});
}
@Test
public void firstInvalidOpcode(){
Compiler compiler = new Compiler("ROX");
try {
compiler.getBytes();
fail("Exception expected, 'ROX' is an invalid OpCode");
}catch(UnknownOpCodeException e){
assertNotNull(e);
}
}
@Test
public void testInvalidValuePrefix(){
try {
Compiler compiler = new Compiler("ADC @$10");
int[] bytes = compiler.getBytes();
fail("Invalid argument structure should throw an exception but was " + Arrays.toString(bytes));
}catch (UnknownOpCodeException e){
assertFalse(e.getMessage().isEmpty());
assertFalse(e.getOpCode() == null);
}
}
} |
package de.voowoo.gameoflife;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class WorldTest
{
@Test
public void aliveCellWith2NeighborsShouldSurvive() throws Exception
{
assertThat(World.nextCellState(true, 2), is(true));
}
@Test
public void aliveCellWith3NeighborsShouldSurvive() throws Exception
{
assertThat(World.nextCellState(true, 3), is(true));
}
@Test
public void aliveCellWithMoreThan3NeighborsShouldDie() throws Exception
{
assertThat(World.nextCellState(true, 4), is(false));
}
@Test
public void deadCellWith2NeighborsShouldStayDead() throws Exception
{
assertThat(World.nextCellState(false, 2), is(false));
}
@Test
public void deadCellWith3NeighborsShouldBeRevived() throws Exception
{
assertThat(World.nextCellState(false, 3), is(true));
}
@Test
public void shouldCountNeighborsOfAliveCellInA3x3World() throws Exception
{
boolean[][] neighborhood = {{true, true, true},
{true, true, true},
{true, true, true}};
assertThat(World.countNeighbors(1, 1, neighborhood), is(8));
}
@Test
public void shouldCountNeighborsOfDeadCellInA3x3World() throws Exception
{
boolean[][] neighborhood = {{true, true, true},
{true, false, true},
{true, true, true}};
assertThat(World.countNeighbors(1, 1, neighborhood), is(8));
}
@Test
public void shouldCount0NeighborsInDead3x3World() throws Exception
{
boolean[][] neighborhood = {{false, false, false},
{false, false, false},
{false, false, false}};
assertThat(World.countNeighbors(1, 1, neighborhood), is(0));
}
@Test
public void shouldCount0NeighborsOnTheLeftSideInA4x3World() throws Exception
{
boolean[][] neighborhood = {{false, false, false},
{false, false, false},
{false, false, false},
{true, true, true}};
assertThat(World.countNeighbors(1, 1, neighborhood), is(0));
}
@Test
public void shouldCount0NeighborsOnTheRightSideInA4x3World() throws Exception
{
boolean[][] neighborhood = {{true, true, true},
{false, false, false},
{false, false, false},
{false, false, false}};
assertThat(World.countNeighbors(2, 1, neighborhood), is(0));
}
@Test
public void shouldCount8NeighborsOnTheRightSideInA6x3World() throws Exception
{
boolean[][] neighborhood = {{false, false, false},
{false, false, false},
{false, false, false},
{true, true, true},
{true, true, true},
{true, true, true}};
assertThat(World.countNeighbors(4, 1, neighborhood), is(8));
}
@Test
public void shouldCount0NeighborsInTheMiddleInA5x3World() throws Exception
{
boolean[][] neighborhood = {{true, true, true},
{false, false, false},
{false, false, false},
{false, false, false},
{true, true, true}};
assertThat(World.countNeighbors(2, 1, neighborhood), is(0));
}
@Test
public void shouldCount0NeighborsOnTheTopInA3x4World() throws Exception
{
boolean[][] neighborhood = {{false, false, false, true},
{false, false, false, true},
{false, false, false, true}};
assertThat(World.countNeighbors(1, 1, neighborhood), is(0));
}
@Test
public void shouldCount0NeighborsOnTheBottomInA3x4World() throws Exception
{
boolean[][] neighborhood = {{true, false, false, false},
{true, false, false, false},
{true, false, false, false}};
assertThat(World.countNeighbors(1, 2, neighborhood), is(0));
}
@Test
public void shouldCount8NeighborsOnTheBottomInA3x6World() throws Exception
{
boolean[][] neighborhood = {{false, false, false, true, true, true},
{false, false, false, true, true, true},
{false, false, false, true, true, true}};
assertThat(World.countNeighbors(1, 4, neighborhood), is(8));
}
@Test
public void shouldCount0NeighborsInTheMiddleOfA5x5World() throws Exception
{
boolean[][] neighborhood = {{true, true, true, true, true},
{true, false, false, false, true},
{true, false, false, false, true},
{true, false, false, false, true},
{true, true, true, true, true}};
assertThat(World.countNeighbors(2, 2, neighborhood), is(0));
}
@Test
public void shouldApplyRulesToA5x5World() throws Exception
{
World world = new World(new boolean[][]{{false, false, false, false, false},
{false, false, true, false, false},
{false, false, false, true, false},
{false, false, true, false, false},
{false, false, false, false, false}});
world.cycle();
assertThat(world, is(new World(new boolean[][]{{false, false, false, false, false},
{false, false, false, false, false},
{false, false, true, true, false},
{false, false, false, false, false},
{false, false, false, false, false}})));
}
@Test
public void worldShouldBlink() throws Exception
{
boolean[][] neighborhood = new boolean[][]{{false, false, false, false, false},
{false, false, false, false, false},
{false, true, true, true, false},
{false, false, false, false, false},
{false, false, false, false, false}};
assertThat(World.countNeighbors(2, 1, neighborhood), is(1));
World world = new World(new boolean[][]{{false, false, false, false, false},
{false, false, true, false, false},
{false, false, true, false, false},
{false, false, true, false, false},
{false, false, false, false, false}});
world.cycle();
assertThat(world, is(new World(new boolean[][]{{false, false, false, false, false},
{false, false, false, false, false},
{false, true, true, true, false},
{false, false, false, false, false},
{false, false, false, false, false}})));
world.cycle();
world = new World(new boolean[][]{{false, false, false, false, false},
{false, false, true, false, false},
{false, false, true, false, false},
{false, false, true, false, false},
{false, false, false, false, false}});
}
} |
package io.atom.electron;
import java.util.concurrent.Future;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.netbeans.junit.NbTestCase;
import org.openide.loaders.DataObject;
/**
*
* @author spindizzy
*/
public class RunActionTest extends NbTestCase {
private RunAction instance;
private TaskObserver taskObserver;
public RunActionTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
taskObserver = mock(TaskObserver.class);
instance = new RunAction(mock(DataObject.class)) {
@Override
String getFileDisplayName() {
return "test.js";
}
@Override
TaskObserver createObserver() {
return taskObserver;
}
};
}
/**
* Test of actionPerformed method, of class RunAction.
*/
@Test
public void testActionPerformed() {
instance.actionPerformed(null);
verify(taskObserver).observe(any(Future.class));
}
} |
package ru.job4j.lambda;
public class Attachment {
private String name;
private int size;
public Attachment(String name, int size) {
this.name = name;
this.size = size;
}
public String getName() {
return name;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return String.format("{name='%s', size=%d}",
name, size);
}
} |
package geeksforgeeks;
public class _01AmazonInterview_21_03 {
public static void main(String[] args) {
int distance[]={6,3,7};
int petrol[]={4,6,4};
startingPointLong(distance,petrol);
}
private static void startingPointLong(int[] distance, int[] petrol) {
for (int i = 0; i < petrol.length; i++) {//for forward propogation in circle
boolean exited=false;
int distanceValue=distance[i];
int petrolValue=petrol[i];
if(distanceValue>petrolValue){
continue;
}
int j=i;
int counter=0;
while(true && counter<distance.length){
counter++;
if(i==j){
j=(j+1)%(distance.length);
continue;
}
else{
if(distanceValue>petrolValue){
exited=true;
break;
}
else{
petrolValue=petrolValue-distanceValue;
distanceValue=0;
distanceValue=distance[j];
petrolValue+=petrol[j];
j=(j+1)%distance.length;
}
}
}
if(!exited)
{
System.out.println(i);
return;
}
}
System.out.println("No Path");
}
} |
package railo.runtime.engine;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.MemoryUsage;
import java.util.Map;
import railo.commons.io.IOUtil;
import railo.commons.io.SystemUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.filter.ExtensionResourceFilter;
import railo.commons.io.res.filter.ResourceFilter;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.SystemOut;
import railo.commons.lang.types.RefBoolean;
import railo.runtime.CFMLFactoryImpl;
import railo.runtime.Mapping;
import railo.runtime.MappingImpl;
import railo.runtime.PageSource;
import railo.runtime.PageSourcePool;
import railo.runtime.config.ConfigImpl;
import railo.runtime.config.ConfigServer;
import railo.runtime.config.ConfigServerImpl;
import railo.runtime.config.ConfigWeb;
import railo.runtime.config.ConfigWebImpl;
import railo.runtime.net.smtp.SMTPConnectionPool;
import railo.runtime.op.Caster;
import railo.runtime.type.scope.ScopeContext;
import railo.runtime.type.scope.client.ClientFile;
import railo.runtime.type.util.ArrayUtil;
/**
* own thread how check the main thread and his data
*/
public final class Controler extends Thread {
private int interval;
private long lastMinuteInterval=System.currentTimeMillis();
private long lastHourInterval=System.currentTimeMillis();
int maxPoolSize=500;
private final Map contextes;
private final RefBoolean run;
//private ScheduleThread scheduleThread;
private final ConfigServer configServer;
/**
* @param contextes
* @param interval
* @param run
*/
public Controler(ConfigServer configServer,Map contextes,int interval, RefBoolean run) {
this.contextes=contextes;
this.interval=interval;
this.run=run;
this.configServer=configServer;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
//scheduleThread.start();
boolean firstRun=true;
CFMLFactoryImpl factories[]=null;
while(run.toBooleanValue()) {
try {
sleep(interval);
}
catch (InterruptedException e) {
e.printStackTrace();
}
long now = System.currentTimeMillis();
//print.out("now:"+new Date(now));
boolean doMinute=lastMinuteInterval+60000<now;
if(doMinute)lastMinuteInterval=now;
boolean doHour=(lastHourInterval+(1000*60*60))<now;
if(doHour)lastHourInterval=now;
// broadcast cluster scope
factories=toFactories(factories,contextes);
try {
ScopeContext.getClusterScope(configServer,true).broadcast();
}
catch (Throwable t) {
t.printStackTrace();
}
monitor();
for(int i=0;i<factories.length;i++) {
run(factories[i], doMinute, doHour,firstRun);
}
if(factories.length>0)
firstRun=false;
}
}
private void monitor() {
Resource dir=((ConfigServerImpl)configServer).getMonitorDir();
Resource memory = touch(dir,"memory.bin",ConfigServerImpl._CF,ConfigServerImpl._01);
if(memory!=null);
//memory.isAbsolute();
}
private Resource touch(Resource dir, String name, byte first, byte second) {
Resource file = dir.getRealResource(name);
file.isAbsolute();
//if(file.length()>)
return null;
}
private CFMLFactoryImpl[] toFactories(CFMLFactoryImpl[] factories,Map contextes) {
if(factories==null || factories.length!=contextes.size())
factories=(CFMLFactoryImpl[]) contextes.values().toArray(new CFMLFactoryImpl[contextes.size()]);
return factories;
}
private void run(CFMLFactoryImpl cfmlFactory, boolean doMinute, boolean doHour, boolean firstRun) {
try {
boolean isRunning=cfmlFactory.getUsedPageContextLength()>0;
if(isRunning) {
cfmlFactory.checkTimeout();
}
ConfigWeb config = null;
if(firstRun) {
if(config==null) {
config = cfmlFactory.getConfig();
ThreadLocalConfig.register(config);
}
config.reloadTimeServerOffset();
checkOldClientFile(config);
//try{checkStorageScopeFile(config,Session.SCOPE_CLIENT);}catch(Throwable t){}
//try{checkStorageScopeFile(config,Session.SCOPE_SESSION);}catch(Throwable t){}
try{config.reloadTimeServerOffset();}catch(Throwable t){}
try{checkTempDirectorySize(config);}catch(Throwable t){}
try{checkCacheFileSize(config);}catch(Throwable t){}
try{cfmlFactory.getScopeContext().clearUnused();}catch(Throwable t){}
}
if(config==null) {
config = cfmlFactory.getConfig();
ThreadLocalConfig.register(config);
}
//try{cfmlFactory.getScopeContext().clearUnused();}catch(Throwable t){}
//every Minute
if(doMinute) {
if(config==null) {
config = cfmlFactory.getConfig();
ThreadLocalConfig.register(config);
}
// clear unused DB Connections
try{((ConfigImpl)config).getDatasourceConnectionPool().clear();}catch(Throwable t){}
// clear all unused scopes
try{cfmlFactory.getScopeContext().clearUnused();}catch(Throwable t){}
// Memory usage
// clear Query Cache
try{cfmlFactory.getQueryCache().clearUnused();}catch(Throwable t){}
// contract Page Pool
try{doClearPagePools((ConfigWebImpl) config);}catch(Throwable t){}
try{doClearClassLoaders((ConfigWebImpl) config);}catch(Throwable t){}
try{doCheckMappings(config);}catch(Throwable t){}
try{doClearMailConnections();}catch(Throwable t){}
}
// every hour
if(doHour) {
if(config==null) {
config = cfmlFactory.getConfig();
ThreadLocalConfig.register(config);
}
// time server offset
try{config.reloadTimeServerOffset();}catch(Throwable t){}
// check file based client/session scope
//try{checkStorageScopeFile(config,Session.SCOPE_CLIENT);}catch(Throwable t){}
//try{checkStorageScopeFile(config,Session.SCOPE_SESSION);}catch(Throwable t){}
// check temp directory
try{checkTempDirectorySize(config);}catch(Throwable t){}
// check cache directory
try{checkCacheFileSize(config);}catch(Throwable t){}
}
}
catch(Throwable t){
}
finally{
ThreadLocalConfig.release();
}
}
private void doClearMailConnections() {
SMTPConnectionPool.closeSessions();
}
private void checkOldClientFile(ConfigWeb config) {
ExtensionResourceFilter filter = new ExtensionResourceFilter(".script",false);
// move old structured file in new structure
try {
Resource dir = config.getClientScopeDir(),trgres;
Resource[] children = dir.listResources(filter);
String src,trg;
int index;
for(int i=0;i<children.length;i++) {
src=children[i].getName();
index=src.indexOf('-');
trg=ClientFile.getFolderName(src.substring(0,index), src.substring(index+1),false);
trgres=dir.getRealResource(trg);
if(!trgres.exists()){
trgres.createFile(true);
ResourceUtil.copy(children[i],trgres);
}
//children[i].moveTo(trgres);
children[i].delete();
}
} catch (Throwable t) {}
}
private void checkCacheFileSize(ConfigWeb config) {
checkSize(config,config.getCacheDir(),config.getCacheDirSize(),new ExtensionResourceFilter(".cache"));
}
private void checkTempDirectorySize(ConfigWeb config) {
checkSize(config,config.getTempDirectory(),1024*1024*1024,null);
}
private void checkSize(ConfigWeb config,Resource dir,long maxSize, ResourceFilter filter) {
if(!dir.exists()) return;
Resource res=null;
int count=ArrayUtil.size(filter==null?dir.list():dir.list(filter));
long size=ResourceUtil.getRealSize(dir,filter);
PrintWriter out = config.getOutWriter();
SystemOut.printDate(out,"check size of directory ["+dir+"]");
SystemOut.printDate(out,"- current size ["+size+"]");
SystemOut.printDate(out,"- max size ["+maxSize+"]");
int len=-1;
while(count>100000 || size>maxSize) {
Resource[] files = filter==null?dir.listResources():dir.listResources(filter);
if(len==files.length) break;// protect from inifinti loop
len=files.length;
for(int i=0;i<files.length;i++) {
if(res==null || res.lastModified()>files[i].lastModified()) {
res=files[i];
}
}
if(res!=null) {
size-=res.length();
try {
res.remove(true);
count
} catch (IOException e) {
SystemOut.printDate(out,"cannot remove resource "+res.getAbsolutePath());
break;
}
}
res=null;
}
}
private void doCheckMappings(ConfigWeb config) {
Mapping[] mappings = config.getMappings();
for(int i=0;i<mappings.length;i++) {
Mapping mapping = mappings[i];
mapping.check();
}
}
private void doClearPagePools(ConfigWebImpl config) {
PageSourcePool[] pools=getPageSourcePools(config);
int poolSize=getPageSourcePoolSize(pools);
long start =System.currentTimeMillis();
int startsize=poolSize;
while(poolSize>maxPoolSize) {
removeOldest(pools);
poolSize
}
if(startsize>poolSize)
SystemOut.printDate(config.getOutWriter(),"contract pagepools from "+startsize+" to "+poolSize +" in "+(System.currentTimeMillis()-start)+" millis");
}
private void doClearClassLoaders(ConfigWebImpl config) {
MemoryUsage pg = SystemUtil.getPermGenSpaceSize();
if((pg.getMax()-pg.getUsed())<1024*1024) {
SystemOut.printDate(config.getOutWriter(),"Free Perm Gen Space is less than 1mb (used:"+(pg.getUsed()/1024)+"kb;free:"+((pg.getMax()-pg.getUsed())/1024)+"kb), reset all template classloaders");
clearClassLoaders(config.getMappings());
clear(getPageSourcePools(config.getMappings()));
clearClassLoaders(config.getComponentMappings());
clear(getPageSourcePools(config.getComponentMappings()));
clearClassLoaders(config.getCustomTagMappings());
clear(getPageSourcePools(config.getCustomTagMappings()));
clearClassLoaders(config.getFunctionMapping());
clear(getPageSourcePools(config.getFunctionMapping()));
clearClassLoaders(config.getServerFunctionMapping());
clear(getPageSourcePools(config.getServerFunctionMapping()));
clearClassLoaders(config.getServerTagMapping());
clear(getPageSourcePools(config.getServerTagMapping()));
clearClassLoaders(config.getTagMapping());
clear(getPageSourcePools(config.getTagMapping()));
}
}
private void clearClassLoaders(Mapping... mappings) {
for(int i=0;i<mappings.length;i++){
try {
mappings[i].getClassLoaderForPhysical(true);
} catch (IOException e) {}
}
}
private PageSourcePool[] getPageSourcePools(ConfigWeb config) {
return getPageSourcePools(config.getMappings());
}
private PageSourcePool[] getPageSourcePools(Mapping... mappings) {
PageSourcePool[] pools=new PageSourcePool[mappings.length];
int size=0;
for(int i=0;i<mappings.length;i++) {
pools[i]=((MappingImpl)mappings[i]).getPageSourcePool();
size+=pools[i].size();
}
return pools;
}
private int getPageSourcePoolSize(PageSourcePool[] pools) {
int size=0;
for(int i=0;i<pools.length;i++)size+=pools[i].size();
return size;
}
private void removeOldest(PageSourcePool[] pools) {
PageSourcePool pool=null;
Object key=null;
PageSource ps=null;
long date=-1;
for(int i=0;i<pools.length;i++) {
try {
Object[] keys=pools[i].keys();
for(int y=0;y<keys.length;y++) {
ps = pools[i].getPageSource(keys[y],false);
if(date==-1 || date>ps.getLastAccessTime()) {
pool=pools[i];
key=keys[y];
date=ps.getLastAccessTime();
}
}
}
catch(Throwable t) {
pools[i].clear();
}
}
if(pool!=null)pool.remove(key);
}
private void clear(PageSourcePool[] pools) {
for(int i=0;i<pools.length;i++) {
pools[i].clear();
}
}
/*private void doLogMemoryUsage(ConfigWeb config) {
if(config.logMemoryUsage()&& config.getMemoryLogger()!=null)
config.getMemoryLogger().write();
}*/
static class ExpiresFilter implements ResourceFilter {
private long time;
private boolean allowDir;
public ExpiresFilter(long time, boolean allowDir) {
this.allowDir=allowDir;
this.time=time;
}
public boolean accept(Resource res) {
if(res.isDirectory()) return allowDir;
// load content
String str=null;
try {
str = IOUtil.toString(res,"UTF-8");
}
catch (IOException e) {
return false;
}
int index=str.indexOf(':');
if(index!=-1){
long expires=Caster.toLongValue(str.substring(0,index),-1L);
// check is for backward compatibility, old files have no expires date inside. they do ot expire
if(expires!=-1) {
if(expires<System.currentTimeMillis()){
return true;
}
else {
str=str.substring(index+1);
return false;
}
}
}
// old files not having a timestamp inside
else if(res.lastModified()<=time) {
return true;
}
return false;
}
}
} |
package fitnesse.junit;
import java.io.File;
import org.junit.Test;
import static org.junit.Assert.*;
public class FitNesseSuiteArgumentsTest {
@Test
public void argumentsAreParsedCorrectly() throws Exception {
System.setProperty("fitnesse.root.dir.parent", ".");
FitNesseSuite suite = new FitNesseSuite(FitNesseSuiteTest.class);
assertEquals(".", suite.getFitNesseDir(FitNesseSuiteExampleTest.class));
assertEquals(new File(System.getProperty("fitnesse.root.dir.parent")).getAbsolutePath(), suite.getFitNesseDir(FitNesseSuiteExampleFromPropertiesTest.class));
assertEquals("FitNesse.SuiteAcceptanceTests.SuiteSlimTests", suite.getSuiteName(FitNesseSuiteExampleTest.class));
assertEquals("tmp",suite.getOutputDir(FitNesseSuiteExampleTest.class));
assertEquals(new File(System.getProperty("java.io.tmpdir"),"fitnesse").getAbsolutePath(),suite.getOutputDir(FitNesseSuiteExampleFromPropertiesTest.class));
assertNull("null filter allowed", suite.getSuiteFilter(FitNesseSuiteExampleTest.class));
assertNull("null exclude filter allowed", suite.getExcludeSuiteFilter(FitNesseSuiteExampleTest.class));
assertEquals("testSuite", suite.getSuiteFilter(FitNesseSuiteWithFilterExampleTest.class));
assertEquals("excludedSuite", suite.getExcludeSuiteFilter(FitNesseSuiteWithFilterExampleTest.class));
assertEquals(true, suite.useDebugMode(FitNesseSuiteExampleTest.class));
assertEquals(true, suite.useDebugMode(FitNesseSuiteWithFilterExampleTest.class));
assertEquals(false, suite.useDebugMode(FitNesseSuiteExampleTestNoDebug.class));
}
} |
package raptor.swt.chess.controller;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import raptor.Raptor;
import raptor.connector.Connector;
import raptor.game.Game;
import raptor.game.GameConstants;
import raptor.game.Move;
import raptor.game.Result;
import raptor.game.util.GameUtils;
import raptor.pref.PreferenceKeys;
import raptor.service.SoundService;
import raptor.service.GameService.GameServiceAdapter;
import raptor.service.GameService.GameServiceListener;
import raptor.swt.SWTUtils;
import raptor.swt.chess.BoardUtils;
import raptor.swt.chess.ChessBoardController;
/**
* The controller used when a user is playing a game. Supports premove,queued
* premove, and auto draw. game.getWhiteName() or game.getBlackName() must match
* connector.getUserName().
*
* When a game is no longer active, this controller swaps itself out with the
* Inactive controller.
*
*/
public class PlayingController extends ChessBoardController {
/**
* A class containing the details of a premove.
*/
protected static class PremoveInfo {
int fromPiece;
int fromSquare;
int promotionColorlessPiece;
int toPiece;
int toSquare;
}
static final Log LOG = LogFactory.getLog(PlayingController.class);
protected Connector connector;
protected boolean isUserWhite;
protected GameServiceListener listener = new GameServiceAdapter() {
@Override
public void droppablePiecesChanged(Game game) {
if (!isDisposed() && game.getId().equals(getGame().getId())) {
board.getDisplay().asyncExec(new Runnable() {
public void run() {
refreshBoard();
}
});
}
}
@Override
public void gameInactive(Game game) {
if (!isDisposed() && game.getId().equals(getGame().getId())) {
board.getDisplay().asyncExec(new Runnable() {
public void run() {
try {
board.redrawSquares();
onPlayGameEndSound();
// Now swap controllers to the inactive controller.
InactiveController inactiveController = new InactiveController(
getGame());
getBoard().setController(inactiveController);
inactiveController.setBoard(board);
inactiveController
.setItemChangedListeners(itemChangedListeners);
// Detatch from the GameService.
connector.getGameService()
.removeGameServiceListener(listener);
// Clear the cool bar and init the inactive
// controller.
// board.clearCoolbar();
inactiveController.init();
// Set the listeners to null so they wont get
// cleared and we wont get notified.
setItemChangedListeners(null);
// Fire item changed from the inactive controller
// so they tab information gets adjusted.
inactiveController.fireItemChanged();
// And finally dispose.
PlayingController.this.dispose();
} catch (Throwable t) {
connector.onError("PlayingController.gameInactive",
t);
}
}
});
}
}
@Override
public void gameStateChanged(Game game, final boolean isNewMove) {
if (!isDisposed() && game.getId().equals(getGame().getId())) {
board.getDisplay().asyncExec(new Runnable() {
public void run() {
try {
if (isNewMove) {
handleAutoDraw();
if (!makePremove()) {
board.unhighlightAllSquares();
refresh();
}
} else {
refresh();
}
onPlayMoveSound();
} catch (Throwable t) {
connector.onError(
"PlayingController.gameStateChanged", t);
}
}
});
}
}
@Override
public void illegalMove(Game game, final String move) {
if (!isDisposed() && game.getId().equals(getGame().getId())) {
board.getDisplay().asyncExec(new Runnable() {
public void run() {
try {
adjustForIllegalMove(move, true);
} catch (Throwable t) {
connector.onError("PlayingController.illegalMove",
t);
}
}
});
}
}
};
protected int movingPiece;
protected List<PremoveInfo> premoves = Collections
.synchronizedList(new ArrayList<PremoveInfo>(10));
protected Random random = new SecureRandom();
protected ToolBar toolbar;
/**
* Creates a playing controller. One of the players white or black playing
* the game must match the name of connector.getUserName.
*
* @param game
* The game to control.
* @param connector
* The backing connector.
*/
public PlayingController(Game game, Connector connector) {
super(game);
this.connector = connector;
if (StringUtils.equalsIgnoreCase(game.getWhiteName(), connector
.getUserName())) {
isUserWhite = true;
} else if (StringUtils.equalsIgnoreCase(game.getBlackName(), connector
.getUserName())) {
isUserWhite = false;
} else {
throw new IllegalArgumentException(
"Could not deterimne user color " + connector.getUserName()
+ " " + game.getWhiteName() + " "
+ game.getBlackName());
}
if (LOG.isDebugEnabled()) {
LOG.debug("isUserWhite=" + isUserWhite);
}
}
public void adjustForIllegalMove(int from, int to, boolean adjustClocks) {
if (LOG.isDebugEnabled()) {
LOG.debug("adjustForIllegalMove ");
}
if (!getPreferences().getBoolean(
PreferenceKeys.BOARD_QUEUED_PREMOVE_ENABLED)) {
onClearPremoves();
}
board.unhighlightAllSquares();
if (adjustClocks) {
refresh();
} else {
refreshBoard();
}
try {
board.getStatusLabel().setText(
"Illegal Move: "
+ GameUtils.getPseudoSan(getGame(), from, to));
} catch (IllegalArgumentException iae) {
board.getStatusLabel().setText(
"Illegal Move: " + GameUtils.getSan(from) + "-"
+ GameUtils.getSan(to));
}
SoundService.getInstance().playSound("illegalMove");
}
public void adjustForIllegalMove(String move, boolean adjustClocks) {
if (LOG.isDebugEnabled()) {
LOG.debug("adjustForIllegalMove ");
}
if (!getPreferences().getBoolean(
PreferenceKeys.BOARD_QUEUED_PREMOVE_ENABLED)) {
onClearPremoves();
}
board.unhighlightAllSquares();
if (adjustClocks) {
refresh();
} else {
refreshBoard();
}
board.getStatusLabel().setText("Illegal Move: " + move);
SoundService.getInstance().playSound("illegalMove");
}
@Override
public void adjustGameDescriptionLabel() {
board.getGameDescriptionLabel().setText(
"Playing " + getGame().getEvent());
}
/**
* Adds all premoves to the premoves label. Also updates the clear premove
* button if there are moves in the premove queue.
*/
@Override
protected void adjustPremoveLabel() {
String labelText = "Premoves: ";
synchronized (premoves) {
boolean hasAddedPremove = false;
for (PremoveInfo info : premoves) {
String premove = ""
+ GameUtils.getPseudoSan(info.fromPiece, info.toPiece,
info.fromSquare, info.toSquare);
if (!hasAddedPremove) {
labelText += premove;
} else {
labelText += " , " + premove;
}
hasAddedPremove = true;
}
}
board.getCurrentPremovesLabel().setText(labelText);
}
/**
* Invoked when the user tries to start a dnd or click click move operation
* on the board. This method returns false if its not allowed.
*
* For non premoven you can only move one of your pieces when its your move.
* If the game is droppable you can drop from the piece jail, otherwise you
* can't.
*
* If premove is enabled you are allowed to move your pieces when it is not
* your move.
*/
@Override
public boolean canUserInitiateMoveFrom(int squareId) {
if (LOG.isDebugEnabled()) {
LOG.debug("canUserInitiateMoveFrom " + GameUtils.getSan(squareId));
}
if (!isUsersMove()) {
if (isPremoveable()) {
if (getGame().isInState(Game.DROPPABLE_STATE)
&& BoardUtils.isPieceJailSquare(squareId)) {
return isUserWhite
&& BoardUtils.isJailSquareWhitePiece(squareId)
|| !isUserWhite
&& BoardUtils.isJailSquareBlackPiece(squareId);
} else {
return isUserWhite
&& GameUtils.isWhitePiece(getGame(), squareId)
|| !isUserWhite
&& GameUtils.isBlackPiece(game, squareId);
}
}
return false;
} else if (BoardUtils.isPieceJailSquare(squareId)
&& !getGame().isInState(Game.DROPPABLE_STATE)) {
return false;
} else if (getGame().isInState(Game.DROPPABLE_STATE)
&& BoardUtils.isPieceJailSquare(squareId)) {
return isUserWhite && BoardUtils.isJailSquareWhitePiece(squareId)
|| !isUserWhite
&& BoardUtils.isJailSquareBlackPiece(squareId);
} else {
return isUserWhite && GameUtils.isWhitePiece(getGame(), squareId)
|| !isUserWhite && GameUtils.isBlackPiece(game, squareId);
}
}
@Override
public boolean confirmClose() {
if (connector.isConnected()) {
boolean result = Raptor.getInstance().confirm(
"Closing a game you are playing will result in resignation of the game."
+ ". Do you wish to proceed?");
if (result) {
connector.onResign(getGame());
}
return result;
} else {
return true;
}
}
@Override
public void dispose() {
connector.getGameService().removeGameServiceListener(listener);
super.dispose();
if (toolbar != null) {
toolbar.setVisible(false);
SWTUtils.clearToolbar(toolbar);
toolbar = null;
}
}
public Connector getConnector() {
return connector;
}
@Override
public String getTitle() {
return connector.getShortName() + "(Play " + getGame().getId() + ")";
}
@Override
public Control getToolbar(Composite parent) {
if (toolbar == null) {
toolbar = new ToolBar(parent, SWT.FLAT);
BoardUtils.addPromotionIconsToToolbar(this, toolbar, isUserWhite);
new ToolItem(toolbar, SWT.SEPARATOR);
BoardUtils.addPremoveClearAndAutoDrawToolbar(this, toolbar);
new ToolItem(toolbar, SWT.SEPARATOR);
BoardUtils.addNavIconsToToolbar(this, toolbar, false, false);
new ToolItem(toolbar, SWT.SEPARATOR);
} else if (toolbar.getParent() != parent) {
toolbar.setParent(parent);
}
setToolItemSelected(ToolBarItemKey.AUTO_QUEEN, true);
return toolbar;
}
/**
* If auto draw is enabled, a draw request is sent. This method should be
* invoked when receiving a move and right after sending one.
*
* In the future this will become smarter and only draw when the game shows
* a draw by three times in the same position or 50 move draw rule.
*/
protected void handleAutoDraw() {
if (isToolItemSelected(ToolBarItemKey.AUTO_DRAW)) {
getConnector().onDraw(getGame());
}
}
@Override
public void init() {
board.setWhiteOnTop(!isUserWhite());
/**
* In Droppable games (bughouse/crazyhouse) you own your own piece jail
* since you can drop pieces from it.
*
* In other games its just a collection of pieces yu have captured so
* your opponent owns your piece jail.
*/
if (getGame().isInState(Game.DROPPABLE_STATE)) {
board.setWhitePieceJailOnTop(board.isWhiteOnTop() ? true : false);
} else {
board.setWhitePieceJailOnTop(board.isWhiteOnTop() ? false : true);
}
refresh();
onPlayGameStartSound();
// Since the game object is updated while the game is being created,
// there
// is no risk of missing game events. We will pick them up when we get
// the position
// of the game since it will always be udpated.
connector.getGameService().addGameServiceListener(listener);
}
/**
* Returns true if the premove preference is enabled.
*/
public boolean isPremoveable() {
return Raptor.getInstance().getPreferences().getBoolean(
PreferenceKeys.BOARD_PREMOVE_ENABLED);
}
public boolean isUsersMove() {
return isUserWhite() && game.isWhitesMove() || !isUserWhite()
&& !game.isWhitesMove();
}
public boolean isUserWhite() {
return isUserWhite;
}
/**
* Runs through the premove queue and tries to make each move. If a move
* succeeds it is made and the rest of the queue is left intact. If a move
* fails it is removed from the queue and the next move is tried.
*
* If a move succeeded true is returned, otherwise false is returned.
*/
protected boolean makePremove() {
synchronized (premoves) {
for (PremoveInfo info : premoves) {
Move move = null;
try {
if (info.promotionColorlessPiece == EMPTY) {
move = game.makeMove(info.fromSquare, info.toSquare);
} else {
move = game.makeMove(info.fromSquare, info.toSquare,
info.promotionColorlessPiece);
}
getConnector().makeMove(getGame(), move);
premoves.remove(info);
handleAutoDraw();
refreshForMove(move);
return true;
} catch (IllegalArgumentException iae) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid premove trying next one in queue.",
iae);
}
premoves.remove(info);
}
}
}
premoves.clear();
adjustPremoveLabel();
return false;
}
public void onClearPremoves() {
premoves.clear();
adjustPremoveLabel();
}
protected void onPlayGameEndSound() {
if (isUserWhite() && game.getResult() == Result.WHITE_WON) {
SoundService.getInstance().playSound("win");
} else if (!isUserWhite() && game.getResult() == Result.BLACK_WON) {
SoundService.getInstance().playSound("win");
} else if (isUserWhite() && game.getResult() == Result.BLACK_WON) {
SoundService.getInstance().playSound("lose");
} else if (!isUserWhite() && game.getResult() == Result.WHITE_WON) {
SoundService.getInstance().playSound("lose");
} else {
SoundService.getInstance().playSound("obsGameEnd");
}
}
protected void onPlayGameStartSound() {
SoundService.getInstance().playSound("gameStart");
}
protected void onPlayIllegalMoveSound() {
SoundService.getInstance().playSound("illegalMove");
}
protected void onPlayMoveSound() {
SoundService.getInstance().playSound("move");
}
@Override
public void onToolbarButtonAction(ToolBarItemKey key, String... args) {
switch (key) {
case FEN:
Raptor.getInstance().promptForText(
"FEN for game " + game.getWhiteName() + " vs "
+ game.getBlackName(), game.toFEN());
break;
case FLIP:
onFlip();
break;
case CLEAR_PREMOVES:
onClearPremoves();
}
}
/**
* Invoked when the user cancels an initiated move. All squares are
* unhighlighted and the board is adjusted back to the game so any pieces
* removed in userInitiatedMove will be added back.
*/
@Override
public void userCancelledMove(int fromSquare, boolean isDnd) {
if (isDisposed()) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("userCancelledMove " + GameUtils.getSan(fromSquare)
+ " is drag and drop=" + isDnd);
}
board.unhighlightAllSquares();
movingPiece = EMPTY;
refresh();
onPlayIllegalMoveSound();
}
/**
* Invoked when the user initiates a move from a square. The square becomes
* highlighted and if its a DND move the piece is removed.
*/
@Override
public void userInitiatedMove(int square, boolean isDnd) {
if (LOG.isDebugEnabled()) {
LOG.debug("userInitiatedMove " + GameUtils.getSan(square)
+ " is drag and drop=" + isDnd);
}
if (!isDisposed() && board.getSquare(square).getPiece() != EMPTY) {
board.unhighlightAllSquares();
board.getSquare(square).highlight();
movingPiece = board.getSquare(square).getPiece();
if (isDnd && !BoardUtils.isPieceJailSquare(square)) {
board.getSquare(square).setPiece(GameConstants.EMPTY);
}
board.redrawSquares();
}
}
/**
* Invoked when a user makes a dnd move or a click click move on the
* chessboard.
*/
@Override
public void userMadeMove(int fromSquare, int toSquare) {
if (isDisposed()) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("userMadeMove " + getGame().getId() + " "
+ GameUtils.getSan(fromSquare) + " "
+ GameUtils.getSan(toSquare));
}
if (movingPiece == 0) {
LOG.error("movingPiece is 0 this should never happen.",
new Exception());
return;
}
long startTime = System.currentTimeMillis();
board.unhighlightAllSquares();
if (isUsersMove()) {
// Non premoves flow through here
if (fromSquare == toSquare
|| BoardUtils.isPieceJailSquare(toSquare)) {
if (LOG.isDebugEnabled()) {
LOG
.debug("User tried to make a move where from square == to square or toSquar was the piece jail.");
}
adjustForIllegalMove(fromSquare, toSquare, false);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processing user move..");
}
Move move = null;
if (GameUtils.isPromotion(getGame(), fromSquare, toSquare)) {
move = BoardUtils.createMove(getGame(), fromSquare, toSquare,
getAutoPromoteSelection());
} else {
move = BoardUtils.createMove(getGame(), fromSquare, toSquare);
}
if (move == null) {
adjustForIllegalMove(fromSquare, toSquare, false);
} else {
board.getSquare(fromSquare).highlight();
board.getSquare(toSquare).highlight();
if (game.move(move)) {
board.getSquare(fromSquare).setPiece(movingPiece);
refreshForMove(move);
connector.makeMove(game, move);
} else {
connector.onError(
"Game.move returned false for a move that should have been legal.Move: "
+ move + ".", new Throwable(getGame()
.toString()));
adjustForIllegalMove(move.toString(), false);
}
}
} else if (isPremoveable()) {
// Premove logic flows through here
if (fromSquare == toSquare
|| BoardUtils.isPieceJailSquare(toSquare)) {
// No need to check other conditions they are checked in
// canUserInitiateMoveFrom
if (LOG.isDebugEnabled()) {
LOG
.debug("User tried to make a premove that failed immediate validation.");
}
adjustForIllegalMove(fromSquare, toSquare, false);
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processing premove.");
}
PremoveInfo premoveInfo = new PremoveInfo();
premoveInfo.fromSquare = fromSquare;
premoveInfo.toSquare = toSquare;
premoveInfo.fromPiece = movingPiece;
premoveInfo.toPiece = board.getSquare(toSquare).getPiece();
premoveInfo.promotionColorlessPiece = GameUtils.isPromotion(
isUserWhite(), getGame(), fromSquare, toSquare) ? getAutoPromoteSelection()
: EMPTY;
board.getSquare(fromSquare).setPiece(movingPiece);
/**
* In queued premove mode you can have multiple premoves so just add
* it to the queue. In non queued premove you can have only one, so
* always clear out the queue before adding new moves.
*/
if (!getPreferences().getBoolean(
PreferenceKeys.BOARD_QUEUED_PREMOVE_ENABLED)) {
premoves.clear();
premoves.add(premoveInfo);
adjustPremoveLabel();
board.unhighlightAllSquares();
board.getSquare(premoveInfo.fromSquare).highlight();
board.getSquare(premoveInfo.toSquare).highlight();
refreshBoard();
} else {
premoves.add(premoveInfo);
board.getSquare(premoveInfo.fromSquare).highlight();
board.getSquare(premoveInfo.toSquare).highlight();
adjustPremoveLabel();
refreshBoard();
}
}
// Clear the moving piece.
movingPiece = EMPTY;
if (LOG.isDebugEnabled()) {
LOG.debug("userMadeMove completed in "
+ (System.currentTimeMillis() - startTime) + "ms");
}
}
/**
* Middle click is smart move. A move is randomly selected that is'nt a drop
* move and played if its enabled.
*/
@Override
public void userMiddleClicked(int square) {
if (isDisposed()) {
return;
}
if (getPreferences().getBoolean(PreferenceKeys.BOARD_SMARTMOVE_ENABLED)) {
if (LOG.isDebugEnabled()) {
LOG
.debug("On middle click " + getGame().getId() + " "
+ square);
}
if (isUsersMove()) {
Move[] moves = getGame().getLegalMoves().asArray();
List<Move> foundMoves = new ArrayList<Move>(5);
for (Move move : moves) {
if (move.getTo() == square
&& (move.getMoveCharacteristic() & Move.DROP_CHARACTERISTIC) != 0) {
foundMoves.add(move);
}
}
if (foundMoves.size() > 0) {
Move move = foundMoves.get(random
.nextInt(foundMoves.size()));
if (game.move(move)) {
connector.makeMove(game, move);
} else {
throw new IllegalStateException(
"Game rejected move in smart move. This is a bug.");
}
board.unhighlightAllSquares();
refreshForMove(move);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Rejected smart move since its not users move.");
}
}
}
}
/**
* In droppable games this shows a menu of the pieces available for
* dropping. In bughouse the menu includes the premove drop features which
* drops a move when the piece becomes available.
*/
@Override
public void userRightClicked(final int square) {
if (isDisposed()) {
return;
}
if (!BoardUtils.isPieceJailSquare(square)
&& getGame().isInState(Game.DROPPABLE_STATE)) {
}
}
} |
package info.ata4.unity.serdes;
import info.ata4.unity.struct.Struct;
import info.ata4.util.io.DataInputReader;
import java.io.IOException;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class SerializedInput {
private static final int ALIGNMENT = 4;
private final DataInputReader in;
private int bytes;
public SerializedInput(DataInputReader in) {
this.in = in;
}
public byte readByte() throws IOException {
bytes++;
return in.readByte();
}
public int readUnsignedByte() throws IOException {
bytes++;
return in.readUnsignedByte();
}
public boolean readBoolean() throws IOException {
bytes++;
return in.readBoolean();
}
public int readInt() throws IOException {
align();
return in.readInt();
}
public long readUnsignedInt() throws IOException {
align();
return in.readUnsignedInt();
}
public long readLong() throws IOException {
align();
return in.readLong();
}
public float readFloat() throws IOException {
align();
return in.readFloat();
}
public double readDouble() throws IOException {
align();
return in.readDouble();
}
public short readShort() throws IOException {
align();
return in.readShort();
}
public int readUnsignedShort() throws IOException {
align();
return in.readUnsignedShort();
}
public byte[] readByteArray(int size) throws IOException {
byte[] data = new byte[size];
in.readFully(data);
bytes = size;
align();
return data;
}
public byte[] readByteArray() throws IOException {
int len = readInt();
return readByteArray(len);
}
public String readString() throws IOException {
return new String(readByteArray(), "UTF8");
}
public void readStruct(Struct obj) throws IOException {
align();
obj.read(in);
}
public void align() throws IOException {
if (bytes > 0) {
in.align(bytes, ALIGNMENT);
bytes = 0;
}
}
} |
package org.davidmoten.rx;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.davidmoten.rx.jdbc.Database;
import org.davidmoten.rx.jdbc.Pools;
import org.davidmoten.rx.jdbc.annotations.Column;
import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException;
import org.davidmoten.rx.jdbc.pool.DatabaseCreator;
import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
public class DatabaseTest {
private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class);
private static Database db() {
return DatabaseCreator.create(1);
}
private static Database db(int poolSize) {
return DatabaseCreator.create(poolSize);
}
@Test
public void testSelectUsingQuestionMark() {
db()
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingQuestionMarkWithPublicTestingDatabase() {
Database.test()
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingNonBlockingBuilder() {
NonBlockingConnectionPool pool = Pools
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.healthy(c -> c.prepareStatement("select 1").execute())
.maxPoolSize(3)
.build();
Database.from(pool)
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingName() {
db()
.select("select score from person where name=:name")
.parameter("name", "FRED")
.parameter("name", "JOSEPH")
.getAs(Integer.class)
.test()
.assertValues(21, 34)
.assertComplete();
}
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() {
db()
.select("select score from person where name=:name")
.parameters("FRED", "JOSEPH");
}
@Test(expected = IllegalArgumentException.class)
public void testSelectParametersSpecifiedWhenNoneExpectedThrowsImmediately() {
db()
.select("select score from person")
.parameters("FRED", "JOSEPH");
}
@Test
public void testSelectTransacted() {
System.out.println("testSelectTransacted");
db()
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transacted()
.getAs(Integer.class)
.doOnNext(System.out::println)
.test()
.assertValueCount(3)
.assertComplete();
}
@Test
public void testSelectTransactedChained() throws Exception {
System.out.println("testSelectTransactedChained");
Database db = db();
db
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transacted()
.transactedValuesOnly()
.getAs(Integer.class)
.doOnNext(System.out::println)
.flatMap(tx -> db
.tx(tx)
.select("select name from person where score = ?")
.parameters(tx.value())
.valuesOnly()
.getAs(String.class))
.test()
.assertNoErrors()
.assertValues("FRED", "JOSEPH")
.assertComplete();
}
@Test
public void databaseIsAutoCloseable() {
try (Database db = db()) {
log.debug(db.toString());
}
}
@Test
public void testSelectChained() {
System.out.println("testSelectChained");
// we should be able to do this with 2 connections only
// using tx() we get to resuse current connection
Database db = db(2);
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.concatMap(score -> {
log.info("score={}", score);
return db
.select("select name from person where score = ?")
.parameters(score)
.getAs(String.class)
.doOnComplete(() -> log.info("completed select where score=" + score));
})
.test()
.assertNoErrors()
.assertValues("FRED", "JOSEPH")
.assertComplete();
}
@Test
public void testReadMeFragment1() {
Database db = Database.test();
db.select("select name from person").getAs(String.class).forEach(System.out::println);
}
@Test(expected = RuntimeException.class)
public void testReadMeFragmentColumnDoesNotExist() {
Database db = Database.test();
db.select("select nam from person").getAs(String.class).doOnNext(System.out::println).blockingSubscribe();
}
@Test
public void testTupleSupport() {
db().select("select name, score from person").getAs(String.class, Integer.class).forEach(System.out::println);
}
@Test
public void testDelayedCallsAreNonBlocking() throws InterruptedException {
List<String> list = new CopyOnWriteArrayList<String>();
Database db = db(1);
db.select("select score from person where name=?")
.parameters("FRED")
.getAs(Integer.class)
.doOnNext(x -> Thread.sleep(1000))
.subscribeOn(Schedulers.io())
.subscribe();
Thread.sleep(100);
CountDownLatch latch = new CountDownLatch(1);
db.select("select score from person where name=?")
.parameters("FRED")
.getAs(Integer.class)
.doOnNext(x -> list.add("emitted"))
.doOnNext(x -> System.out.println("emitted on " + Thread.currentThread().getName()))
.doOnNext(x -> latch.countDown())
.subscribe();
list.add("subscribed");
latch.await(5, TimeUnit.SECONDS);
assertEquals(Arrays.asList("subscribed", "emitted"), list);
}
@Test
public void testAutoMapToInterface() {
db()
.select("select name from person")
.autoMap(Person.class)
.map(p -> p.name())
.test()
.assertValueCount(3)
.assertComplete();
}
@Test
public void testAutoMapToInterfaceWithoutAnnotationsEmitsError() {
db()
.select("select name from person")
.autoMap(PersonNoAnnotation.class)
.map(p -> p.name())
.test()
.assertNoValues()
.assertError(AnnotationsNotFoundException.class);
}
@Test
public void testAutoMapToInterfaceWithTwoMethods() {
db()
.select("select name, score from person order by name")
.autoMap(Person2.class)
.doOnNext(System.out::println)
.firstOrError()
.map(Person2::score)
.test()
.assertValue(21)
.assertComplete();
}
@Test
public void testAutoMapToInterfaceWithExplicitColumnName() {
db()
.select("select name, score from person order by name")
.autoMap(Person3.class)
.doOnNext(System.out::println)
.firstOrError()
.map(Person3::examScore)
.test()
.assertValue(21)
.assertComplete();
}
@Test
public void testSelectWithoutWhereClause() {
Assert.assertEquals(3, (long) db().select("select name from person")
.count().blockingGet());
}
static interface Person {
@Column
String name();
}
static interface Person2 {
@Column
String name();
@Column
int score();
}
static interface Person3 {
@Column("name")
String fullName();
@Column("score")
int examScore();
}
static interface PersonNoAnnotation {
String name();
}
public static void main(String[] args) {
Flowable.just(1, 2, 3, 4, 5, 6).doOnRequest(System.out::println).subscribe();
}
} |
package claw;
import claw.tatsu.common.CompilerDirective;
import claw.tatsu.common.Context;
import claw.tatsu.common.Target;
import claw.tatsu.directive.generator.OpenAcc;
import claw.tatsu.xcodeml.backend.OmniBackendDriver;
import claw.wani.report.ClawTransformationReport;
import claw.wani.x2t.configuration.Configuration;
import claw.wani.x2t.translator.ClawPythonTranslatorDriver;
import claw.wani.x2t.translator.ClawTranslatorDriver;
import exc.xcodeml.XcodeMLtools_Fmod;
import org.apache.commons.cli.*;
import xcodeml.util.XmOption;
import java.io.File;
/**
* ClawX2T is the entry point of any CLAW XcodeML/F translation.
*
* @author clementval
*/
public class ClawX2T {
/**
* Print an error message an abort.
*
* @param filename Filename in which error occurred.
* @param lineNumber Line number of the error, if known.
* @param charPos Character position of the error, if known.
* @param msg Error message.
*/
private static void error(String filename, int lineNumber,
int charPos, String msg)
{
System.err.println(String.format("%s:%d:%d error: %s",
filename, lineNumber, charPos, msg));
System.exit(1);
}
/**
* Print program usage.
*/
private static void usage() {
Options options = prepareOptions();
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("clawfc", options);
System.exit(1);
}
/**
* List all directive target available for code generation.
*/
private static void listTarget() {
System.out.println("- CLAW available targets -");
for(String t : Target.availableTargets()) {
System.out.println(" - " + t);
}
}
/**
* List all directive directive language available for code generation.
*/
private static void listDirectiveLanguage() {
System.out.println("- CLAW directive directive language -");
for(String d : CompilerDirective.availableDirectiveLanguage()) {
System.out.println(" - " + d);
}
}
/**
* Prepare the set of available options.
*
* @return Options object.
*/
private static Options prepareOptions() {
Options options = new Options();
options.addOption("h", "help", false,
"display program usage.");
options.addOption("l", false,
"suppress line directive in decompiled code.");
options.addOption("cp", "config-path", true,
"specify the configuration directory");
options.addOption("c", "config", true,
"specify the configuration for the translator.");
options.addOption("s", "schema", true,
"specify the XSD schema location to validate the configuration.");
options.addOption("t", "target", true,
"specify the target for the code transformation.");
options.addOption("dir", "directive", true,
"list all directive directive language available for code generation.");
options.addOption("d", "debug", false,
"enable output debug message.");
options.addOption("f", true,
"specify FORTRAN decompiled output file.");
options.addOption("w", true,
"number of character per line in decompiled code.");
options.addOption("o", true,
"specify XcodeML/F output file.");
options.addOption("M", true,
"specify where to search for .xmod files");
options.addOption("tl", "target-list", false,
"list all target available for code transformation.");
options.addOption("dl", "directive-list", false,
"list all available directive language to be generated.");
options.addOption("sc", "show-config", false,
"display the current configuration.");
options.addOption("fp", "force-pure", false,
"exit the translator if a PURE subroutine/function " +
"has to be transformed.");
options.addOption("r", "report", true,
"generate the transformation report.");
options.addOption("script", "python-script", true,
"Python optimisation script to apply (requires Jython)");
return options;
}
/**
* Parse the arguments passed to the program.
*
* @param args Arguments passed to the program.
* @return Parsed command line object.
* @throws ParseException If one or several arguments are not found.
*/
private static CommandLine processCommandArgs(String[] args)
throws ParseException
{
Options options = prepareOptions();
CommandLineParser parser = new DefaultParser();
return parser.parse(options, args);
}
/**
* Main point of entry of the program.
*
* @param args Arguments of the program.
* @throws Exception if translation failed.
*/
public static void main(String[] args) throws Exception {
String input;
String xcmlOutput = null;
String targetLangOutput = null;
String target_option = null;
String directive_option = null;
String configuration_file = null;
String configuration_path = null;
String recipeScript = null;
int maxColumns = 0;
//boolean forcePure = false;
CommandLine cmd;
try {
cmd = processCommandArgs(args);
} catch(ParseException pex) {
error("internal", 0, 0, pex.getMessage());
return;
}
// Help option
if(cmd.hasOption("h")) {
usage();
return;
}
// Display target list option
if(cmd.hasOption("tl")) {
listTarget();
return;
}
// Display directive list option
if(cmd.hasOption("dl")) {
listDirectiveLanguage();
return;
}
// Target option
if(cmd.hasOption("t")) {
target_option = cmd.getOptionValue("t");
}
// Directive option
if(cmd.hasOption("dir")) {
directive_option = cmd.getOptionValue("dir");
}
// Suppressing line directive option
if(cmd.hasOption("l")) {
XmOption.setIsSuppressLineDirective(true);
}
// Debug option
if(cmd.hasOption("d")) {
XmOption.setDebugOutput(true);
}
// XcodeML/F output file option
if(cmd.hasOption("o")) {
xcmlOutput = cmd.getOptionValue("o");
}
// FORTRAN output file option
if(cmd.hasOption("f")) {
targetLangOutput = cmd.getOptionValue("f");
}
if(cmd.hasOption("w")) {
maxColumns = Integer.parseInt(cmd.getOptionValue("w"));
}
if(cmd.hasOption("c")) {
configuration_file = cmd.getOptionValue("c");
}
if(cmd.hasOption("cp")) {
configuration_path = cmd.getOptionValue("cp");
}
// Check that configuration path exists
if(configuration_path == null) {
error("internal", 0, 0, "Configuration path missing.");
return;
}
// Check that configuration file exists
if(configuration_file != null) {
File configFile = new File(configuration_file);
if(!configFile.exists()) {
error("internal", 0, 0, "Configuration file not found. "
+ configuration_path);
}
}
// --show-configuration option
if(cmd.hasOption("sc")) {
Configuration.get().load(configuration_path, configuration_file);
Configuration.get().displayConfig();
return;
}
if(cmd.hasOption("script")) {
recipeScript = cmd.getOptionValue("script");
}
// Get the input XcodeML file to transform
if(cmd.getArgs().length == 0) {
input = null;
} else {
input = cmd.getArgs()[0];
}
// Module search path options
if(cmd.hasOption("M")) {
for(String value : cmd.getOptionValues("M")) {
XcodeMLtools_Fmod.addSearchPath(value);
}
}
// Read the configuration file
try {
Configuration.get().load(configuration_path, configuration_file);
Configuration.get().setUserDefinedTarget(target_option);
Configuration.get().setUserDefineDirective(directive_option);
Configuration.get().setMaxColumns(maxColumns);
Context.init(Configuration.get().getCurrentDirective(),
Configuration.get().getCurrentTarget(), maxColumns);
if(Context.get().getCompilerDirective() == CompilerDirective.OPENACC) {
OpenAcc openaccGen = (OpenAcc) Context.get().getGenerator();
openaccGen.setExecutionMode(Configuration.get().openACC().getMode());
}
} catch(Exception ex) {
error("internal", 0, 0, ex.getMessage());
return;
}
// Force pure option
if(cmd.hasOption("fp")) {
Configuration.get().setForcePure();
}
ClawTranslatorDriver translatorDriver;
// Call the translator driver to apply transformation on XcodeML/F
if(recipeScript != null) {
// Transformation is to be performed by Python script
translatorDriver =
new ClawPythonTranslatorDriver(recipeScript, input, xcmlOutput);
} else {
translatorDriver = new ClawTranslatorDriver(input, xcmlOutput);
}
translatorDriver.analyze();
translatorDriver.transform();
translatorDriver.flush();
// Produce report (unless we've used the Python driver)
if(recipeScript == null && cmd.hasOption("r")) {
ClawTransformationReport report =
new ClawTransformationReport(cmd.getOptionValue("r"));
report.generate(args, translatorDriver);
}
// Decompile XcodeML/F to target language
OmniBackendDriver backend;
if(Configuration.get().getCurrentTarget() == Target.FPGA) {
// TODO remove when supported
error(xcmlOutput, 0, 0, "FPGA target is not supported yet");
backend = new OmniBackendDriver(OmniBackendDriver.Lang.C);
} else {
backend = new OmniBackendDriver(OmniBackendDriver.Lang.FORTRAN);
}
if(xcmlOutput == null) { // XcodeML output not written to file. Use pipe.
if(!backend.decompile(targetLangOutput,
translatorDriver.getTranslationUnit(), maxColumns,
XmOption.isSuppressLineDirective()))
{
error(targetLangOutput, 0, 0, "Unable to decompile XcodeML to Fortran");
System.exit(1);
}
} else {
if(!backend.decompileFromFile(targetLangOutput, xcmlOutput, maxColumns,
XmOption.isSuppressLineDirective()))
{
error(xcmlOutput, 0, 0, "Unable to decompile XcodeML to Fortran");
System.exit(1);
}
}
}
} |
package io.flutter;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.scratch.ScratchRootType;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.diagnostic.ErrorReportSubmitter;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diagnostic.SubmittedReportInfo;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import io.flutter.run.daemon.DaemonApi;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT;
import static io.flutter.run.daemon.DaemonApi.COMPLETION_EXCEPTION_PREFIX;
// Not sure how others debug this but here's one technique.
// Edit com.intellij.ide.plugins.PluginManagerCore.
// Add this line at the top of getPluginByClassName():
// if (true) return getPlugins()[getPlugins().length-1].getPluginId(); // DEBUG do not merge
public class FlutterErrorReportSubmitter extends ErrorReportSubmitter {
private static final Logger LOG = Logger.getInstance(FlutterErrorReportSubmitter.class);
private static final String[] KNOWN_ERRORS = new String[]{"Bad state: No element"};
@NotNull
@Override
public String getReportActionText() {
return "Create Flutter Bug Report";
}
@SuppressWarnings("deprecation")
@Override
public void submitAsync(@NotNull IdeaLoggingEvent[] events,
@Nullable String additionalInfo,
@NotNull Component parentComponent,
@NotNull Consumer<SubmittedReportInfo> consumer) {
if (events.length == 0) {
fail(consumer);
return;
}
String stackTrace = null;
String errorMessage = null;
for (IdeaLoggingEvent event : events) {
String stackTraceText = event.getThrowableText();
if (stackTraceText.startsWith(COMPLETION_EXCEPTION_PREFIX)) {
stackTraceText = stackTraceText.substring(COMPLETION_EXCEPTION_PREFIX.length());
if (stackTraceText.startsWith(DaemonApi.FLUTTER_ERROR_PREFIX)) {
final String message = stackTraceText.substring(DaemonApi.FLUTTER_ERROR_PREFIX.length());
final int start = message.indexOf(": ") + 2;
if (start == 0) continue;
int end = message.indexOf('\n');
if (end < 0) end = message.length();
final String error = message.substring(start, end);
stackTrace = message.substring(end + 1);
for (String err : KNOWN_ERRORS) {
if (error.contains(err)) {
if (end != message.length()) {
// Dart stack trace included so extract it and set the issue target to the Flutter repo.
errorMessage = err;
final int endOfDartStack = stackTrace.indexOf("\\n\"\n");
if (endOfDartStack > 0) {
// Get only the part between quotes. If the format is wrong just use the whole thing.
stackTrace = stackTrace.substring(1, endOfDartStack);
}
break;
}
}
}
}
}
}
final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent);
final Project project = PROJECT.getData(dataContext);
if (project == null) {
fail(consumer);
return;
}
final StringBuilder builder = new StringBuilder();
builder.append("Please file this bug report at ");
builder.append("https://github.com/flutter/flutter-intellij/issues/new");
builder.append(".\n");
builder.append("\n");
builder.append("
builder.append("\n");
builder.append("## What happened\n");
builder.append("\n");
if (additionalInfo != null) {
builder.append(additionalInfo.trim()).append("\n");
}
else {
builder.append("(please describe what you were doing when this exception occurred)\n");
}
builder.append("\n");
builder.append("## Version information\n");
builder.append("\n");
// IntelliJ version
final ApplicationInfo info = ApplicationInfo.getInstance();
builder.append(info.getVersionName()).append(" `").append(info.getFullVersion()).append("`");
final PluginId pid = FlutterUtils.getPluginId();
final IdeaPluginDescriptor flutterPlugin = PluginManager.getPlugin(pid);
//noinspection ConstantConditions
builder.append(" • Flutter plugin `").append(pid.getIdString()).append(' ').append(flutterPlugin.getVersion()).append("`");
final IdeaPluginDescriptor dartPlugin = PluginManager.getPlugin(PluginId.getId("Dart"));
if (dartPlugin != null) {
builder.append(" • Dart plugin `").append(dartPlugin.getVersion()).append("`");
}
builder.append("\n\n");
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
builder.append("No Flutter sdk configured.\n");
}
else {
final String flutterVersion = getFlutterVersion(sdk);
if (flutterVersion != null) {
builder.append(flutterVersion.trim()).append("\n");
}
else {
builder.append("Error getting Flutter sdk information.\n");
}
}
builder.append("\n");
if (stackTrace == null) {
for (IdeaLoggingEvent event : events) {
builder.append("## Exception\n");
builder.append("\n");
builder.append(event.getMessage()).append("\n");
builder.append("\n");
if (event.getThrowable() != null) {
builder.append("```\n");
builder.append(event.getThrowableText().trim()).append("\n");
builder.append("```\n");
builder.append("\n");
}
}
}
else {
builder.append("## Exception\n");
builder.append("\n");
builder.append(errorMessage).append("\n");
builder.append("\n");
builder.append("```\n");
builder.append(stackTrace.replaceAll("\\\\n", "\n")).append("\n");
builder.append("```\n");
builder.append("\n");
}
for (IdeaLoggingEvent event : events) {
FlutterInitializer.getAnalytics().sendException(event.getThrowableText(), false);
}
final String text = builder.toString().trim() + "\n";
// Create scratch file.
final ScratchRootType scratchRoot = ScratchRootType.getInstance();
final VirtualFile file = scratchRoot.createScratchFile(project, "bug-report.md", PlainTextLanguage.INSTANCE, text);
if (file == null) {
fail(consumer);
return;
}
// Open the file.
new OpenFileDescriptor(project, file).navigate(true);
consumer.consume(new SubmittedReportInfo(
null,
"",
SubmittedReportInfo.SubmissionStatus.NEW_ISSUE));
}
@SuppressWarnings("deprecation")
@Override
public SubmittedReportInfo submit(IdeaLoggingEvent[] events, Component parentComponent) {
// obsolete API
return new SubmittedReportInfo(null, "0", SubmittedReportInfo.SubmissionStatus.FAILED);
}
private static String getFlutterVersion(final FlutterSdk sdk) {
try {
final String flutterPath = sdk.getHomePath() + "/bin/flutter";
final ProcessBuilder builder = new ProcessBuilder(flutterPath, "--version");
final Process process = builder.start();
if (!process.waitFor(3, TimeUnit.SECONDS)) {
return null;
}
return new String(readFully(process.getInputStream()), StandardCharsets.UTF_8);
}
catch (IOException | InterruptedException ioe) {
return null;
}
}
private static void fail(@NotNull Consumer<SubmittedReportInfo> consumer) {
consumer.consume(new SubmittedReportInfo(
null,
null,
SubmittedReportInfo.SubmissionStatus.FAILED));
}
private static byte[] readFully(InputStream in) throws IOException {
//noinspection resource
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] temp = new byte[4096];
int count = in.read(temp);
while (count > 0) {
out.write(temp, 0, count);
count = in.read(temp);
}
return out.toByteArray();
}
} |
package testsupport.matchers;
import com.jnape.palatable.lambda.adt.Either;
import com.jnape.palatable.lambda.io.IO;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.concurrent.atomic.AtomicReference;
import static com.jnape.palatable.lambda.adt.Either.left;
import static com.jnape.palatable.lambda.adt.Either.right;
import static com.jnape.palatable.lambda.io.IO.io;
import static org.hamcrest.Matchers.anything;
public final class IOMatcher<A> extends TypeSafeMatcher<IO<A>> {
private final Either<Matcher<? super Throwable>, Matcher<? super A>> matcher;
private final AtomicReference<Either<Throwable, A>> resultRef;
private IOMatcher(Either<Matcher<? super Throwable>, Matcher<? super A>> matcher) {
this.matcher = matcher;
resultRef = new AtomicReference<>();
}
@Override
protected boolean matchesSafely(IO<A> io) {
Either<Throwable, A> res = io.safe().unsafePerformIO();
resultRef.set(res);
return res.match(t -> matcher.match(tMatcher -> tMatcher.matches(t),
aMatcher -> false),
a -> matcher.match(tMatcher -> false,
aMatcher -> aMatcher.matches(a)));
}
@Override
public void describeTo(Description description) {
matcher.match(m -> io(() -> m.describeTo(description.appendText("IO throwing exception matching "))),
m -> io(() -> m.describeTo(description.appendText("IO yielding value matching "))))
.unsafePerformIO();
}
@Override
protected void describeMismatchSafely(IO<A> item, Description mismatchDescription) {
resultRef.get().match(t -> io(() -> mismatchDescription.appendText("IO threw " + t)),
a -> io(() -> mismatchDescription.appendText("IO yielded value " + a)))
.unsafePerformIO();
}
public static <A> IOMatcher<A> yieldsValue(Matcher<? super A> matcher) {
return new IOMatcher<>(right(matcher));
}
public static <A> IOMatcher<A> completesNormally() {
return yieldsValue(anything());
}
public static <A> IOMatcher<A> throwsException(Matcher<? super Throwable> throwableMatcher) {
return new IOMatcher<>(left(throwableMatcher));
}
} |
package org.apache.jmeter.gui.action;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import org.apache.jmeter.gui.GuiPackage;
import org.apache.jmeter.swing.HtmlPane;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.ComponentUtil;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author unattributed
* @version $revision$ $date$
*/
public class Help implements Command
{
transient private static Logger log = LoggingManager.getLoggerForClass();
public final static String HELP = "help";
private static Set commands = new HashSet();
public static final String HELP_DOCS =
"file:
+ JMeterUtils.getJMeterHome()
+ "/printable_docs/usermanual/";
public static final String HELP_PAGE =
HELP_DOCS + "component_reference.html";
public static final String HELP_FUNCTIONS =
HELP_DOCS + "functions.html";
private static JDialog helpWindow;
private static HtmlPane helpDoc;
private static JScrollPane scroller;
private static String currentPage;
static
{
commands.add(HELP);
helpDoc = new HtmlPane();
scroller = new JScrollPane(helpDoc);
helpDoc.setEditable(false);
try
{
helpDoc.setPage(HELP_PAGE);
currentPage = HELP_PAGE;
}
catch (IOException err)
{
String msg = "Couldn't load help file " + err.toString();
log.error(msg);
currentPage="";// Avoid NPE in resetPage()
}
}
/**
* @see org.apache.jmeter.gui.action.Command#doAction(ActionEvent)
*/
public void doAction(ActionEvent e)
{
if (helpWindow == null)
{
helpWindow =
new JDialog(
new Frame(),// independent frame to allow it to be overlaid by the main frame
JMeterUtils.getResString("help"),//$NON-NLS-1$
false);
helpWindow.getContentPane().setLayout(new GridLayout(1, 1));
ComponentUtil.centerComponentInWindow(helpWindow, 60);
}
helpWindow.getContentPane().removeAll();
helpWindow.getContentPane().add(scroller);
helpWindow.show();
if (e.getSource() instanceof String[])
{
String[] source = (String[]) e.getSource();
resetPage(source[0]);
helpDoc.scrollToReference(source[1]);
}
else
{
resetPage(HELP_PAGE);
helpDoc.scrollToReference(
GuiPackage
.getInstance()
.getTreeListener()
.getCurrentNode()
.getStaticLabel()
.replace(' ', '_'));
}
}
private void resetPage(String source)
{
if (!currentPage.equals(source))
{
try
{
helpDoc.setPage(source);
currentPage = source;
}
catch (IOException err)
{
log.error(err.toString());
JMeterUtils.reportErrorToUser("Problem loading a help page - see log for details");
currentPage="";
}
}
}
/**
* @see org.apache.jmeter.gui.action.Command#getActionNames()
*/
public Set getActionNames()
{
return commands;
}
} |
package ua.com.fielden.platform.entity.query.metadata;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractUnionEntity.unionProperties;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getAnnotation;
import static ua.com.fielden.platform.reflection.AnnotationReflector.isContextual;
import static ua.com.fielden.platform.reflection.Finder.getFieldByName;
import static ua.com.fielden.platform.reflection.Reflector.getKeyMemberSeparator;
import static ua.com.fielden.platform.utils.EntityUtils.isEntityType;
import static ua.com.fielden.platform.utils.EntityUtils.isUnionEntityType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.meta.PropertyDescriptor;
import ua.com.fielden.platform.entity.query.exceptions.EqlException;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICaseWhenFunctionWhen;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IFromAlias;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IStandAloneExprOperationAndClose;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ISubsequentCompletedAndYielded;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.ExpressionModel;
import ua.com.fielden.platform.expression.ExpressionText2ModelConverter;
import ua.com.fielden.platform.utils.Pair;
public class DomainMetadataUtils {
/** Private default constructor to prevent instantiation. */
private DomainMetadataUtils() {
}
public static ExpressionModel generateUnionEntityPropertyExpression(final Class<? extends AbstractUnionEntity> entityType, final String commonPropName) {
final List<Field> props = unionProperties(entityType);
final Iterator<Field> iterator = props.iterator();
final String firstUnionPropName = iterator.next().getName();
ICaseWhenFunctionWhen<IStandAloneExprOperationAndClose, AbstractEntity<?>> expressionModelInProgress = expr().caseWhen().prop(firstUnionPropName).isNotNull().then().prop(firstUnionPropName
+ "." + commonPropName);
for (; iterator.hasNext();) {
final String unionPropName = iterator.next().getName();
expressionModelInProgress = expressionModelInProgress.when().prop(unionPropName).isNotNull().then().prop(unionPropName + "." + commonPropName);
}
return expressionModelInProgress.otherwise().val(null).end().model();
}
public static ExpressionModel getVirtualKeyPropForEntityWithCompositeKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final List<Pair<Field, Boolean>> keyMembers) {
return composeExpression(keyMembers, getKeyMemberSeparator(entityType));
}
private static String getKeyMemberConcatenationExpression(final Field keyMember) {
if (PropertyDescriptor.class != keyMember.getType() && isEntityType(keyMember.getType())) {
return keyMember.getName() + "." + KEY;
} else {
return keyMember.getName();
}
}
private static ExpressionModel composeExpression(final List<Pair<Field, Boolean>> original, final String separator) {
ExpressionModel currExp = null;
Boolean currExpIsOptional = null;
for (final Pair<Field, Boolean> originalField : original) {
currExp = composeTwo(new Pair<ExpressionModel, Boolean>(currExp, currExpIsOptional), originalField, separator);
currExpIsOptional = currExpIsOptional != null ? currExpIsOptional && originalField.getValue() : originalField.getValue();
}
return currExp;
}
private static ExpressionModel concatTwo(final ExpressionModel first, final String secondPropName, final String separator) {
return expr().concat().expr(first).with().val(separator).with().prop(secondPropName).end().model();
}
private static ExpressionModel composeTwo(final Pair<ExpressionModel, Boolean> first, final Pair<Field, Boolean> second, final String separator) {
final ExpressionModel firstModel = first.getKey();
final Boolean firstIsOptional = first.getValue();
final String secondPropName = getKeyMemberConcatenationExpression(second.getKey());
final boolean secondPropIsOptional = second.getValue();
if (first.getKey() == null) {
return expr().prop(secondPropName).model();
} else {
if (firstIsOptional) {
if (secondPropIsOptional) {
return expr().caseWhen().expr(firstModel).isNotNull().and().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)).
when().expr(firstModel).isNotNull().and().prop(secondPropName).isNull().then().expr(firstModel).
when().prop(secondPropName).isNotNull().then().prop(secondPropName).
otherwise().val(null).endAsStr(256).model();
} else {
return expr().caseWhen().expr(firstModel).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)).
otherwise().prop(secondPropName).endAsStr(256).model();
}
} else {
if (secondPropIsOptional) {
return expr().caseWhen().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)).
otherwise().expr(firstModel).endAsStr(256).model();
} else {
return concatTwo(firstModel, secondPropName, separator);
}
}
}
}
public static ExpressionModel extractExpressionModelFromCalculatedProperty(final Class<? extends AbstractEntity<?>> entityType, final Field calculatedPropfield) throws Exception {
final Calculated calcAnnotation = getAnnotation(calculatedPropfield, Calculated.class);
if (isNotEmpty(calcAnnotation.value())) {
return createExpressionText2ModelConverter(entityType, calcAnnotation).convert().getModel();
} else {
try {
final Field exprField = getFieldByName(entityType, calculatedPropfield.getName() + "_");
exprField.setAccessible(true);
return (ExpressionModel) exprField.get(null);
} catch (final Exception e) {
throw new EqlException(format("Can't extract hard-coded expression model for prop [%s] due to: [%s]", calculatedPropfield.getName(), e.getMessage()));
}
}
}
private static ExpressionText2ModelConverter createExpressionText2ModelConverter(final Class<? extends AbstractEntity<?>> entityType, final Calculated calcAnnotation)
throws Exception {
if (isContextual(calcAnnotation)) {
return new ExpressionText2ModelConverter(getRootType(calcAnnotation), calcAnnotation.contextPath(), calcAnnotation.value());
} else {
return new ExpressionText2ModelConverter(entityType, calcAnnotation.value());
}
}
private static Class<? extends AbstractEntity<?>> getRootType(final Calculated calcAnnotation) throws ClassNotFoundException {
return (Class<? extends AbstractEntity<?>>) ClassLoader.getSystemClassLoader().loadClass(calcAnnotation.rootTypeName());
}
public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> produceUnionEntityModels(final Class<ET> entityType) {
final List<EntityResultQueryModel<ET>> result = new ArrayList<>();
if (!isUnionEntityType(entityType)) {
return result;
}
final List<Field> unionProps = unionProperties((Class<? extends AbstractUnionEntity>) entityType);
for (final Field currProp : unionProps) {
result.add(generateModelForUnionEntityProperty(unionProps, currProp).modelAsEntity(entityType));
}
return result;
}
private static <PT extends AbstractEntity<?>> ISubsequentCompletedAndYielded<PT> generateModelForUnionEntityProperty(final List<Field> unionProps, final Field currProp) {
final IFromAlias<PT> startWith = select((Class<PT>) currProp.getType());
final Field firstUnionProp = unionProps.get(0);
final ISubsequentCompletedAndYielded<PT> initialModel = firstUnionProp.equals(currProp) ? startWith.yield().prop(ID).as(firstUnionProp.getName()) : startWith.yield().val(null).as(firstUnionProp.getName());
return unionProps.stream().skip(1).reduce(initialModel, (m, f) -> f.equals(currProp) ? m.yield().prop(ID).as(f.getName()) : m.yield().val(null).as(f.getName()), (m1, m2) -> {throw new UnsupportedOperationException("Combining is not applicable here.");});
}
} |
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.decorator.AlternateRowHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.Filter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PatternFilter;
import org.jdesktop.swingx.decorator.PatternHighlighter;
import org.jdesktop.swingx.decorator.PipelineListener;
import org.jdesktop.swingx.decorator.RolloverHighlighter;
import org.jdesktop.swingx.decorator.ShuttleSorter;
import org.jdesktop.swingx.table.ColumnHeaderRenderer;
import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.util.AncientSwingTeam;
public class JXTableUnitTest extends InteractiveTestCase {
protected DynamicTableModel tableModel = null;
protected TableModel sortableTableModel;
public JXTableUnitTest() {
super("JXTable unit test");
}
protected void setUp() throws Exception {
super.setUp();
// set loader priority to normal
if (tableModel == null) {
tableModel = new DynamicTableModel();
}
sortableTableModel = new AncientSwingTeam();
}
/**
* Issue #189, #214: Sorter fails if content is
* comparable with mixed types
*
*/
public void testMixedComparableTypes() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, new Integer(2) },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
final JXTable table = new JXTable(model);
table.setSorter(1);
}
/**
* Issue #189, #214: Sorter fails if content is
* mixed comparable/not comparable
*
*/
public void testMixedComparableTypesWithNonComparable() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, new Integer(2) },
new Object[] { Boolean.TRUE, new Object() } };
String[] columnNames = new String[] { "Critical", "Task" };
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
final JXTable table = new JXTable(model);
table.setSorter(1);
}
/**
* Issue #196: backward search broken.
*
*/
public void testBackwardSearch() {
JXTable table = new JXTable(createModel(0, 10));
int row = 1;
String lastName = table.getValueAt(row, 0).toString();
int found = table.search(Pattern.compile(lastName), -1, true);
assertEquals(row, found);
}
/**
* Issue #175: multiple registration as PipelineListener.
*
*
*/
public void testRegisterUniquePipelineListener() {
JXTable table = new JXTable();
PatternFilter noFilter = new PatternFilter(".*", 0, 1);
table.setFilters(new FilterPipeline(new Filter[] {noFilter}));
int listenerCount = table.getFilters().getPipelineListeners().length;
PipelineListener l = table.getFilters().getPipelineListeners()[listenerCount - 1];
// sanity assert
assertEquals(1, listenerCount);
// JW: no longer valid assumption - the pipelineListener now is an
// implementation detail of JXTable
// assertEquals(table, l);
table.setModel(createModel(0, 20));
assertEquals("pipeline listener count must not change after setModel", listenerCount, table.getFilters().getPipelineListeners().length);
}
/**
* Issue #174: componentAdapter.hasFocus() looks for anchor instead of lead.
*
*/
public void testLeadFocusCell() {
final JXTable table = new JXTable();
table.setModel(createModel(0, 10));
// sort first column
// table.setSorter(0);
// select last rows
table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1);
final int leadRow = table.getSelectionModel().getLeadSelectionIndex();
int anchorRow = table.getSelectionModel().getAnchorSelectionIndex();
table.addColumnSelectionInterval(0, 0);
final int leadColumn = table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
int anchorColumn = table.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
assertEquals("lead must be last row", table.getRowCount() - 1, leadRow);
assertEquals("anchor must be second last row", table.getRowCount() - 2, anchorRow);
assertEquals("lead must be first column", 0, leadColumn);
assertEquals("anchor must be first column", 0, anchorColumn);
final JFrame frame = new JFrame();
frame.add(table);
frame.pack();
frame.setVisible(true);
table.requestFocus();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ComponentAdapter adapter = table.getComponentAdapter();
adapter.row = leadRow;
adapter.column = leadColumn;
// difficult to test - hasFocus() implies that the table isFocusOwner()
assertTrue("adapter must have focus for leadRow/Column: " + adapter.row + "/" + adapter.column,
adapter.hasFocus());
frame.dispose();
}
});
}
/**
* Issue #173:
* ArrayIndexOOB if replacing model with one containing
* fewer rows and the "excess" is selected.
*
*/
public void testSelectionAndToggleModel() {
JXTable table = new JXTable();
table.setModel(createModel(0, 10));
// sort first column
table.setSorter(0);
// select last rows
table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1);
// invert sort
table.setSorter(0);
// set model with less rows
table.setModel(createModel(0, 8));
}
/**
* testing selection and adding rows.
*
*
*/
public void testSelectionAndAddRows() {
JXTable table = new JXTable();
DefaultTableModel model = createModel(0, 10);
table.setModel(model);
// sort first column
table.setSorter(0);
// select last rows
table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1);
// invert sort
table.setSorter(0);
Integer highestValue = new Integer(100);
model.addRow(new Object[] { highestValue });
assertEquals(highestValue, table.getValueAt(0, 0));
}
/**
* Issue #16: removing row throws ArrayIndexOOB if
* last row was selected
*
*/
public void testSelectionAndRemoveRows() {
JXTable table = new JXTable();
DefaultTableModel model = createModel(0, 10);
table.setModel(model);
// sort first column
table.setSorter(0);
// select last rows
table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1);
// invert sort
table.setSorter(0);
model.removeRow(0);
}
private DefaultTableModel createModel(int startRow, int count) {
DefaultTableModel model = new DefaultTableModel(count, 5);
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(new Integer(startRow++), i, 0);
}
return model;
}
/**
* Issue #171: row-coordinate not transformed in isCellEditable (sorting)
*
*/
public void testSortedEditability() {
int rows = 2;
RowObjectTableModel model = createRowObjectTableModel(rows);
JXTable table = new JXTable(model);
RowObject firstInModel = model.getRowObject(0);
assertEquals("rowObject data must be equal", firstInModel.getData1(), table.getValueAt(0, 0));
assertEquals("rowObject editability must be equal", firstInModel.isEditable(), table.isCellEditable(0, 0));
// nothing changed
table.setSorter(0);
Object firstDataValueInTable = table.getValueAt(0,0);
boolean firstEditableValueInTable = table.isCellEditable(0, 0);
assertEquals("rowObject data must be equal", firstInModel.getData1(), table.getValueAt(0, 0));
assertEquals("rowObject editability must be equal", firstInModel.isEditable(), table.isCellEditable(0, 0));
// sanity assert: first and last have different values/editability
assertTrue("lastValue different from first", firstDataValueInTable !=
table.getValueAt(rows - 1, 0));
assertTrue("lastEditability different from first", firstEditableValueInTable !=
table.isCellEditable(rows - 1, 0));
// reverse order
table.setSorter(0);
assertEquals("last row data must be equal to former first", firstDataValueInTable,
table.getValueAt(rows - 1, 0));
assertEquals("last row editability must be equal to former first", firstEditableValueInTable,
table.isCellEditable(rows - 1, 0));
}
/**
* Issue #171: row-coordinate not transformed in isCellEditable (filtering)
*
*/
public void testFilteredEditability() {
int rows = 2;
RowObjectTableModel model = createRowObjectTableModel(rows);
JXTable table = new JXTable(model);
// sanity assert
for (int i = 0; i < table.getRowCount(); i++) {
assertEquals("even/uneven rows must be editable/notEditable " + i,
i % 2 == 0, table.isCellEditable(i, 0));
}
// need to chain two filters (to reach the "else" block in
// filter.isCellEditable()
PatternFilter filter = new PatternFilter("NOT.*", 0, 1);
PatternFilter noFilter = new PatternFilter(".*", 0, 1);
table.setFilters(new FilterPipeline(new Filter[] {noFilter, filter}));
assertEquals("row count is half", rows / 2, table.getRowCount());
for (int i = 0; i < table.getRowCount(); i++) {
assertFalse("all rows must be not-editable " + i, table.isCellEditable(i, 0));
}
}
//----------------------- test data for exposing #171 (Tim Dilks)
/**
* create test model - all cells in even rows are editable,
* in odd rows are not editable.
* @param rows the number of rows to create
* @return
*/
private RowObjectTableModel createRowObjectTableModel(int rows) {
List rowObjects = new ArrayList();
for (int i = 0; i < rows; i++) {
rowObjects.add(new RowObject("somedata" + i, i % 2 == 0));
}
return new RowObjectTableModel(rowObjects);
}
/**
* test object to map in test table model.
*/
static class RowObject {
private String data1;
private boolean editable;
public RowObject(String data1, boolean editable) {
this.data1 = data1;
this.editable = editable;
}
public String getData1() {
return data1;
}
public boolean isEditable() {
return editable;
}
}
/**
* test TableModel wrapping RowObject.
*/
static class RowObjectTableModel extends AbstractTableModel {
List data;
public RowObjectTableModel(List data) {
this.data = data;
}
public RowObject getRowObject(int row) {
return (RowObject) data.get(row);
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return data.size();
}
public Object getValueAt(int row, int col) {
RowObject object = getRowObject(row);
switch (col) {
case 0 :
return object.getData1();
case 1 :
return object.isEditable() ? "EDITABLE" : "NOT EDITABLE";
default :
return null;
}
}
public boolean isCellEditable(int row, int col) {
return getRowObject(row).isEditable();
}
}
// public void testLinkCellType() {
// JXTable table = new JXTable(tableModel);
// assertEquals(LinkModel.class,
// table.getColumnClass(DynamicTableModel.IDX_COL_LINK));
// TableCellRenderer renderer = table.getCellRenderer(0,
// DynamicTableModel.IDX_COL_LINK);
// // XXX note: this should be a LinkCellRenderer LinkRenderer is not public.
// // assertEquals(renderer.getClass(),
// // org.jdesktop.swing.table.TableCellRenderers$LinkRenderer.class);
public void testToggleFiltersWhileSorting() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, "AA" },
new Object[] { Boolean.FALSE, "AB" },
new Object[] { Boolean.FALSE, "AC" },
new Object[] { Boolean.TRUE, "BA" },
new Object[] { Boolean.FALSE, "BB" },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
final JXTable table = new JXTable(rowData, columnNames);
Filter filterA = new PatternFilter("A.*", Pattern.CASE_INSENSITIVE, 1);
// simulates the sequence of user interaction as described in
// the original bug report in
table.setFilters(new FilterPipeline(new Filter[] {filterA}));
table.setSorter(1);
Filter filterB = new PatternFilter(".*", Pattern.CASE_INSENSITIVE, 1);
table.setFilters(new FilterPipeline(new Filter[] {filterB}));
table.setSorter(1);
}
public void testToggleFiltersWhileSortingLonger() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, "AA" },
new Object[] { Boolean.FALSE, "AB" },
new Object[] { Boolean.FALSE, "AC" },
new Object[] { Boolean.TRUE, "BA" },
new Object[] { Boolean.FALSE, "BB" },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
final JXTable table = new JXTable(rowData, columnNames);
// simulates the sequence of user interaction as described in
// the follow-up bug report in
table.setFilters(createFilterPipeline(false, 1));
table.setSorter(0);
table.setSorter(1);
table.setFilters(createFilterPipeline(true, 1));
table.setFilters(createFilterPipeline(false, 1));
table.setSorter(0);
}
private FilterPipeline createFilterPipeline(boolean matchAll, int col) {
Filter filter;
if (matchAll) {
filter = new PatternFilter(".*", Pattern.CASE_INSENSITIVE, col);
} else {
filter = new PatternFilter("A.*", Pattern.CASE_INSENSITIVE, col);
}
return new FilterPipeline(new Filter[] {filter});
}
/**
* Issue #125: setting filter to null doesn't clean up.
*
* A visual consequence is that the hidden (by the old
* filters) rows don't appear. A not-so visual consequence
* is that the sorter is out of synch and accessing a row in
* the region outside of the formerly filtered.
*
*/
public void testRemoveFilterWhileSorting() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, "AA" },
new Object[] { Boolean.FALSE, "AB" },
new Object[] { Boolean.FALSE, "AC" },
new Object[] { Boolean.TRUE, "BA" },
new Object[] { Boolean.FALSE, "BB" },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
final JXTable table = new JXTable(rowData, columnNames);
int rows = table.getRowCount();
Filter filterA = new PatternFilter("A.*", Pattern.CASE_INSENSITIVE, 1);
table.setFilters(new FilterPipeline(new Filter[] {filterA}));
table.setSorter(1);
table.setFilters(null);
assertEquals("rowCount must be original", rows, table.getRowCount());
table.getValueAt(rows - 1, 0);
}
/**
* Issue #134: JXTable - default renderers not loaded.
* To fix the issue the JXTable internal renderers' access scope
* was changed to public. Note: if the JTable internal renderers
* access scope were to be widened then this test has to be changed
* (the comparing class are hardcoded).
*
*/
public void testLazyRenderersByClass() {
JXTable table = new JXTable();
assertEquals("default Boolean renderer", JXTable.BooleanRenderer.class, table.getDefaultRenderer(Boolean.class).getClass());
assertEquals("default Number renderer", JXTable.NumberRenderer.class, table.getDefaultRenderer(Number.class).getClass());
assertEquals("default Double renderer", JXTable.DoubleRenderer.class, table.getDefaultRenderer(Double.class).getClass());
assertEquals("default Date renderer", JXTable.DateRenderer.class, table.getDefaultRenderer(Date.class).getClass());
assertEquals("default LinkModel renderer", LinkRenderer.class, table.getDefaultRenderer(LinkModel.class).getClass());
assertEquals("default Icon renderer", JXTable.IconRenderer.class, table.getDefaultRenderer(Icon.class).getClass());
}
/**
* Issue #150: setting filters must not re-create columns.
*
*/
public void testTableColumnsWithFilters() {
JXTable table = new JXTable(tableModel);
assertEquals("table columns are equal to columns of model",
tableModel.getColumnCount(), table.getColumnCount());
TableColumn column = table.getColumnExt(0);
table.removeColumn(column);
int columnCountAfterRemove = table.getColumnCount();
assertEquals("table columns must be one less than columns of model",
tableModel.getColumnCount() - 1, columnCountAfterRemove);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, false), // column 1, descending
}));
assertEquals("table columns must be unchanged after setting filter",
columnCountAfterRemove, table.getColumnCount());
}
/**
* hmm... sporadic ArrayIndexOOB after sequence:
*
* filter(column), sort(column), hide(column), setFilter(null)
*
*/
public void testColumnControlAndFilters() {
final JXTable table = new JXTable(sortableTableModel);
table.setColumnControlVisible(true);
Filter filter = new PatternFilter(".*e.*", 0, 0);
table.setFilters(new FilterPipeline(new Filter[] {filter}));
// needed to make public in JXTable for testing
// table.getTable().setSorter(0);
table.getColumnExt(0).setVisible(false);
table.setFilters(null);
}
/**
* example mixed sorting (Jens Elkner).
*
*/
public void interactiveTestSorterPatch() {
Object[][] fourWheels = new Object[][]{
new Object[] {"Car", new Car(180f)},
new Object[] {"Porsche", new Porsche(170)},
new Object[] {"Porsche", new Porsche(170)},
new Object[] {"Porsche", new Porsche(170, false)},
new Object[] {"Tractor", new Tractor(20)},
new Object[] {"Tractor", new Tractor(10)},
};
DefaultTableModel model = new DefaultTableModel(fourWheels, new String[] {"Text", "Car"}) ;
JXTable table = new JXTable(model);
JFrame frame = wrapWithScrollingInFrame(table, "Sorter patch");
frame.setVisible(true);
}
public class Car implements Comparable<Car> {
float speed = 100;
public Car(float speed) { this.speed = speed; }
public int compareTo(Car o) {
return speed < o.speed ? -1 : speed > o.speed ? 1 : 0;
}
public String toString() {
return "Car - " + speed;
}
}
public class Porsche extends Car {
boolean hasBridgeStone = true;
public Porsche(float speed) { super(speed); }
public Porsche(float speed, boolean bridgeStone) {
this(speed);
hasBridgeStone = bridgeStone;
}
public int compareTo(Car o) {
if (o instanceof Porsche) {
return ((Porsche) o).hasBridgeStone ? 0 : 1;
}
return super.compareTo(o);
}
public String toString() {
return "Porsche - " + speed + (hasBridgeStone ? "+" : "");
}
}
public class Tractor implements Comparable<Tractor> {
float speed = 20;
public Tractor(float speed) { this.speed = speed; }
public int compareTo(Tractor o) {
return speed < o.speed ? -1 : speed > o.speed ? 1 : 0;
}
public String toString() {
return "Tractor - " + speed;
}
}
/**
* Issue #179: Sorter does not use collator if cell content is
* a String.
*
*/
public void interactiveTestLocaleSorter() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, "aa" },
new Object[] { Boolean.FALSE, "AB" },
new Object[] { Boolean.FALSE, "AC" },
new Object[] { Boolean.TRUE, "BA" },
new Object[] { Boolean.FALSE, "BB" },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
// public Class getColumnClass(int column) {
// return column == 1 ? String.class : super.getColumnClass(column);
final JXTable table = new JXTable(model);
table.setSorter(1);
JFrame frame = wrapWithScrollingInFrame(table, "locale sorting");
frame.setVisible(true);
}
/**
* Issue #??: Problems with filters and ColumnControl
*
* - sporadic ArrayIndexOOB after sequence:
* filter(column), sort(column), hide(column), setFilter(null)
*
* - filtering invisible columns? Unclear state transitions.
*
*/
public void interactiveTestColumnControlAndFilters() {
final JXTable table = new JXTable(sortableTableModel);
// hmm bug regression with combos as editors - same in JTable
// JComboBox box = new JComboBox(new Object[] {"one", "two", "three" });
// box.setEditable(true);
// table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box));
Action toggleFilter = new AbstractAction("Toggle Filter") {
public void actionPerformed(ActionEvent e) {
if (table.getFilters() != null) {
table.setFilters(null);
} else {
Filter filter = new PatternFilter(".*e.*", 0, 0);
table.setFilters(new FilterPipeline(new Filter[] {filter}));
}
}
};
toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible ");
table.setColumnControlVisible(true);
JFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters");
addAction(frame, toggleFilter);
frame.setVisible(true);
}
/**
* Issue #11: Column control not showing with few rows.
*
*/
public void interactiveTestColumnControlFewRows() {
final JXTable table = new JXTable();
Action toggleAction = new AbstractAction("Toggle Control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
JFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* check behaviour outside scrollPane
*
*/
public void interactiveTestColumnControlWithoutScrollPane() {
final JXTable table = new JXTable();
Action toggleAction = new AbstractAction("Toggle Control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane");
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
JFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* check behaviour of moving into/out of scrollpane.
*
*/
public void interactiveTestToggleScrollPaneWithColumnControlOn() {
final JXTable table = new JXTable();
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
final JFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on");
Action toggleAction = new AbstractAction("Toggle ScrollPane") {
public void actionPerformed(ActionEvent e) {
Container parent = table.getParent();
boolean inScrollPane = parent instanceof JViewport;
if (inScrollPane) {
JScrollPane scrollPane = (JScrollPane) table.getParent().getParent();
frame.getContentPane().remove(scrollPane);
frame.getContentPane().add(table);
} else {
parent.remove(table);
parent.add(new JScrollPane(table));
}
frame.pack();
}
};
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue #192: initially invisibility columns are hidden
* but marked as visible in control.
*
* Issue #38 (swingx): initially invisble columns don't show up
* in the column control list.
*/
public void interactiveTestColumnControlInvisibleColumns() {
final JXTable table = new JXTable(sortableTableModel);
// table.getColumnExt("Last Name").setVisible(false);
table.setColumnControlVisible(true);
// JComponent columnControl = table.getColumnControl();
int totalColumnCount = table.getColumnCount();
TableColumnExt priorityColumn = table.getColumnExt("First Name");
priorityColumn.setVisible(false);
// assertNotNull("popup menu not null", columnControl.popupMenu);
// assertEquals("menu items must be equal to columns", totalColumnCount,
// columnControl.popupMenu.getComponentCount());
// JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) columnControl.popupMenu
// .getComponent(1);
// // sanit assert
// assertEquals(priorityColumn.getHeaderValue(), menuItem.getText());
// assertEquals("selection of menu must be equal to column visibility",
// priorityColumn.isVisible(), menuItem.isSelected());
JFrame frame = wrapWithScrollingInFrame(table, "JXTable (#192) ColumnControl and Visibility");
frame.setVisible(true);
}
public void interactiveTestRolloverHighlight() {
JXTable table = new JXTable(sortableTableModel);
table.setRolloverEnabled(true);
table.setHighlighters(new HighlighterPipeline(new Highlighter[]
{new RolloverHighlighter(Color.YELLOW, null)} ));
JFrame frame = wrapWithScrollingInFrame(table, "rollover highlight");
frame.setVisible(true);
}
/**
* Issue #31 (swingx): clicking header must not sort if table !enabled.
*
*/
public void interactiveTestDisabledTableSorting() {
final JXTable table = new JXTable(sortableTableModel);
Action toggleAction = new AbstractAction("Toggle Enabled") {
public void actionPerformed(ActionEvent e) {
table.setEnabled(!table.isEnabled());
}
};
JFrame frame = wrapWithScrollingInFrame(table, "Disabled tabled: no sorting");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue #191: sorting and custom renderer
* not reproducible ...
*
*/
public void interactiveTestCustomRendererSorting() {
JXTable table = new JXTable(sortableTableModel);
TableColumn column = table.getColumn("No.");
TableCellRenderer renderer = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
value = "# " + value ;
Component comp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col );
return comp;
}
};
column.setCellRenderer(renderer);
JFrame frame = wrapWithScrollingInFrame(table, "RendererSortingTest");
frame.setVisible(true); // RG: Changed from deprecated method show();
}
public void interactiveTestToggleSortingEnabled() {
final JXTable table = new JXTable(sortableTableModel);
Action toggleSortableAction = new AbstractAction("Toggle Sortable") {
public void actionPerformed(ActionEvent e) {
table.setSortable(!table.isSortable());
}
};
JFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test");
addAction(frame, toggleSortableAction);
frame.setVisible(true); // RG: Changed from deprecated method show();
}
public void interactiveTestTableSizing1() {
JXTable table = new JXTable();
table.setAutoCreateColumnsFromModel(false);
table.setModel(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()];
for (int i = 0; i < columns.length; i++) {
columns[i] = new TableColumnExt(i);
table.addColumn(columns[i]);
}
columns[0].setPrototypeValue(new Integer(0));
columns[1].setPrototypeValue("Simple String Value");
columns[2].setPrototypeValue(new Integer(1000));
columns[3].setPrototypeValue(Boolean.TRUE);
columns[4].setPrototypeValue(new Date(100));
columns[5].setPrototypeValue(new Float(1.5));
columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank",
tableModel.linkURL));
columns[7].setPrototypeValue(new Integer(3023));
columns[8].setPrototypeValue("John Doh");
columns[9].setPrototypeValue("23434 Testcase St");
columns[10].setPrototypeValue(new Integer(33333));
columns[11].setPrototypeValue(Boolean.FALSE);
table.setVisibleRowCount(12);
JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test");
frame.setVisible(true);
}
public void interactiveTestTableSizing2() {
JXTable table = new JXTable();
table.setAutoCreateColumnsFromModel(false);
table.setModel(tableModel);
TableColumnExt columns[] = new TableColumnExt[6];
int viewIndex = 0;
for (int i = columns.length - 1; i >= 0; i
columns[viewIndex] = new TableColumnExt(i);
table.addColumn(columns[viewIndex++]);
}
columns[5].setHeaderValue("String Value");
columns[5].setPrototypeValue("9999");
columns[4].setHeaderValue("String Value");
columns[4].setPrototypeValue("Simple String Value");
columns[3].setHeaderValue("Int Value");
columns[3].setPrototypeValue(new Integer(1000));
columns[2].setHeaderValue("Bool");
columns[2].setPrototypeValue(Boolean.FALSE);
//columns[2].setSortable(false);
columns[1].setHeaderValue("Date");
columns[1].setPrototypeValue(new Date(0));
//columns[1].setSortable(false);
columns[0].setHeaderValue("Float");
columns[0].setPrototypeValue(new Float(5.5));
table.setRowHeight(24);
table.setRowMargin(2);
JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test");
frame.setVisible(true);
}
public void interactiveTestTableAlternateHighlighter1() {
JXTable table = new JXTable(tableModel);
table.setRowHeight(22);
table.setRowMargin(1);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true) // column 0, ascending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.
linePrinter,
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableAlternateRowHighlighter1 Test");
frame.setVisible(true);
}
public void interactiveTestTableAlternateRowHighlighter2() {
JXTable table = new JXTable(tableModel);
table.setRowHeight(22);
table.setRowMargin(1);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, false), // column 1, descending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.classicLinePrinter,
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableAlternateRowHighlighter2 Test");
frame.setVisible(true);
}
public void interactiveTestTableSorter1() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.notePadBackground,
}));
table.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad
table.setGridColor(Color.cyan.darker());
table.setRowHeight(22);
table.setRowMargin(1);
table.setShowHorizontalLines(true);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true), // column 0, ascending
new ShuttleSorter(1, true), // column 1, ascending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter1 col 0= asc, col 1 = asc");
frame.setVisible(true);
}
public void interactiveTestTableSorter2() {
JXTable table = new JXTable(sortableTableModel);
table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
table.setGridColor(Color.cyan.darker());
table.setRowHeight(22);
table.setRowMargin(1);
table.setShowHorizontalLines(true);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true), // column 0, ascending
new ShuttleSorter(1, false), // column 1, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter2 col 0 = asc, col 1 = desc");
frame.setVisible(true);
}
public void interactiveTestFocusedCellBackground() {
TableModel model = new AncientSwingTeam() {
public boolean isCellEditable(int row, int column) {
return column != 0;
}
};
JXTable xtable = new JXTable(model);
// BasicLookAndFeel lf;
xtable.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
JTable table = new JTable(model);
table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable");
frame.setVisible(true);
}
public void interactiveTestTableSorter3() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new Highlighter(Color.orange, null),
}));
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, true), // column 1, ascending
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter3 col 1 = asc, col 0 = desc");
frame.setVisible(true);
}
public void interactiveTestTableSorter4() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new Highlighter(Color.orange, null),
}));
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, false), // column 0, descending
new ShuttleSorter(1, true), // column 1, ascending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter4 col 0 = des, col 1 = asc");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter1() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(1, 1));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("A.*", 0, 1)
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter1 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter2() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(2, 2));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("S.*", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter2 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter3() {
JXTable table = new JXTable(tableModel);
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("S.*", 0, 1),
new ShuttleSorter(1, false), // column 1, descending
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter3 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter4() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(3, 3));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("A.*", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter4 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter5() {
JXTable table = new JXTable(tableModel);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("S.*", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
new ShuttleSorter(1, true), // column 1, ascending
new ShuttleSorter(3, false), // column 3, descending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new PatternHighlighter(null, Color.red, "S.*", 0, 1),
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter5 Test");
frame.setVisible(true);
}
public void interactiveTestTableViewProperties() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(15, 15));
table.setRowHeight(48);
JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternHighlighter() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(15, 15));
table.setRowHeight(48);
table.setRowHeight(0, 96);
table.setShowGrid(true);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new PatternHighlighter(null, Color.red, "A.*", 0, 1),
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternHighlighter Test");
frame.setVisible(true);
}
public void interactiveTestTableColumnProperties() {
JXTable table = new JXTable();
table.setModel(tableModel);
table.getTableHeader().setBackground(Color.green);
table.getTableHeader().setForeground(Color.magenta);
table.getTableHeader().setFont(new Font("Serif", Font.PLAIN, 10));
ColumnHeaderRenderer headerRenderer = ColumnHeaderRenderer.createColumnHeaderRenderer();
headerRenderer.setHorizontalAlignment(JLabel.LEFT);
headerRenderer.setBackground(Color.blue);
headerRenderer.setForeground(Color.yellow);
headerRenderer.setIcon(new Icon() {
public int getIconWidth() {
return 12;
}
public int getIconHeight() {
return 12;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.red);
g.fillOval(0, 0, 10, 10);
}
});
headerRenderer.setIconTextGap(20);
headerRenderer.setFont(new Font("Serif", Font.BOLD, 18));
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumnExt column = table.getColumnExt(i);
if (i % 3 > 0) {
column.setHeaderRenderer(headerRenderer);
}
if (i % 2 > 0) {
TableCellRenderer cellRenderer =
table.getNewDefaultRenderer(table.getColumnClass(i));
if (cellRenderer instanceof JLabel || cellRenderer instanceof AbstractButton) {
JComponent labelCellRenderer = (JComponent)cellRenderer;
labelCellRenderer.setBackground(Color.gray);
labelCellRenderer.setForeground(Color.red);
if (cellRenderer instanceof JLabel) {
((JLabel) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER);
} else {
((AbstractButton) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER);
}
column.setCellRenderer(cellRenderer);
}
}
}
JFrame frame = wrapWithScrollingInFrame(table, "TableColumnProperties Test");
frame.setVisible(true);
}
public static class DynamicTableModel extends AbstractTableModel {
private Object columnSamples[];
private Object columnSamples2[];
public URL linkURL;
public static final int IDX_COL_LINK = 6;
public DynamicTableModel() {
try {
linkURL = new URL("http:
}
catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
columnSamples = new Object[12];
columnSamples[0] = new Integer(0);
columnSamples[1] = "Simple String Value";
columnSamples[2] = new Integer(1000);
columnSamples[3] = Boolean.TRUE;
columnSamples[4] = new Date(100);
columnSamples[5] = new Float(1.5);
columnSamples[IDX_COL_LINK] = new LinkModel("Sun Micro", "_blank", linkURL);
columnSamples[7] = new Integer(3023);
columnSamples[8] = "John Doh";
columnSamples[9] = "23434 Testcase St";
columnSamples[10] = new Integer(33333);
columnSamples[11] = Boolean.FALSE;
columnSamples2 = new Object[12];
columnSamples2[0] = new Integer(0);
columnSamples2[1] = "Another String Value";
columnSamples2[2] = new Integer(999);
columnSamples2[3] = Boolean.FALSE;
columnSamples2[4] = new Date(333);
columnSamples2[5] = new Float(22.22);
columnSamples2[IDX_COL_LINK] = new LinkModel("Sun Web", "new_frame", linkURL);
columnSamples[7] = new Integer(5503);
columnSamples[8] = "Jane Smith";
columnSamples[9] = "2343 Table Blvd.";
columnSamples[10] = new Integer(2);
columnSamples[11] = Boolean.TRUE;
}
public DynamicTableModel(Object columnSamples[]) {
this.columnSamples = columnSamples;
}
public Class getColumnClass(int column) {
return columnSamples[column].getClass();
}
public int getRowCount() {
return 1000;
}
public int getColumnCount() {
return columnSamples.length;
}
public Object getValueAt(int row, int column) {
Object value;
if (row % 3 == 0) {
value = columnSamples[column];
}
else {
value = columnSamples2[column];
}
return column == 0 ? new Integer(row >> 3) :
column == 3 ? new Boolean(row % 2 == 0) : value;
}
public boolean isCellEditable(int row, int column) {
return (column == 1);
}
public void setValueAt(Object aValue, int row, int column) {
if (column == 1) {
if (row % 3 == 0) {
columnSamples[column] = aValue;
}
else {
columnSamples2[column] = aValue;
}
}
this.fireTableDataChanged();
}
}
public static void main(String args[]) {
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (Exception e1) { // ignore
JXTableUnitTest test = new JXTableUnitTest();
try {
// test.runInteractiveTests();
// test.runInteractiveTests("interactive.*Column.*");
// test.runInteractiveTests("interactive.*TableHeader.*");
// test.runInteractiveTests("interactive.*SorterP.*");
test.runInteractiveTests("interactive.*Column.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
} |
package net.sourceforge.mayfly.acceptance;
import net.sourceforge.mayfly.util.StringBuilder;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class Dialect {
abstract public Connection openConnection() throws Exception;
abstract public Connection openAdditionalConnection() throws Exception;
public void assertTableCount(int expected) {
// Could probably do this with JDBC metadata or database-specific tricks.
// Not clear we should bother.
}
abstract public void shutdown(Connection connection) throws Exception;
public void assertMessage(String expectedMessage, SQLException exception) {
// To assert on this we'd need to keep lists of messages for many
// databases in many versions. That seems hard.
// But we would like to see that databases fail for the same
// reasons. So we provide the ability to manually inspect
// the messages side by side.
if (SqlTestCase.SHOW_MESSAGES) {
System.out.print("Mayfly message would be " + expectedMessage + "\n");
System.out.print("Actual message was " + exception.getMessage() + "\n\n");
}
else if (SqlTestCase.SHOW_STACK_TRACES) {
System.out.print("Mayfly message would be " + expectedMessage + "\n");
System.out.print("Actual exception was:\n");
printException(exception);
System.out.print("\n\n");
}
}
private void printException(SQLException exception) {
exception.printStackTrace(System.out);
System.out.print("SQL state was: " + exception.getSQLState() + "\n");
System.out.print("Vendor code was: " + exception.getErrorCode() + "\n");
if (exception.getNextException() != null) {
// Is it really true that next exceptions are not related to
// causes? Or is that just an artifact of libgcj 4.0.2?
printException(exception.getNextException());
}
}
public boolean backslashInAStringIsAnEscape() {
// For most SQL dialects (including SQL92 I believe), '\' is just a string
// with one character in it.
/** Note that there are security considerations to this choice; an application
trying to prevent SQL injection must use database-specific quoting
(or, setString) */
return false;
}
public boolean isReservedWord(String word) {
// War on reserved words: they can make it quite a pain to
// port SQL from one implementation to another. Mayfly's
// rule of thumb: Don't put big kluges in the parser to
// avoid a reserved word, but make words non-reserved
// where feasible.
// A few specific cases:
// LIMIT needs/wants to be a reserved word, but there is no
// particular need for OFFSET to be (unless just for symmetry
// with LIMIT or something).
return false;
}
public boolean tableNamesMightBeCaseSensitive() {
return false;
}
public boolean detectsAmbiguousColumns() {
return true;
}
/**
* @internal
* Should a test look for behavior in which Mayfly intentionally diverges
* from what other databases do.
*
* (In most case it makes more sense to have an individual test for a specific questions
* like detectsAmbiguousColumns or whatever). */
public boolean expectMayflyBehavior() {
return false;
}
/**
* @internal
* This is how we mark things where Mayfly doesn't yet implement the behavior
* which is desired for Mayfly. So for non-Mayfly databases, there is no
* "wish" to be marked.
*/
boolean wishThisWereTrue() {
return true;
}
public boolean crossJoinRequiresOn() {
return false;
}
public boolean crossJoinCanHaveOn() {
return false;
}
public boolean innerJoinRequiresOn() {
return true;
}
public boolean rightHandArgumentToJoinCanBeJoin() {
return true;
}
public boolean onIsRestrictedToJoinsTables() {
return true;
}
public boolean considerTablesMentionedAfterJoin() {
return false;
}
boolean onCanMentionOutsideTable() {
return !onIsRestrictedToJoinsTables();
}
public boolean detectsSyntaxErrorsInPrepareStatement() {
return true;
}
public boolean requiresAllParameters() {
return true;
}
public boolean stringComparisonsAreCaseInsensitive() {
return false;
}
public boolean notBindsMoreTightlyThanIn() {
return false;
}
public boolean orderByCountsAsWhat() {
return false;
}
public boolean haveLimit() {
// Interestingly enough, the majority of my test databases
// do have this, in a more or less compatible fashion.
return true;
}
public boolean canHaveLimitWithoutOrderBy() {
return false;
}
public boolean fromIsOptional() {
return false;
}
public boolean verticalBarsMeanConcatenation() {
return true;
}
public boolean maySpecifyTableDotColumnToJdbc() {
return false;
}
public boolean schemasMissing() {
return false;
}
public boolean canCreateSchemaAndTablesInSameStatement() {
// Not sure how clean/useful/popular this is.
return true;
}
public boolean authorizationAllowedInCreateSchema() {
return true;
}
public boolean authorizationRequiredInCreateSchema() {
return false;
}
public String createEmptySchemaCommand(String name) {
StringBuilder sql = new StringBuilder();
sql.append("create schema ");
sql.append(name);
if (authorizationRequiredInCreateSchema()) {
sql.append(" authorization dba");
}
return sql.toString();
}
public boolean aggregateDistinctIsForCountOnly() {
return false;
}
public boolean aggregateAsteriskIsForCountOnly() {
return true;
}
public boolean canSumStrings() {
return false;
}
public boolean errorIfNotAggregateOrGrouped() {
return true;
}
public boolean errorIfNotAggregateOrGroupedWhenGroupByExpression() {
return errorIfNotAggregateOrGrouped();
}
public boolean canGroupByExpression() {
return true;
}
public boolean canGroupByColumnAlias() {
return true;
}
public boolean canOrderByExpression() {
return false;
}
public boolean canGetValueViaExpressionName() {
return false;
}
public boolean allowCountDistinctStar() {
return false;
}
public boolean canQuoteIdentifiers() {
return true;
}
public boolean columnInHavingMustAlsoBeInSelect() {
return true;
}
public boolean canHaveHavingWithoutGroupBy() {
return false;
}
public boolean nullSortsLower() {
// I don't know whether there are arguments pro or con on this.
// Different databases seem to disagree, and several make it
// configurable somehow.
return true;
}
public boolean disallowColumnAndAggregateInExpression() {
return true;
}
public boolean notRequiresBoolean() {
return true;
}
public boolean numberOfValuesMustMatchNumberOfColumns() {
return true;
}
public boolean canConcatenateStringAndInteger() {
// Most databases seem to allow this. I'm sure there
// are larger issues/tradeoffs here (like "do what I
// mean" versus avoiding surprises).
return true;
}
public boolean disallowNullsInExpressions() {
// If this is true, insist people say "null" rather than
// "5 + null". This may reduce confusion over the
// "null propagates up" semantics (or might just delay
// the time when people discover them :-)).
return true;
}
public boolean disallowNullOnRightHandSideOfIn() {
return true;
}
public boolean canGetValueViaExpression() {
return false;
}
protected boolean constraintCanHaveForwardReference() {
return true;
}
public boolean uniqueColumnMayBeNullable() {
return true;
}
public boolean allowMultipleNullsInUniqueColumn() {
// False is analogous to the GROUP BY model in which all rows
// with null go in a single group. It isn't clear whether this
// is the best way to treat null or not.
return false;
}
public boolean allowUniqueAsPartOfColumnDeclaration() {
return true;
}
public boolean haveUpdateDefault() {
return true;
}
public boolean quotedIdentifiersAreCaseSensitive() {
// I guess SQL92 says this should be true.
// Perhaps a bit tricky to get this true, and still have
// messages case-preserving in general.
return false;
}
public boolean haveTransactions() {
/**
* @internal
* Should we be testing {@link Connection#getTransactionIsolation()}
* and {@link Connection#setTransactionIsolation(int)} ?
* Need to do more testing, but the issue is whether most/any
* databases will indicate what they can do, or change their
* behavior based on this setting. In a case like MySQL,
* transaction capability is per-table, for one thing.
*
* Anyway, for now we set the isolation level appropriate for
* each test, but in terms of figuring out what the database
* can do, we have methods here.
*/
return true;
}
public boolean willReadUncommitted() {
return false;
}
public boolean willWaitForWriterToCommit() {
return false;
}
public String databaseTypeForForeignKeys() {
return "";
}
public boolean haveTinyint() {
return true;
}
public boolean haveTextType() {
return true;
}
/** Is there a command DROP TABLE name IF EXISTS (with IF EXISTS after the name)? */
public boolean haveDropTableFooIfExists() {
return true;
}
/** Is there a command DROP TABLE IF EXISTS name (with IF EXISTS before the name)? */
public boolean haveDropTableIfExistsFoo() {
return true;
}
public boolean defaultValueCanBeExpression() {
// Who does this besides postgres?
// The postgres manual gives two examples: setting a date to now() (the
// SQL92 way seems to be CURRENT_DATE/CURRENT_TIME/CURRENT_TIMESTAMP,
// which is specifically allowed as a default value),
// and auto-increment (but is the default-value-as-expression way of
// doing it one that we want to try to have?).
return false;
}
public boolean canUpdateToDefault() {
return true;
}
public boolean allowJdbcParameterAsDefault() {
return false;
}
public boolean notNullImpliesDefaults() {
return false;
}
public boolean haveAutoUnderbarIncrement() {
return false;
}
public boolean haveSerial() {
return false;
}
public boolean haveIdentity() {
return false;
}
public boolean haveSql200xAutoIncrement() {
return false;
}
public boolean autoIncrementIsRelativeToLastValue() {
// Not sure what the arguments on either side of
// this one are. (If not relative to the last
// inserted value, it is a sequence, which is
// independent of what was explicitly inserted).
return false;
}
public boolean decimalScaleIsFromType() {
// False is just bugginess, as far as I know.
return true;
}
} |
package com.threerings.gwt.ui;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Reveals another widget via a sliding down animation.
*/
public class RevealPanel extends SimplePanel
{
/** Anchor constants. */
public enum Anchor { TOP, BOTTOM }
/**
* Creates a panel that will reveal (and hide) the supplied target widget with a vertical wipe
* animation.
*/
public RevealPanel (Widget target)
{
this(DEFAULT_ANIM_TIME, target);
}
/**
* Creates a panel that will reveal (and hide) the supplied target with a vertical wipe
* animation that lasts the specified number of milliseconds.
*/
public RevealPanel (int animTime, Widget target)
{
_animTime = animTime;
add(target);
}
/**
* Reveals the target widget with a vertical wipe. The panel will be height zero when the
* animation starts and the full height of the target when it completes.
*
* @param anchor if TOP the top of the widget will remain in place as the bottom is revealed,
* if BOTTOM, the bottom of the widget will move along with the wipe as if the widget was being
* slid down onto the screen.
* @param onComplete an optional command to execute when the animation is completd.
*/
public void reveal (Anchor anchor, Command onComplete)
{
new WipeAnimation(anchor, onComplete) {
@Override protected void onStart () {
DOM.setStyleAttribute(getElement(), "height", "0px");
super.onStart();
}
@Override protected void onUpdate (double progress) {
// the target may not be fully laid out when we start so we update our target
// height every frame so that we eventually know how big we want to be; this can
// result in a little jitter at the start of the animation but usually isn't bad
_targetHeight = getWidget().getOffsetHeight();
super.onUpdate(progress);
}
@Override protected int computeCurHeight (double progress) {
return (int) (progress * _targetHeight);
}
}.run(_animTime);
}
/** Convienence form of {@link #reveal}. */
public void revealFromTop ()
{
reveal(Anchor.TOP, null);
}
/** Convienence form of {@link #reveal}. */
public void revealFromTop (Command onComplete)
{
reveal(Anchor.TOP, onComplete);
}
/** Convienence form of {@link #reveal}. */
public void revealFromBottom ()
{
reveal(Anchor.BOTTOM, null);
}
/** Convienence form of {@link #reveal}. */
public void revealFromBottom (Command onComplete)
{
reveal(Anchor.BOTTOM, onComplete);
}
/**
* Hides the target widget with a vertical wipe and then removes it from its parent panel when
* the animation completes.
*
* @param anchor if TOP the top of the widget will remain in place as the widget is hidden from
* the bottom up, if BOTTOM, the bottom of the widget will move along with the wipe as if the
* widget was being slid up off of the screen.
* @param onComplete an optional command to execute when the animation is completd.
*/
public void hideAndRemove (Anchor anchor, Command onComplete)
{
new WipeAnimation(anchor, onComplete) {
@Override protected int computeCurHeight (double progress) {
return (int) ((1-progress) * _targetHeight);
}
@Override protected void onComplete () {
super.onComplete();
((Panel)getParent()).remove(RevealPanel.this);
}
}.run(_animTime);
}
/** Convienence form of {@link #hideAndRemove}. */
public void hideAndRemoveFromTop ()
{
hideAndRemove(Anchor.TOP, null);
}
/** Convienence form of {@link #hideAndRemove}. */
public void hideAndRemoveFromTop (Command onComplete)
{
hideAndRemove(Anchor.TOP, onComplete);
}
/** Convienence form of {@link #hideAndRemove}. */
public void hideAndRemoveFromBottom ()
{
hideAndRemove(Anchor.BOTTOM, null);
}
/** Convienence form of {@link #hideAndRemove}. */
public void hideAndRemoveFromBottom (Command onComplete)
{
hideAndRemove(Anchor.BOTTOM, onComplete);
}
protected abstract class WipeAnimation extends Animation
{
public WipeAnimation (Anchor anchor, Command onComplete) {
_anchor = anchor;
_onComplete = onComplete;
}
protected abstract int computeCurHeight (double progress);
@Override // from Animation
protected void onStart () {
_targetHeight = getWidget().getOffsetHeight();
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
if (_anchor == Anchor.BOTTOM) {
DOM.setStyleAttribute(getWidget().getElement(), "position", "relative");
}
super.onStart();
}
@Override // from Animation
protected void onUpdate (double progress) {
int curHeight = computeCurHeight(progress);
DOM.setStyleAttribute(RevealPanel.this.getElement(), "height", curHeight + "px");
if (_anchor == Anchor.BOTTOM) {
DOM.setStyleAttribute(
getWidget().getElement(), "top", (curHeight - _targetHeight) + "px");
}
}
@Override // from Animation
protected void onComplete () {
super.onComplete();
DOM.setStyleAttribute(getElement(), "overflow", "auto");
DOM.setStyleAttribute(getElement(), "height", "auto");
if (_anchor == Anchor.BOTTOM) {
DOM.setStyleAttribute(getWidget().getElement(), "position", "static");
}
if (_onComplete != null) {
_onComplete.execute();
}
}
protected Anchor _anchor;
protected Command _onComplete;
protected int _targetHeight;
}
protected int _animTime;
protected static final int DEFAULT_ANIM_TIME = 500;
} |
package org.pocketcampus.plugin.moodle.server;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.pocketcampus.platform.launcher.server.PocketCampusServer;
import org.pocketcampus.platform.sdk.shared.utils.PostDataBuilder;
import org.pocketcampus.plugin.moodle.shared.Constants;
/**
* Implementation of FileService using Moodle's web service API.
*
* TODO: Check if the user has access to the requested file!
*
* @author Solal Pirelli <solal@pocketcampus.org>
*/
public final class FileServiceImpl implements FileService {
// Guards between the file name in the link we receive
private static final String FILE_NAME_LEFT_GUARD = "pluginfile.php";
private static final String FILE_NAME_RIGHT_GUARD = "?";
// Prefix for the download URL of a file, using Moodle's web service.
private static final String DOWNLOAD_URL_PREFIX = "http://moodle.epfl.ch/webservice/pluginfile.php";
// The key of the token parameter to download files
private static final String TOKEN_KEY = "token";
// Missing from Apache's HttpHeaders constant for some reason
private static final String HTTP_CONTENT_DISPOSITION = "Content-Disposition";
private final String token;
public FileServiceImpl(final String token) {
this.token = token;
}
@Override
public void download(final HttpServletRequest request, final HttpServletResponse response) {
try {
final String gaspar = PocketCampusServer.authGetUserGasparFromReq(request);
if (gaspar == null) {
response.setStatus(HttpURLConnection.HTTP_PROXY_AUTH);
return;
}
final String action = request.getParameter(Constants.MOODLE_RAW_ACTION_KEY);
String filePath = request.getParameter(Constants.MOODLE_RAW_FILE_PATH);
if (!Constants.MOODLE_RAW_ACTION_DOWNLOAD_FILE.equals(action) || filePath == null) {
response.setStatus(HttpURLConnection.HTTP_BAD_METHOD);
return;
}
filePath = StringUtils.substringBetween(filePath, FILE_NAME_LEFT_GUARD, FILE_NAME_RIGHT_GUARD);
filePath = DOWNLOAD_URL_PREFIX + filePath;
final HttpURLConnection conn = (HttpURLConnection) new URL(filePath).openConnection();
conn.setDoOutput(true);
final byte[] bytes = new PostDataBuilder()
.addParam(TOKEN_KEY, token)
.toBytes();
conn.getOutputStream().write(bytes);
conn.connect();
response.setContentType(conn.getContentType());
response.setContentLength(conn.getContentLength());
// "a means for the origin server to suggest a default filename if the user requests that the content is saved to a file"
response.addHeader(HTTP_CONTENT_DISPOSITION, conn.getHeaderField(HTTP_CONTENT_DISPOSITION));
InputStream in = null;
OutputStream out = null;
try {
in = conn.getInputStream();
out = response.getOutputStream();
IOUtils.copy(in, out);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
} catch (Exception _) {
// This is ugly, but it shouldn't ever be triggered anyway
response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
}
}
} |
package jade.core;
import jade.lang.acl.ACLMessage;
import jade.security.AuthException;
/**
This interface represent the whole platform as seen by a
<code>Container</code>.
It provides methods that allows a <code>Container</code> to
register/deregister to the platform, dispatch a message to an
<code>Agent</code> living somewhere in the platform and notify
the platform that an agent has born/died/moved or that an MTP
has been installed/removed.
@see MainContainer
@see MainContainerImpl
@see MainContainerProxy
@author Giovanni Caire - TILAB
*/
interface Platform {
void addLocalContainer(NodeDescriptor desc) throws IMTPException, AuthException;
void removeLocalContainer() throws IMTPException;
void startSystemAgents(AgentContainerImpl ac) throws IMTPException, NotFoundException, AuthException;
} |
package org.jcoderz.commons;
import org.jcoderz.commons.util.HashCodeUtil;
/**
* This is the base class for audit log events.
*
* <p>The base class of this AuditLogEvent is Throwable but instances
* of this class are not expected to be thrown.</p>
*
* <p>Most functionality is implemented and documented by the
* {@link org.jcoderz.commons.LoggableImpl} which is used a member of
* objects of this class.</p>
*
* @see org.jcoderz.commons
* @author Andreas Mandel
* @author Michael Griffel
*/
public class AuditLogEvent
extends LogEvent
{
/** Key used for the audit principal parameter object. */
public static final String AUDIT_PRINCIPAL_PARAMETER_NAME
= "_AUDIT_PRINCIPAL";
/**
* The class fingerprint that is set to indicate serialization
* compatibility with a previous version of the class.
* Corresponds to CVS revision 1.3 of the class.
*/
static final long serialVersionUID = 3L;
/** the principal of the AuditLogEvent */
private final AuditPrincipal mAuditPrincipal;
/** The hashcode value, lazy initialized. */
private transient int mLazyHashCode = 0;
/**
* Constructor to create a AuditLogEvent instance with the minimum
* mandatory parameters.
* @param messageInfo the log message info of this audit log event.
* @param principal the audit principal that cause this audit log event.
*/
public AuditLogEvent (LogMessageInfo messageInfo, AuditPrincipal principal)
{
super(messageInfo);
mAuditPrincipal = principal;
addParameter(AUDIT_PRINCIPAL_PARAMETER_NAME, principal);
}
/**
* Constructor to create a AuditLogEvent instance with a
* given root <tt>cause</tt>.
* @param messageInfo the log message info of this audit log event.
* @param principal the audit principal that cause this audit log event.
* @param cause the cause of this audit log event.
*/
public AuditLogEvent (LogMessageInfo messageInfo, AuditPrincipal principal,
Throwable cause)
{
super(messageInfo, cause);
mAuditPrincipal = principal;
addParameter(AUDIT_PRINCIPAL_PARAMETER_NAME, principal);
}
/**
* Returns the audit principal of this audit log event.
* @return the audit principal of this audit log event.
*/
public final AuditPrincipal getAuditPrincipal ()
{
return mAuditPrincipal;
}
/**
* Indicates whether some other object is "equal to" this one.
*
* @param obj the object to compare to.
* @return true if this object is the same as the obj argument; false
* otherwise.
*/
public boolean equals (Object obj)
{
boolean equals = false;
if (obj instanceof AuditLogEvent)
{
final AuditLogEvent algEvent = (AuditLogEvent) obj;
if (mAuditPrincipal.equals(algEvent.getAuditPrincipal())
&& getLogMessageInfo().equals(algEvent.getLogMessageInfo())
&& getCause().equals(algEvent.getCause()))
{
equals = true;
}
}
return equals;
}
/**
* Override hashCode.
* @return the Object's hashcode.
*/
public int hashCode ()
{
if (mLazyHashCode == 0)
{
mLazyHashCode = HashCodeUtil.SEED;
mLazyHashCode = HashCodeUtil.hash(mLazyHashCode, mAuditPrincipal);
mLazyHashCode = HashCodeUtil.hash(mLazyHashCode, getLogMessageInfo());
mLazyHashCode = HashCodeUtil.hash(mLazyHashCode, getCause());
}
return mLazyHashCode;
}
} |
package com.redhat.ceylon.eclipse.imp.builder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.CommonTokenStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.imp.builder.BuilderBase;
import org.eclipse.imp.builder.MarkerCreator;
import org.eclipse.imp.language.Language;
import org.eclipse.imp.language.LanguageRegistry;
import org.eclipse.imp.model.IPathEntry;
import org.eclipse.imp.model.IPathEntry.PathEntryType;
import org.eclipse.imp.model.ISourceProject;
import org.eclipse.imp.model.ModelFactory;
import org.eclipse.imp.model.ModelFactory.ModelException;
import org.eclipse.imp.runtime.PluginBase;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.eclipse.imp.parser.CeylonTokenColorer;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
import com.redhat.ceylon.eclipse.util.ErrorVisitor;
import com.redhat.ceylon.eclipse.vfs.IFolderVirtualFile;
import com.redhat.ceylon.eclipse.vfs.ResourceVirtualFile;
/**
* A builder may be activated on a file containing ceylon code every time it has
* changed (when "Build automatically" is on), or when the programmer chooses to
* "Build" a project.
*
* TODO This default implementation was generated from a template, it needs to
* be completed manually.
*/
public class CeylonBuilder extends BuilderBase {
/**
* Extension ID of the Ceylon builder, which matches the ID in the
* corresponding extension definition in plugin.xml.
*/
public static final String BUILDER_ID = CeylonPlugin.PLUGIN_ID
+ ".ceylonBuilder";
/**
* A marker ID that identifies problems detected by the builder
*/
public static final String PROBLEM_MARKER_ID = CeylonPlugin.PLUGIN_ID
+ ".ceylonProblem";
public static final String LANGUAGE_NAME = "ceylon";
public static final Language LANGUAGE = LanguageRegistry
.findLanguage(LANGUAGE_NAME);
private final Collection<IFile> fSourcesToCompileTogether = new HashSet<IFile>();
private final static Map<IProject, TypeChecker> typeCheckers = new HashMap<IProject, TypeChecker>();
public static List<PhasedUnit> getUnits(IProject project) {
List<PhasedUnit> result = new ArrayList<PhasedUnit>();
TypeChecker tc = typeCheckers.get(project);
if (tc!=null) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
result.add(pu);
}
}
return result;
}
public static List<PhasedUnit> getUnits() {
List<PhasedUnit> result = new ArrayList<PhasedUnit>();
for (TypeChecker tc: typeCheckers.values()) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
result.add(pu);
}
}
return result;
}
/*public static PhasedUnit getPhasedUnit(IFile file) {
for (PhasedUnit pu: getUnits(file.getProject())) {
if (getFile(pu).getFullPath().equals(file.getFullPath())) {
return pu;
}
}
return null;
}*/
public static List<PhasedUnit> getUnits(String[] projects) {
List<PhasedUnit> result = new ArrayList<PhasedUnit>();
if (projects!=null) {
for (Map.Entry<IProject, TypeChecker> me: typeCheckers.entrySet()) {
for (String pname: projects) {
if (me.getKey().getName().equals(pname)) {
result.addAll(me.getValue().getPhasedUnits().getPhasedUnits());
}
}
}
}
return result;
}
protected PluginBase getPlugin() {
return CeylonPlugin.getInstance();
}
public String getBuilderID() {
return BUILDER_ID;
}
protected String getErrorMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getWarningMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getInfoMarkerID() {
return PROBLEM_MARKER_ID;
}
// returns workspace-relative paths
private Collection<IPath> retrieveSourceFolders(
ISourceProject sourceProject) {
List<IPath> result = new ArrayList<IPath>();
List<IPathEntry> buildPath = sourceProject.getBuildPath();
for (IPathEntry buildPathEntry : buildPath) {
if (buildPathEntry.getEntryType().equals(
PathEntryType.SOURCE_FOLDER)) {
result.add(buildPathEntry.getPath().makeRelativeTo(sourceProject.getRawProject().getFullPath()));
}
}
return result;
}
private ISourceProject getSourceProject() {
ISourceProject sourceProject = null;
try {
sourceProject = ModelFactory.open(getProject());
} catch (ModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sourceProject;
}
/**
* Decide whether a file needs to be build using this builder. Note that
* <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should
* never return true for the same file.
*
* @return true iff an arbitrary file is a ceylon source file.
*/
protected boolean isSourceFile(IFile file) {
IPath path = file.getProjectRelativePath();
if (path == null)
return false;
if (!LANGUAGE.hasExtension(path.getFileExtension()))
return false;
ISourceProject sourceProject = getSourceProject();
if (sourceProject != null) {
Collection<IPath> sourceFolders = retrieveSourceFolders(sourceProject);
for (IPath sourceFolder : sourceFolders) {
if (sourceFolder.isPrefixOf(path)) {
return true;
}
}
}
return false;
}
/**
* Decide whether or not to scan a file for dependencies. Note:
* <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should
* never return true for the same file.
*
* @return true iff the given file is a source file that this builder should
* scan for dependencies, but not compile as a top-level compilation
* unit.
*
*/
protected boolean isNonRootSourceFile(IFile resource) {
return false;
}
/**
* Collects compilation-unit dependencies for the given file, and records
* them via calls to <code>fDependency.addDependency()</code>.
*/
protected void collectDependencies(IFile file) {
// String fromPath = file.getFullPath().toString();
/*getPlugin().writeInfoMsg(
"Collecting dependencies from ceylon file: " + file.getName());*/
// TODO: implement dependency collector
// E.g. for each dependency:
// fDependencyInfo.addDependency(fromPath, uponPath);
}
/**
* @return true iff this resource identifies the output folder
*/
protected boolean isOutputFolder(IResource resource) {
return resource.getFullPath().lastSegment().equals("target/classes");
}
@Override
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) {
IProject project = getProject();
ISourceProject sourceProject = getSourceProject();
if (sourceProject == null) {
return new IProject[0];
}
fSourcesToCompileTogether.clear();
IProject[] result = super.build(kind, args, monitor);
// parseController.getAnnotationTypeInfo().addProblemMarkerType(getErrorMarkerID());
switch (kind) {
case FULL_BUILD:
System.out.println("Starting full build");
typeCheckers.remove(project);
Collection<IPath> sourceFolders = retrieveSourceFolders(sourceProject);
TypeCheckerBuilder typeCheckerBuilder = new TypeCheckerBuilder()
.verbose(false);
for (IPath sourceFolder : sourceFolders) {
IFolderVirtualFile srcDir = new IFolderVirtualFile(project,
sourceFolder);
typeCheckerBuilder.addSrcDirectory(srcDir);
}
TypeChecker typeChecker = typeCheckerBuilder.getTypeChecker();
// Parsing of ALL units in the source folder should have been done
typeChecker.process();
typeCheckers.put(project, typeChecker);
for (PhasedUnit phasedUnit : typeChecker.getPhasedUnits().getPhasedUnits())
{
IFile file = getFile(phasedUnit);
CommonTokenStream tokens = phasedUnit.getTokenStream();
phasedUnit.getCompilationUnit()
.visit(new ErrorVisitor(new MarkerCreator(file, PROBLEM_MARKER_ID)) {
@Override
public int getSeverity(Message error) {
return IMarker.SEVERITY_ERROR;
}
});
addTaskMarkers(file, tokens);
}
System.out.println("Finished full build");
break;
}
return result;
}
private void addTaskMarkers(IFile file, CommonTokenStream tokens) {
//TODO: need our own marker type
try {
file.deleteMarkers(IMarker.TASK, false, IResource.DEPTH_INFINITE);
}
catch (CoreException e) {
e.printStackTrace();
}
for (CommonToken token: (List<CommonToken>) tokens.getTokens()) {
if (token.getType()==CeylonLexer.LINE_COMMENT) {
if (CeylonTokenColorer.isTodo(token)) {
new MarkerCreator(file, IMarker.TASK)
.handleSimpleMessage(token.getText().substring(2),
token.getStartIndex(), token.getStopIndex(),
token.getCharPositionInLine(), token.getCharPositionInLine(),
token.getLine(), token.getLine());
}
}
}
}
public static IFile getFile(PhasedUnit phasedUnit) {
return (IFile) ((ResourceVirtualFile) phasedUnit.getUnitFile()).getResource();
}
/**
* Compile one ceylon file.
*/
protected void compile(final IFile file, IProgressMonitor monitor) {
fSourcesToCompileTogether.add(file);
}
// generated files go into parent folder
public static TypeChecker getProjectTypeChecker(IProject project) {
return typeCheckers.get(project);
}
} |
package org.jcoderz.commons.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
/**
* Jar Utility class.
*
* @author Michael Griffel
* @author Andreas Mandel
*/
public final class JarUtils
{
private static final int BUFFER_SIZE = 4096;
/**
* Utility class - no instances allowed.
*/
private JarUtils ()
{
// no instances allowed -- provides only static helper functions
}
/**
* Extract a jar archive into the base directory
* <code>baseDir</code>.
*
* @param baseDir the root directory where the archive is extracted
* to.
* @param archive jar file.
* @throws IOException in case of an I/O error.
*/
public static void extractJarArchive (File baseDir, File archive)
throws IOException
{
final JarFile archiveFile = new JarFile(archive);
final List archiveEntries = Collections.list(archiveFile.entries());
for (final Iterator iterator = archiveEntries.iterator(); iterator
.hasNext();)
{
InputStream in = null;
FileOutputStream out = null;
try
{
final ZipEntry e = (ZipEntry) iterator.next();
in = archiveFile.getInputStream(e);
final File f = new File(baseDir, e.getName());
if (e.isDirectory())
{
if (!f.exists())
{
if (!f.mkdirs())
{
throw new IOException("Cannot create directory "
+ f);
}
}
}
else
{
if (!f.getParentFile().exists())
{
if (!f.getParentFile().mkdirs())
{
throw new IOException("Cannot create directory "
+ f.getParentFile());
}
}
out = new FileOutputStream(f);
copy(in, out);
}
}
finally
{
IoUtil.close(out);
IoUtil.close(in);
}
}
}
/**
* Creates a jar archive from the directory.
*
* @param baseDir for the jar archive.
* @param archive the jar file.
* @throws IOException in case of an I/O error.
*/
public static void createJarArchive (File baseDir, File archive)
throws IOException
{
JarOutputStream jarArchive = null;
try
{
jarArchive = new JarOutputStream(new FileOutputStream(archive));
addFileToJar(baseDir, baseDir, jarArchive);
}
finally
{
IoUtil.close(jarArchive);
}
}
private static void addFileToJar (File baseDir, File file,
JarOutputStream archive)
throws IOException
{
if (file == null)
{
// done
}
else if (file.isDirectory())
{
String path = FileUtils.getRelativePath(baseDir, file);
if (!path.equals("/") && !path.equals(""))
{
if (!path.endsWith("/"))
{
path += "/";
}
final JarEntry entry = new JarEntry(path);
archive.putNextEntry(entry);
archive.closeEntry();
}
final File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
addFileToJar(baseDir, files[i], archive);
}
}
else
{
final String path = FileUtils.getRelativePath(baseDir, file);
final JarEntry entry = new JarEntry(path);
archive.putNextEntry(entry);
InputStream in = null;
try
{
in = new FileInputStream(file);
copy(in, archive);
}
finally
{
IoUtil.close(in);
}
archive.closeEntry();
}
}
/**
* Copies the content of the input stream <code>in</code> to the
* output stream <code>out</code>.
*
* @param in input stream.
* @param out output stream.
* @throws IOException in case of an I/O error.
*/
private static void copy (InputStream in, OutputStream out)
throws IOException
{
final byte[] buffer = new byte[BUFFER_SIZE];
int nread;
while ((nread = in.read(buffer)) != -1)
{
out.write(buffer, 0, nread);
}
}
} |
package jade.tools.rma;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.InputStreamReader;
import jade.util.leap.List;
import jade.util.leap.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import jade.util.leap.Iterator;
import java.net.URL;
import jade.util.Logger;
import jade.core.*;
import jade.core.behaviours.*;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.JADEAgentManagement.*;
import jade.domain.introspection.*;
import jade.domain.persistence.*;
import jade.domain.mobility.*;
import jade.domain.FIPANames;
import jade.gui.AgentTreeModel;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.content.onto.basic.Result;
import jade.content.onto.basic.Action;
import jade.proto.SimpleAchieveREInitiator;
import jade.tools.ToolAgent;
import jade.security.JADEPrincipal;
import jade.security.SDSIName;
/**
<em>Remote Management Agent</em> agent. This class implements
<b>JADE</b> <em>RMA</em> agent. <b>JADE</b> applications cannot use
this class directly, but interact with it through <em>ACL</em>
message passing. Besides, this agent has a <em>GUI</em> through
which <b>JADE</b> Agent Platform can be administered.
@author Giovanni Rimassa - Universita' di Parma
@version $Date$ $Revision$
*/
public class rma extends ToolAgent {
private APDescription myPlatformProfile;
//logging
private static Logger logger = Logger.getMyLogger(rma.class.getName());
// Sends requests to the AMS
private class AMSClientBehaviour extends SimpleAchieveREInitiator {
private String actionName;
public AMSClientBehaviour(String an, ACLMessage request) {
super(rma.this, request);
actionName = an;
}
protected void handleNotUnderstood(ACLMessage reply) {
myGUI.showErrorDialog("NOT-UNDERSTOOD received by RMA during " + actionName, reply);
}
protected void handleRefuse(ACLMessage reply) {
myGUI.showErrorDialog("REFUSE received during " + actionName, reply);
}
protected void handleAgree(ACLMessage reply) {
logger.log(Logger.FINE,"AGREE received"+reply);
}
protected void handleFailure(ACLMessage reply) {
myGUI.showErrorDialog("FAILURE received during " + actionName, reply);
}
protected void handleInform(ACLMessage reply) {
logger.log(Logger.FINE,"INFORM received"+reply);
}
} // End of AMSClientBehaviour class
private class handleAddRemotePlatformBehaviour extends AMSClientBehaviour{
public handleAddRemotePlatformBehaviour(String an, ACLMessage request){
super(an,request);
}
protected void handleInform(ACLMessage msg){
logger.log(Logger.FINE,"arrived a new APDescription");
try{
AID sender = msg.getSender();
Result r =(Result)getContentManager().extractContent(msg);
Iterator i = r.getItems().iterator();
APDescription APDesc = (APDescription)i.next();
if(APDesc != null){
myGUI.addRemotePlatformFolder();
myGUI.addRemotePlatform(sender,APDesc);}
}catch(Exception e){
e.printStackTrace();
}
}
}//end handleAddRemotePlatformBehaviour
private class handleRefreshRemoteAgentBehaviour extends AMSClientBehaviour{
private APDescription platform;
public handleRefreshRemoteAgentBehaviour(String an, ACLMessage request,APDescription ap){
super(an,request);
platform = ap;
}
protected void handleInform(ACLMessage msg){
logger.log(Logger.FINE,"arrived a new agents from a remote platform");
try{
AID sender = msg.getSender();
Result r = (Result)getContentManager().extractContent(msg);
Iterator i = r.getItems().iterator();
myGUI.addRemoteAgentsToRemotePlatform(platform,i);
}catch(Exception e){
e.printStackTrace();
}
}
}//end handleAddRemotePlatformBehaviour
private SequentialBehaviour AMSSubscribe = new SequentialBehaviour();
private transient MainWindow myGUI;
private String myContainerName;
class RMAAMSListenerBehaviour extends AMSListenerBehaviour {
protected void installHandlers(Map handlersTable) {
// Fill the event handler table.
handlersTable.put(IntrospectionVocabulary.META_RESETEVENTS, new EventHandler() {
public void handle(Event ev) {
ResetEvents re = (ResetEvents)ev;
myGUI.resetTree();
}
});
handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, new EventHandler() {
public void handle(Event ev) {
AddedContainer ac = (AddedContainer)ev;
ContainerID cid = ac.getContainer();
String name = cid.getName();
String address = cid.getAddress();
try {
InetAddress addr = InetAddress.getByName(address);
myGUI.addContainer(name, addr);
}
catch(UnknownHostException uhe) {
myGUI.addContainer(name, null);
}
}
});
handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, new EventHandler() {
public void handle(Event ev) {
RemovedContainer rc = (RemovedContainer)ev;
ContainerID cid = rc.getContainer();
String name = cid.getName();
myGUI.removeContainer(name);
}
});
handlersTable.put(IntrospectionVocabulary.BORNAGENT, new EventHandler() {
public void handle(Event ev) {
BornAgent ba = (BornAgent)ev;
ContainerID cid = ba.getWhere();
String container = cid.getName();
AID agent = ba.getAgent();
myGUI.addAgent(container, agent);
myGUI.modifyAgent(container, agent, ba.getState(), ba.getOwnership());
if (agent.equals(getAID()))
myContainerName = container;
}
});
handlersTable.put(IntrospectionVocabulary.DEADAGENT, new EventHandler() {
public void handle(Event ev) {
DeadAgent da = (DeadAgent)ev;
ContainerID cid = da.getWhere();
String container = cid.getName();
AID agent = da.getAgent();
myGUI.removeAgent(container, agent);
}
});
handlersTable.put(IntrospectionVocabulary.SUSPENDEDAGENT, new EventHandler() {
public void handle(Event ev) {
SuspendedAgent sa = (SuspendedAgent)ev;
ContainerID cid = sa.getWhere();
String container = cid.getName();
AID agent = sa.getAgent();
myGUI.modifyAgent(container, agent, AMSAgentDescription.SUSPENDED, null);
}
});
handlersTable.put(IntrospectionVocabulary.RESUMEDAGENT, new EventHandler() {
public void handle(Event ev) {
ResumedAgent ra = (ResumedAgent)ev;
ContainerID cid = ra.getWhere();
String container = cid.getName();
AID agent = ra.getAgent();
myGUI.modifyAgent(container, agent, AMSAgentDescription.ACTIVE, null);
}
});
handlersTable.put(IntrospectionVocabulary.FROZENAGENT, new EventHandler() {
public void handle(Event ev) {
FrozenAgent fa = (FrozenAgent)ev;
String oldContainer = fa.getWhere().getName();
String newContainer = fa.getBufferContainer().getName();
AID agent = fa.getAgent();
myGUI.modifyFrozenAgent(oldContainer, newContainer, agent);
}
});
handlersTable.put(IntrospectionVocabulary.THAWEDAGENT, new EventHandler() {
public void handle(Event ev) {
ThawedAgent ta = (ThawedAgent)ev;
String oldContainer = ta.getWhere().getName();
String newContainer = ta.getBufferContainer().getName();
AID agent = ta.getAgent();
myGUI.modifyThawedAgent(oldContainer, newContainer, agent);
}
});
handlersTable.put(IntrospectionVocabulary.CHANGEDAGENTOWNERSHIP, new EventHandler() {
public void handle(Event ev) {
ChangedAgentOwnership cao = (ChangedAgentOwnership)ev;
ContainerID cid = cao.getWhere();
String container = cid.getName();
AID agent = cao.getAgent();
myGUI.modifyAgent(container, agent, null, cao.getTo());
}
});
handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, new EventHandler() {
public void handle(Event ev) {
MovedAgent ma = (MovedAgent)ev;
AID agent = ma.getAgent();
ContainerID from = ma.getFrom();
ContainerID to = ma.getTo();
myGUI.moveAgent(from.getName(), to.getName(), agent);
}
});
handlersTable.put(IntrospectionVocabulary.ADDEDMTP, new EventHandler() {
public void handle(Event ev) {
AddedMTP amtp = (AddedMTP)ev;
String address = amtp.getAddress();
ContainerID where = amtp.getWhere();
myGUI.addAddress(address, where.getName());
}
});
handlersTable.put(IntrospectionVocabulary.REMOVEDMTP, new EventHandler() {
public void handle(Event ev) {
RemovedMTP rmtp = (RemovedMTP)ev;
String address = rmtp.getAddress();
ContainerID where = rmtp.getWhere();
myGUI.removeAddress(address, where.getName());
}
});
//handle the APDescription provided by the AMS
handlersTable.put(IntrospectionVocabulary.PLATFORMDESCRIPTION, new EventHandler(){
public void handle(Event ev){
PlatformDescription pd = (PlatformDescription)ev;
APDescription APdesc = pd.getPlatform();
myPlatformProfile = APdesc;
myGUI.refreshLocalPlatformName(myPlatformProfile.getName());
}
});
}
} // END of inner class RMAAMSListenerBehaviour
/**
This method starts the <em>RMA</em> behaviours to allow the agent
to carry on its duties within <em><b>JADE</b></em> agent platform.
*/
protected void toolSetup() {
// Register the supported ontologies
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
// Send 'subscribe' message to the AMS
AMSSubscribe.addSubBehaviour(new SenderBehaviour(this, getSubscribe()));
// Handle incoming 'inform' messages
AMSSubscribe.addSubBehaviour(new RMAAMSListenerBehaviour());
// Schedule Behaviour for execution
addBehaviour(AMSSubscribe);
// Show Graphical User Interface
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
}
/**
Cleanup during agent shutdown. This method cleans things up when
<em>RMA</em> agent is destroyed, disconnecting from <em>AMS</em>
agent and closing down the platform administration <em>GUI</em>.
*/
protected void toolTakeDown() {
send(getCancel());
if (myGUI != null) {
// The following call was removed as it causes a threading
// deadlock with join. Its also not needed as the async
// dispose will do it.
// myGUI.setVisible(false);
myGUI.disposeAsync();
}
}
protected void beforeMove() {
super.beforeMove();
myGUI.disposeAsync();
send(getCancel());
}
protected void afterMove() {
super.afterMove();
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
// Make the AMS send back the whole container list
send(getSubscribe());
}
protected void afterClone() {
super.afterClone();
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
// Add yourself to the RMA list
ACLMessage AMSSubscription = getSubscribe();
send(AMSSubscription);
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
}
protected void afterLoad() {
super.afterLoad();
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
// Add yourself to the RMA list
ACLMessage AMSSubscription = getSubscribe();
send(AMSSubscription);
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
}
protected void beforeReload() {
super.beforeReload();
myGUI.disposeAsync();
send(getCancel());
}
protected void afterReload() {
super.afterReload();
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
// Make the AMS send back the whole container list
send(getSubscribe());
}
protected void beforeFreeze() {
super.beforeFreeze();
myGUI.disposeAsync();
send(getCancel());
}
protected void afterThaw() {
super.afterThaw();
getContentManager().registerOntology(MobilityOntology.getInstance());
getContentManager().registerOntology(PersistenceOntology.getInstance());
myGUI = new MainWindow(this);
myGUI.ShowCorrect();
// Make the AMS send back the whole container list
send(getSubscribe());
}
/**
Callback method for platform management <em>GUI</em>.
*/
public AgentTreeModel getModel() {
return myGUI.getModel();
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void newAgent(String agentName, String className, Object arg[], String containerName) {
CreateAgent ca = new CreateAgent();
if(containerName.equals(""))
containerName = AgentContainer.MAIN_CONTAINER_NAME;
// fill the create action with the intended agent owner
jade.security.JADEPrincipal intendedOwner = null;
jade.security.Credentials initialCredentials = null;
// the ownerName (this can come from the GUI)
final String ownerName="alice"; // TOFIX: AR, please replace this
if ((ownerName==null) || (ownerName.trim().length()==0)) {
// it is requested the creation of an agent
// with the same owner of the RMA
try {
jade.security.JADEPrincipal rmaOwner = null;
jade.security.Credentials rmaCredentials = null;
jade.security.CredentialsHelper ch = (jade.security.CredentialsHelper) getHelper("jade.core.security.Security");
// get RMA's owner
if (ch!=null) { rmaCredentials = ch.getCredentials(); }
if (rmaCredentials!=null) { rmaOwner = rmaCredentials.getOwner(); }
intendedOwner = rmaOwner;
}
catch (ServiceException se) { // Security service not present. Owner is null.
intendedOwner=null;
initialCredentials=null;
}
} else {
// it is requested the creation of an agent
// with a specified owner name
try
{
Class c = Class.forName("jade.security.impl.JADEPrincipalImpl");
System.out.println("Loaded class: " + c);
intendedOwner = (JADEPrincipal) c.newInstance();
java.lang.reflect.Method setName = c.getDeclaredMethod("setName", new Class[]{ String.class });
System.out.println("Got method: " + setName);
setName.invoke(intendedOwner, new Object[] {ownerName});
} catch (Exception e)
{
//e.printStackTrace();
// Security service not present. Owner is null.
intendedOwner=null;
initialCredentials=null;
}
}
ca.setOwner( intendedOwner );
ca.setInitialCredentials( initialCredentials );
ca.setAgentName(agentName);
ca.setClassName(className);
ca.setContainer(new ContainerID(containerName, null));
for(int i = 0; i<arg.length ; i++)
ca.addArguments((Object)arg[i]);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(ca);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("CreateAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void suspendAgent(AID name) {
AMSAgentDescription amsd = new AMSAgentDescription();
amsd.setName(name);
amsd.setState(AMSAgentDescription.SUSPENDED);
Modify m = new Modify();
m.setDescription(amsd);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(m);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(FIPAManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("SuspendAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void suspendContainer(String name) {
// FIXME: Not implemented
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void resumeAgent(AID name) {
AMSAgentDescription amsd = new AMSAgentDescription();
amsd.setName(name);
amsd.setState(AMSAgentDescription.ACTIVE);
Modify m = new Modify();
m.setDescription(amsd);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(m);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(FIPAManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("ResumeAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void changeAgentOwnership(AID name, String ownership) {
AMSAgentDescription amsd = new AMSAgentDescription();
amsd.setName(name);
amsd.setState(AMSAgentDescription.ACTIVE);//SUSPENDED);
amsd.setOwnership(ownership);
Modify m = new Modify();
m.setDescription(amsd);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(m);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(FIPAManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("ChangeAgentOwnership", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void resumeContainer(String name) {
// FIXME: Not implemented
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void killAgent(AID name) {
KillAgent ka = new KillAgent();
ka.setAgent(name);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(ka);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("KillAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void saveContainer(String name, String repository) {
SaveContainer saveAct = new SaveContainer();
saveAct.setContainer(new ContainerID(name, null));
saveAct.setRepository(repository);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(saveAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("SaveContainer", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void loadContainer(String name, String repository) {
LoadContainer saveAct = new LoadContainer();
saveAct.setContainer(new ContainerID(name, null));
saveAct.setRepository(repository);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(saveAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("LoadContainer", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void killContainer(String name) {
KillContainer kc = new KillContainer();
kc.setContainer(new ContainerID(name, null));
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(kc);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("KillContainer", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void moveAgent(AID name, String container)
{
MoveAction moveAct = new MoveAction();
MobileAgentDescription desc = new MobileAgentDescription();
desc.setName(name);
ContainerID dest = new ContainerID(container, null);
desc.setDestination(dest);
moveAct.setMobileAgentDescription(desc);
try{
Action a = new Action();
a.setActor(getAMS());
a.setAction(moveAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(MobilityOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("MoveAgent",requestMsg));
} catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void cloneAgent(AID name,String newName, String container)
{
CloneAction cloneAct = new CloneAction();
MobileAgentDescription desc = new MobileAgentDescription();
desc.setName(name);
ContainerID dest = new ContainerID(container, null);
desc.setDestination(dest);
cloneAct.setMobileAgentDescription(desc);
cloneAct.setNewName(newName);
try{
Action a = new Action();
a.setActor(getAMS());
a.setAction(cloneAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(MobilityOntology.NAME);
getContentManager().fillContent(requestMsg,a);
addBehaviour(new AMSClientBehaviour("CloneAgent",requestMsg));
} catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void saveAgent(AID name, String repository)
{
SaveAgent saveAct = new SaveAgent();
saveAct.setAgent(name);
saveAct.setRepository(repository);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(saveAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("SaveAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void loadAgent(AID name, String repository, String container)
{
LoadAgent loadAct = new LoadAgent();
loadAct.setAgent(name);
loadAct.setRepository(repository);
ContainerID where = new ContainerID(container, null);
loadAct.setWhere(where);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(loadAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("LoadAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void freezeAgent(AID name, String repository)
{
FreezeAgent freezeAct = new FreezeAgent();
freezeAct.setAgent(name);
freezeAct.setRepository(repository);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(freezeAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("FreezeAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management
*/
public void thawAgent(AID name, String repository, ContainerID newContainer)
{
ThawAgent thawAct = new ThawAgent();
thawAct.setAgent(name);
thawAct.setRepository(repository);
thawAct.setNewContainer(newContainer);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(thawAct);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(PersistenceVocabulary.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("ThawAgent", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void exit() {
if(myGUI.showExitDialog("Exit this container"))
killContainer(myContainerName);
}
/**
Callback method for platform management <em>GUI</em>.
*/
public void shutDownPlatform() {
if(myGUI.showExitDialog("Shut down the platform")) {
ShutdownPlatform sp = new ShutdownPlatform();
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(sp);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("ShutdownPlatform", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
}
public void installMTP(String containerName) {
InstallMTP imtp = new InstallMTP();
imtp.setContainer(new ContainerID(containerName, null));
if(myGUI.showInstallMTPDialog(imtp)) {
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(imtp);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("InstallMTP", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
}
public void uninstallMTP(String containerName) {
UninstallMTP umtp = new UninstallMTP();
umtp.setContainer(new ContainerID(containerName, null));
if(myGUI.showUninstallMTPDialog(umtp)) {
uninstallMTP(umtp.getContainer().getName(), umtp.getAddress());
}
}
public void uninstallMTP(String containerName, String address) {
UninstallMTP umtp = new UninstallMTP();
umtp.setContainer(new ContainerID(containerName, null));
umtp.setAddress(address);
try {
Action a = new Action();
a.setActor(getAMS());
a.setAction(umtp);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(JADEManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("UninstallMTP", requestMsg));
}
catch(Exception fe) {
fe.printStackTrace();
}
}
//this method sends a request to a remote AMS to know the APDescription of a remote Platform
public void addRemotePlatform(AID remoteAMS){
logger.log(Logger.FINE,"AddRemotePlatform"+remoteAMS.toString());
try{
ACLMessage requestMsg = new ACLMessage(ACLMessage.REQUEST);
requestMsg.setSender(getAID());
requestMsg.clearAllReceiver();
requestMsg.addReceiver(remoteAMS);
requestMsg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
requestMsg.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
requestMsg.setOntology(FIPAManagementOntology.NAME);
GetDescription action = new GetDescription();
List l = new ArrayList(1);
Action a = new Action();
a.setActor(remoteAMS);
a.setAction(action);
getContentManager().fillContent(requestMsg,a);
addBehaviour(new handleAddRemotePlatformBehaviour("GetDescription",requestMsg));
}catch(Exception e){
e.printStackTrace();
}
}
public void addRemotePlatformFromURL(String url){
try{
URL AP_URL = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(AP_URL.openStream()));
StringBuffer buf=new StringBuffer();
String inputLine;
while( (inputLine = in.readLine()) != null ) {
if( ! inputLine.equals("") ) {
buf.append(inputLine);
buf.append(" ");
}
}
//to parse the APDescription it is put in a Dummy ACLMessage
ACLMessage dummyMsg = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
dummyMsg.setOntology(FIPAManagementOntology.NAME);
dummyMsg.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
String content = "(( result (action ( agent-identifier :name ams :addresses (sequence IOR:00000000000000) :resolvers (sequence ) ) (get-description ) ) (set " + buf.toString() +" ) ) )";
dummyMsg.setContent(content);
try{
Result r = (Result)getContentManager().extractContent(dummyMsg);
Iterator i = r.getItems().iterator();
APDescription APDesc = null;
while( i.hasNext() && ((APDesc = (APDescription)i.next()) != null) ){
String amsName = "ams@" + APDesc.getName();
if(amsName.equalsIgnoreCase(getAMS().getName())){
logger.log(Logger.WARNING,"ERROR: Action not allowed.");
}
else
{
// create the proper AID for AMS by adding all available addresses
AID ams = new AID(amsName, AID.ISGUID);
for (Iterator is = APDesc.getAllAPServices(); is.hasNext(); ) {
APService s = (APService)is.next();
for (Iterator js = s.getAllAddresses(); js.hasNext(); )
ams.addAddresses(js.next().toString());
}
myGUI.addRemotePlatformFolder();
myGUI.addRemotePlatform(ams,APDesc);
}
}
}catch(Exception e){
e.printStackTrace();}
in.close();
}catch(java.net.MalformedURLException e){
e.printStackTrace();
}catch(java.io.IOException ioe){
ioe.printStackTrace();
}
}
public void viewAPDescription(String title){
myGUI.viewAPDescriptionDialog(myPlatformProfile,title);
}
public void viewAPDescription(APDescription remoteAP, String title){
myGUI.viewAPDescriptionDialog(remoteAP,title);
}
public void removeRemotePlatform(APDescription platform){
myGUI.removeRemotePlatform(platform.getName());
}
//make a search on a specified ams in order to return
//all the agents registered with that ams.
public void refreshRemoteAgent(APDescription platform,AID ams){
try{
// FIXME. Move all this block into the constructor for better performance
// because it is invariant to the method parameters
ACLMessage request; // variable that keeps the request search message
Action act; // variable that keeps the search action
request = new ACLMessage(ACLMessage.REQUEST);
request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
request.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
request.setOntology(FIPAManagementOntology.NAME);
AMSAgentDescription amsd = new AMSAgentDescription();
SearchConstraints constraints = new SearchConstraints();
constraints.setMaxResults(new Long(-1)); // all results back
// Build a AMS action object for the request
Search s = new Search();
s.setDescription(amsd);
s.setConstraints(constraints);
act = new Action();
act.setAction(s);
// request has been already initialized in the constructor
request.clearAllReceiver();
request.addReceiver(ams);
act.setActor(ams); // set the actor of this search action
getContentManager().fillContent(request, act);
addBehaviour(new handleRefreshRemoteAgentBehaviour ("search",request,platform));
}catch(Exception e){
e.printStackTrace();
}
}
// ask the local AMS to register a remote Agent.
public void registerRemoteAgentWithAMS(AMSAgentDescription amsd){
Register register_act = new Register();
register_act.setDescription(amsd);
try{
Action a = new Action();
a.setActor(getAMS());
a.setAction(register_act);
ACLMessage requestMsg = getRequest();
requestMsg.setOntology(FIPAManagementOntology.NAME);
getContentManager().fillContent(requestMsg, a);
addBehaviour(new AMSClientBehaviour("Register", requestMsg));
}catch(Exception e){e.printStackTrace();}
}
} |
package untref.aydoo.graficador;
public class FuncionConstante {
private float constante;
public FuncionConstante(float constante) {
this.constante = constante;
}
public float evaluarEn(float x) {
return constante;
}
} |
package cs201.structures.restaurant;
import java.util.List;
import cs201.agents.PersonAgent.Intention;
import cs201.roles.Role;
import cs201.roles.restaurantRoles.RestaurantCashierRole;
import cs201.roles.restaurantRoles.RestaurantCookRole;
import cs201.roles.restaurantRoles.RestaurantHostRole;
import cs201.roles.restaurantRoles.RestaurantWaiterRole;
import cs201.structures.Structure;
public abstract class Restaurant extends Structure {
RestaurantCashierRole cashier;
RestaurantCookRole cook;
RestaurantHostRole host;
List<RestaurantWaiterRole> waiters;
double moneyOnHand;
int bankAccountNumber;
boolean isOpen;
public Restaurant(int x, int y, int width, int height, int id) {
super(x, y, width, height, id);
// TODO Auto-generated constructor stub
}
@Override
public Role getRole(Intention role) {
// TODO Auto-generated method stub
return null;
}
/**
* Returns this Restaurant's Cashier if someone is currently acting as a Cashier, null otherwise
* @return This Restaurant's active Cashier
*/
public RestaurantCashierRole getCashier() {
return (cashier.getPerson() != null) ? cashier : null;
}
/**
* Returns this Restaurant's Cook if someone is currently acting as a Cook, null otherwise
* @return This Restaurant's active Cook
*/
public RestaurantCookRole getCook() {
return (cook.getPerson() != null) ? cook : null;
}
/**
* Returns this Restaurant's Host if someone is currently acting as a Host, null otherwise
* @return This Restaurant's active Host
*/
public RestaurantHostRole getHost() {
return (host.getPerson() != null) ? host : null;
}
/**
* Returns a list of this Restaurant's Waiters
* @return A list of Waiters
*/
public List<RestaurantWaiterRole> getWaiters() {
return waiters;
}
/**
* Adds money to the Restaurant's money on hand
* @param howMuch How much money to add
*/
public void addMoney(double howMuch) {
moneyOnHand += howMuch;
}
/**
* Removes money from the Restaurant's money on hand
* @param howMuch How much money to remove
*/
public void removeMoney(double howMuch) {
moneyOnHand -= howMuch;
}
/**
* Returns how much money this Restaurant currently has on hand (not including what's in the bank)
* @return The Restaurant's money on hand
*/
public double getCurrentRestaurantMoney() {
return moneyOnHand;
}
/**
* Sets this Restaurant's bank account number
* @param newNumber The new account number
*/
public void setBankAccountNumber(int newNumber) {
bankAccountNumber = newNumber;
}
/**
* Sets whether this Restaurant is open or closed
* @param open True to set this Restaurant to open, closed to close it down
*/
public void setOpen(boolean open) {
isOpen = open;
}
/**
* Returns whether or not this Restaurant is open
* @return True for an open Restaurant, false otherwise
*/
public boolean getOpen() {
return isOpen;
}
} |
package us.corenetwork.tradecraft;
import net.minecraft.server.v1_7_R2.*;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_7_R2.util.CraftMagicNumbers;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class CustomVillager extends EntityVillager {
private String career = "NOT_INITIALIZED";
private MerchantRecipeList trades;
private String lastTradingPlayer = null;
private boolean overrideName = false;
//Schedules after window closes
private boolean createNewTier = false;
private boolean restockAll = false;
public CustomVillager(World world) {
super(world);
init();
}
public CustomVillager(World world, int i) {
super(world, i);
init();
}
private void init()
{
trades = new MerchantRecipeList();
Bukkit.getScheduler().scheduleSyncDelayedTask(TradeCraftPlugin.instance, new Runnable()
{
@Override
public void run()
{
loadVillagerData();
loadTradesFromDB();
if (trades.size() == 0)
{
addTier(0);
}
}
});
}
@Override
public EntityAgeable createChild(EntityAgeable entityAgeable) {
return b(entityAgeable);
}
/**
* Returns list of offers
*/
@Override
public MerchantRecipeList getOffers(EntityHuman entityHuman) {
if (trades == null || trades.size() == 0)
{
Logs.severe("Villager " + uniqueID.toString() + " has no trades!");
CustomRecipe recipe = new CustomRecipe(new ItemStack((Block) Block.REGISTRY.a("bedrock"), 65), new ItemStack((Block) Block.REGISTRY.a("bedrock"), 1));
//recipe.lockManually();
MerchantRecipeList list = new MerchantRecipeList();
list.add(recipe);
return list;
}
return trades;
}
/**
* Activated when new player starts trading (or null when nobody is trading)
*/
@Override
public void a_(EntityHuman entityHuman)
{
if (entityHuman == null) //Nobody is trading now
{
if (createNewTier)
{
addTier(getLastTier() + 1);
refreshAll();
//Particle effects and increasing village population
Village village = (Village) ReflectionUtils.get(EntityVillager.class, this, "village");
if (village != null && lastTradingPlayer != null) {
Logs.debugIngame("Reputation UP!");
this.world.broadcastEntityEffect(this, (byte) 14);
village.a(lastTradingPlayer, 1);
}
//Particle effect when new tier is created
this.addEffect(new MobEffect(MobEffectList.REGENERATION.id, 200, 0));
}
else if (restockAll)
{
refreshAll();
//Particle effect when restocking
this.addEffect(new MobEffect(MobEffectList.REGENERATION.id, 200, 0));
}
restockAll = false;
createNewTier = false;
}
else
Logs.debugIngame("Trading with: " + career);
super.a_(entityHuman);
}
/**
* Called when somebody right clicks on villager
* @return has trade window been opened
*/
@Override
public boolean a(EntityHuman entityHuman)
{
overrideName = true;
boolean returningBool = super.a(entityHuman);
overrideName = false;
return returningBool;
}
@Override
public String getCustomName()
{
if (overrideName)
return career;
else
return super.getCustomName();
}
/**
* Activated when player makes a trade
*/
@Override
public void a(MerchantRecipe vanillaRecipe)
{
// Yes/No sound
this.makeSound("mob.villager.yes", this.be(), this.bf());
//Refrehs inventory
EntityHuman human = b();
if (human != null && human instanceof EntityPlayer)
{
final org.bukkit.entity.Player player = ((EntityPlayer) human).getBukkitEntity();
Bukkit.getScheduler().runTask(TradeCraftPlugin.instance, new Runnable()
{
@Override
public void run()
{
player.updateInventory();
}
});
((EntityPlayer) human).updateInventory(human.activeContainer);
lastTradingPlayer = human.getName();
}
CustomRecipe recipe = (CustomRecipe) vanillaRecipe;
if (trades == null)
return;
int tradeID = trades.indexOf(recipe);
if (tradeID < 0)
{
Logs.severe("Player completed unknown trade on villager " + uniqueID.toString() + "! ");
return;
}
incrementCounter(tradeID);
Logs.debugIngame("Trade completed! Left:" + recipe.getTradesLeft());
if (areAllTiersUnlocked())
{
if (random.nextDouble() < Settings.getDouble(Setting.ALL_UNLOCKED_REFRESH_CHANCE))
{
restockAll = true;
}
}
else
{
if (isLastTier(recipe) || random.nextInt(100) < 20) //Add new tier when on last trade or with 20% chance
{
createNewTier = true;
}
}
}
public void loadVillagerData()
{
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("SELECT * FROM villagers WHERE ID = ?");
statement.setString(1, uniqueID.toString());
ResultSet set = statement.executeQuery();
if (set.next())
{
career = set.getString("Career");
statement.close();
}
else
{
statement.close();
createVillagerData();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void createVillagerData()
{
career = VillagerConfig.getRandomCareer(getProfession());
if (career == null)
career = "NO_CAREER";
Logs.debugIngame("Decided career: " + career);
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("INSERT INTO villagers (ID, Career) VALUES (?,?)");
statement.setString(1, uniqueID.toString());
statement.setString(2, career);
statement.executeUpdate();
IO.getConnection().commit();
statement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void loadTradesFromDB()
{
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("SELECT * FROM offers WHERE Villager = ?");
statement.setString(1, uniqueID.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
ItemStack itemA;
ItemStack itemB = null;
ItemStack itemC;
//First item
int id = set.getInt("FirstItemID");
int data = set.getInt("FirstItemDamage");
int amount = set.getInt("FirstItemAmount");
itemA = new ItemStack(CraftMagicNumbers.getItem(id), amount, data);
Util.loadNBT(set.getBytes("FirstItemNBT"), itemA);
//Second item
id = set.getInt("SecondItemID");
if (id > 0)
{
data = set.getInt("SecondItemDamage");
amount = set.getInt("SecondItemAmount");
itemB = new ItemStack(CraftMagicNumbers.getItem(id), amount, data);
Util.loadNBT(set.getBytes("SecondItemNBT"), itemB);
}
//Result item
id = set.getInt("ThirdItemID");
data = set.getInt("ThirdItemDamage");
amount = set.getInt("ThirdItemAmount");
itemC = new ItemStack(CraftMagicNumbers.getItem(id), amount, data);
Util.loadNBT(set.getBytes("ThirdItemNBT"), itemC);
CustomRecipe recipe;
if (itemB == null)
recipe = new CustomRecipe(itemA, itemC);
else
recipe = new CustomRecipe(itemA, itemB, itemC);
recipe.setTier(set.getInt("Tier"));
recipe.setTradesLeft(set.getInt("TradesLeft"));
trades.add(recipe);
}
statement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void refreshAll()
{
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("UPDATE offers SET TradesLeft = ? WHERE Villager = ? AND ID = ?");
for (int i = 0; i < trades.size(); i++)
{
int tradesLeft = getDefaultNumberOfTrades();
CustomRecipe recipe = (CustomRecipe) trades.get(i);
recipe.setTradesLeft(tradesLeft);
statement.setInt(1, tradesLeft);
statement.setString(2, uniqueID.toString());
statement.setInt(2, i);
statement.addBatch();
}
statement.executeBatch();
statement.close();
IO.getConnection().commit();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void incrementCounter(int tradeID)
{
CustomRecipe recipe = (CustomRecipe) trades.get(tradeID);
recipe.setTradesLeft(recipe.getTradesLeft() - 1);
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("UPDATE offers SET TradesLeft = ? WHERE Villager = ? AND ID = ?");
statement.setString(1, uniqueID.toString());
statement.setInt(2, tradeID);
statement.executeUpdate();
statement.close();
IO.getConnection().commit();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void addTier(int tier)
{
List<CustomRecipe> recipes = VillagerConfig.getTrades(career, tier);
Logs.debugIngame("Adding trades: " + recipes.size());
try
{
PreparedStatement statement = IO.getConnection().prepareStatement("INSERT INTO offers (Villager, ID, FirstItemID, FirstItemDamage, FirstItemNBT, FirstItemAmount, SecondItemID, SecondItemDamage, SecondItemNBT, SecondItemAmount, ThirdItemID, ThirdItemDamage, ThirdItemNBT, ThirdItemAmount, Tier, TradesLeft) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
for (int i = 0; i < recipes.size(); i++)
{
int id = i + trades.size();
CustomRecipe recipe = recipes.get(i);
statement.setString(1, uniqueID.toString());
statement.setInt(2, id);
statement.setInt(3, CraftMagicNumbers.getId(recipe.getBuyItem1().getItem()));
statement.setInt(4, recipe.getBuyItem1().getData());
statement.setBytes(5, Util.getNBT(recipe.getBuyItem1()));
statement.setInt(6, recipe.getBuyItem1().count);
if (recipe.hasSecondItem())
{
statement.setInt(7, CraftMagicNumbers.getId(recipe.getBuyItem2().getItem()));
statement.setInt(8, recipe.getBuyItem2().getData());
statement.setBytes(9, Util.getNBT(recipe.getBuyItem2()));
statement.setInt(10, recipe.getBuyItem2().count);
}
else
{
statement.setInt(7, 0);
statement.setInt(8, 0);
statement.setBytes(9, new byte[0]);
statement.setInt(10, 0);
}
statement.setInt(11, CraftMagicNumbers.getId(recipe.getBuyItem3().getItem()));
statement.setInt(12, recipe.getBuyItem3().getData());
statement.setBytes(13, Util.getNBT(recipe.getBuyItem3()));
statement.setInt(14, recipe.getBuyItem3().count);
statement.setInt(15, tier);
int amountOfTrades = getDefaultNumberOfTrades();
statement.setInt(16, amountOfTrades);
statement.addBatch();
recipe.setTier(tier);
recipe.setTradesLeft(amountOfTrades);
trades.add(recipe);
}
statement.executeBatch();
statement.close();
IO.getConnection().commit();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private int getLastTier()
{
if (trades.size() == 0)
return 0;
else
return ((CustomRecipe) trades.get(trades.size() - 1)).getTier();
}
private boolean isLastTier(CustomRecipe recipe)
{
return getLastTier() == recipe.getTier();
}
private boolean areAllTiersUnlocked()
{
return !VillagerConfig.hasTrades(career, getLastTier() + 1);
}
private static int getDefaultNumberOfTrades()
{
return 2 + TradeCraftPlugin.random.nextInt(6) + TradeCraftPlugin.random.nextInt(6);
}
} |
package dae.prefabs.parameters;
import dae.components.ComponentType;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Koen Samyn
*/
public class EnumListParameter extends Parameter{
private Object[] choices;
private Class enumClass;
/**
* Creates a new EnumListParameter object.
* @param componentType componentType the component type of the parameter.
* @param type the type of the parameter
* @param id the id of the parameter.
*/
public EnumListParameter(ComponentType componentType, String type, String id){
super(componentType, type, id);
}
/**
* Sets the enum class of this enum list parameter.
* @param className the name of the enum class.
*/
public void setEnumClass(String className){
try {
enumClass = Class.forName(className);
choices = enumClass.getEnumConstants();
} catch (ClassNotFoundException ex) {
Logger.getLogger("DArtE").log(Level.SEVERE, null, ex);
}
}
/**
* Converts the string to the correct enum value.
* @param value
* @return
*/
public Object getEnum(String value){
return Enum.valueOf(enumClass, value);
}
/**
* Gets the list of choices from this EnumList parameter.
* @return the list of choices as an array.
*/
public Object[] getChoices() {
return choices;
}
} |
package de.duenndns.ssl;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.SparseArray;
import android.os.Build;
import android.os.Handler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.cert.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* A X509 trust manager implementation which asks the user about invalid
* certificates and memorizes their decision.
* <p>
* The certificate validity is checked using the system default X509
* TrustManager, creating a query Dialog if the check fails.
* <p>
* <b>WARNING:</b> This only works if a dedicated thread is used for
* opening sockets!
*/
public class MemorizingTrustManager implements X509TrustManager {
final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName());
final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
private final static int NOTIFICATION_ID = 100509;
static String KEYSTORE_DIR = "KeyStore";
static String KEYSTORE_FILE = "KeyStore.bks";
Context master;
Activity foregroundAct;
NotificationManager notificationManager;
private static int decisionId = 0;
private static SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
Handler masterHandler;
private File keyStoreFile;
private KeyStore appKeyStore;
private X509TrustManager defaultTrustManager;
private X509TrustManager appTrustManager;
/** Creates an instance of the MemorizingTrustManager class that falls back to a custom TrustManager.
*
* You need to supply the application context. This has to be one of:
* - Application
* - Activity
* - Service
*
* The context is used for file management, to display the dialog /
* notification and for obtaining translated strings.
*
* @param m Context for the application.
* @param defaultTrustManager Delegate trust management to this TM. If null, the user must accept every certificate.
*/
public MemorizingTrustManager(Context m, X509TrustManager defaultTrustManager) {
init(m);
this.appTrustManager = getTrustManager(appKeyStore);
this.defaultTrustManager = defaultTrustManager;
}
/** Creates an instance of the MemorizingTrustManager class using the system X509TrustManager.
*
* You need to supply the application context. This has to be one of:
* - Application
* - Activity
* - Service
*
* The context is used for file management, to display the dialog /
* notification and for obtaining translated strings.
*
* @param m Context for the application.
*/
public MemorizingTrustManager(Context m) {
init(m);
this.appTrustManager = getTrustManager(appKeyStore);
this.defaultTrustManager = getTrustManager(null);
}
void init(Context m) {
master = m;
masterHandler = new Handler(m.getMainLooper());
notificationManager = (NotificationManager)master.getSystemService(Context.NOTIFICATION_SERVICE);
Application app;
if (m instanceof Application) {
app = (Application)m;
} else if (m instanceof Service) {
app = ((Service)m).getApplication();
} else if (m instanceof Activity) {
app = ((Activity)m).getApplication();
} else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!");
File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);
appKeyStore = loadAppKeyStore();
}
/**
* Returns a X509TrustManager list containing a new instance of
* TrustManagerFactory.
*
* This function is meant for convenience only. You can use it
* as follows to integrate TrustManagerFactory for HTTPS sockets:
*
* <pre>
* SSLContext sc = SSLContext.getInstance("TLS");
* sc.init(null, MemorizingTrustManager.getInstanceList(this),
* new java.security.SecureRandom());
* HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
* </pre>
* @param c Activity or Service to show the Dialog / Notification
*/
public static X509TrustManager[] getInstanceList(Context c) {
return new X509TrustManager[] { new MemorizingTrustManager(c) };
}
/**
* Binds an Activity to the MTM for displaying the query dialog.
*
* This is useful if your connection is run from a service that is
* triggered by user interaction -- in such cases the activity is
* visible and the user tends to ignore the service notification.
*
* You should never have a hidden activity bound to MTM! Use this
* function in onResume() and @see unbindDisplayActivity in onPause().
*
* @param act Activity to be bound
*/
public void bindDisplayActivity(Activity act) {
foregroundAct = act;
}
/**
* Removes an Activity from the MTM display stack.
*
* Always call this function when the Activity added with
* {@link #bindDisplayActivity(Activity)} is hidden.
*
* @param act Activity to be unbound
*/
public void unbindDisplayActivity(Activity act) {
// do not remove if it was overridden by a different activity
if (foregroundAct == act)
foregroundAct = null;
}
/**
* Changes the path for the KeyStore file.
*
* The actual filename relative to the app's directory will be
* <code>app_<i>dirname</i>/<i>filename</i></code>.
*
* @param dirname directory to store the KeyStore.
* @param filename file name for the KeyStore.
*/
public static void setKeyStoreFile(String dirname, String filename) {
KEYSTORE_DIR = dirname;
KEYSTORE_FILE = filename;
}
/**
* Get a list of all certificate aliases stored in MTM.
*
* @return an {@link Enumeration} of all certificates
*/
public Enumeration<String> getCertificates() {
try {
return appKeyStore.aliases();
} catch (KeyStoreException e) {
// this should never happen, however...
throw new RuntimeException(e);
}
}
/**
* Get a certificate for a given alias.
*
* @param alias the certificate's alias as returned by {@link #getCertificates()}.
*
* @return the certificate associated with the alias or <tt>null</tt> if none found.
*/
public Certificate getCertificate(String alias) {
try {
return appKeyStore.getCertificate(alias);
} catch (KeyStoreException e) {
// this should never happen, however...
throw new RuntimeException(e);
}
}
/**
* Removes the given certificate from MTMs key store.
*
* <p>
* <b>WARNING</b>: this does not immediately invalidate the certificate. It is
* well possible that (a) data is transmitted over still existing connections or
* (b) new connections are created using TLS renegotiation, without a new cert
* check.
* </p>
* @param alias the certificate's alias as returned by {@link #getCertificates()}.
*
* @throws KeyStoreException if the certificate could not be deleted.
*/
public void deleteCertificate(String alias) throws KeyStoreException {
appKeyStore.deleteEntry(alias);
keyStoreUpdated();
}
public HostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier) {
if (defaultVerifier == null)
throw new IllegalArgumentException("The default verifier may not be null");
return new MemorizingHostnameVerifier(defaultVerifier);
}
X509TrustManager getTrustManager(KeyStore ks) {
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
for (TrustManager t : tmf.getTrustManagers()) {
if (t instanceof X509TrustManager) {
return (X509TrustManager)t;
}
}
} catch (Exception e) {
// Here, we are covering up errors. It might be more useful
// however to throw them out of the constructor so the
// embedding app knows something went wrong.
LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e);
}
return null;
}
KeyStore loadAppKeyStore() {
KeyStore ks;
try {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
LOGGER.log(Level.SEVERE, "getAppKeyStore()", e);
return null;
}
try {
ks.load(null, null);
} catch (NoSuchAlgorithmException | CertificateException | IOException e) {
LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e);
}
InputStream is = null;
try {
is = new java.io.FileInputStream(keyStoreFile);
ks.load(is, "MTM".toCharArray());
} catch (NoSuchAlgorithmException | CertificateException | IOException e) {
LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - exception loading file key store", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOGGER.log(Level.FINE, "getAppKeyStore(" + keyStoreFile + ") - exception closing file key store input stream", e);
}
}
}
return ks;
}
void storeCert(String alias, Certificate cert) {
try {
appKeyStore.setCertificateEntry(alias, cert);
} catch (KeyStoreException e) {
LOGGER.log(Level.SEVERE, "storeCert(" + cert + ")", e);
return;
}
keyStoreUpdated();
}
void storeCert(X509Certificate cert) {
storeCert(cert.getSubjectDN().toString(), cert);
}
void keyStoreUpdated() {
// reload appTrustManager
appTrustManager = getTrustManager(appKeyStore);
// store KeyStore to file
java.io.FileOutputStream fos = null;
try {
fos = new java.io.FileOutputStream(keyStoreFile);
appKeyStore.store(fos, "MTM".toCharArray());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
}
}
}
}
// if the certificate is stored in the app key store, it is considered "known"
private boolean isCertKnown(X509Certificate cert) {
try {
return appKeyStore.getCertificateAlias(cert) != null;
} catch (KeyStoreException e) {
return false;
}
}
private static boolean isExpiredException(Throwable e) {
do {
if (e instanceof CertificateExpiredException)
return true;
e = e.getCause();
} while (e != null);
return false;
}
private static boolean isPathException(Throwable e) {
do {
if (e instanceof CertPathValidatorException)
return true;
e = e.getCause();
} while (e != null);
return false;
}
public void checkCertTrusted(X509Certificate[] chain, String authType, boolean isServer)
throws CertificateException
{
LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
try {
LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager");
if (isServer)
appTrustManager.checkServerTrusted(chain, authType);
else
appTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ae) {
LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager did not verify certificate. Will fall back to secondary verification mechanisms (if any).", ae);
if (isCertKnown(chain[0])) {
LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore");
return;
}
try {
if (defaultTrustManager == null) {
LOGGER.fine("No defaultTrustManager set. Verification failed, throwing " + ae);
throw ae;
}
LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager");
if (isServer)
defaultTrustManager.checkServerTrusted(chain, authType);
else
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException e) {
LOGGER.log(Level.FINER, "checkCertTrusted: defaultTrustManager failed", e);
interactCert(chain, authType, e);
}
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
checkCertTrusted(chain, authType, false);
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
checkCertTrusted(chain, authType, true);
}
public X509Certificate[] getAcceptedIssuers()
{
LOGGER.log(Level.FINE, "getAcceptedIssuers()");
return defaultTrustManager.getAcceptedIssuers();
}
private static int createDecisionId(MTMDecision d) {
int myId;
synchronized(openDecisions) {
myId = decisionId;
openDecisions.put(myId, d);
decisionId += 1;
}
return myId;
}
private static String hexString(byte[] data) {
StringBuilder si = new StringBuilder();
for (int i = 0; i < data.length; i++) {
si.append(String.format("%02x", data[i]));
if (i < data.length - 1)
si.append(":");
}
return si.toString();
}
private static String certHash(final X509Certificate cert, String digest) {
try {
MessageDigest md = MessageDigest.getInstance(digest);
md.update(cert.getEncoded());
return hexString(md.digest());
} catch (java.security.cert.CertificateEncodingException e) {
return e.getMessage();
} catch (java.security.NoSuchAlgorithmException e) {
return e.getMessage();
}
}
private static void certDetails(StringBuilder si, X509Certificate c) {
SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
si.append("\n");
si.append(c.getSubjectDN().toString());
si.append("\n");
si.append(validityDateFormater.format(c.getNotBefore()));
si.append(" - ");
si.append(validityDateFormater.format(c.getNotAfter()));
si.append("\nSHA-256: ");
si.append(certHash(c, "SHA-256"));
si.append("\nSHA-1: ");
si.append(certHash(c, "SHA-1"));
si.append("\nSigned by: ");
si.append(c.getIssuerDN().toString());
si.append("\n");
}
private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
Throwable e = cause;
LOGGER.log(Level.FINE, "certChainMessage for " + e);
StringBuilder si = new StringBuilder();
if (isPathException(e))
si.append(master.getString(R.string.mtm_trust_anchor));
else if (isExpiredException(e))
si.append(master.getString(R.string.mtm_cert_expired));
else {
// get to the cause
while (e.getCause() != null)
e = e.getCause();
si.append(e.getLocalizedMessage());
}
si.append("\n\n");
si.append(master.getString(R.string.mtm_connect_anyway));
si.append("\n\n");
si.append(master.getString(R.string.mtm_cert_details));
for (X509Certificate c : chain) {
certDetails(si, c);
}
return si.toString();
}
private String hostNameMessage(X509Certificate cert, String hostname) {
StringBuilder si = new StringBuilder();
si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
si.append("\n\n");
try {
Collection<List<?>> sans = cert.getSubjectAlternativeNames();
if (sans == null) {
si.append(cert.getSubjectDN());
si.append("\n");
} else for (List<?> altName : sans) {
Object name = altName.get(1);
if (name instanceof String) {
si.append("[");
si.append(altName.get(0));
si.append("] ");
si.append(name);
si.append("\n");
}
}
} catch (CertificateParsingException e) {
e.printStackTrace();
si.append("<Parsing error: ");
si.append(e.getLocalizedMessage());
si.append(">\n");
}
si.append("\n");
si.append(master.getString(R.string.mtm_connect_anyway));
si.append("\n\n");
si.append(master.getString(R.string.mtm_cert_details));
certDetails(si, cert);
return si.toString();
}
/**
* Reflectively call
* <code>Notification.setLatestEventInfo(Context, CharSequence, CharSequence, PendingIntent)</code>
* since it was remove in Android API level 23.
*
* @param notification
* @param context
* @param mtmNotification
* @param certName
* @param call
*/
private static void setLatestEventInfoReflective(Notification notification,
Context context, CharSequence mtmNotification,
CharSequence certName, PendingIntent call) {
Method setLatestEventInfo;
try {
setLatestEventInfo = notification.getClass().getMethod(
"setLatestEventInfo", Context.class, CharSequence.class,
CharSequence.class, PendingIntent.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
try {
setLatestEventInfo.invoke(notification, context, mtmNotification,
certName, call);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
void startActivityNotification(Intent intent, int decisionId, String certName) {
Notification notification;
final PendingIntent call = PendingIntent.getActivity(master, 0, intent,
0);
final String mtmNotification = master.getString(R.string.mtm_notification);
final long currentMillis = System.currentTimeMillis();
final Context context = master.getApplicationContext();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
@SuppressWarnings("deprecation")
// Use an extra identifier for the legacy build notification, so
// that we suppress the deprecation warning. We will latter assign
// this to the correct identifier.
Notification n = new Notification(android.R.drawable.ic_lock_lock,
mtmNotification,
currentMillis);
setLatestEventInfoReflective(n, context, mtmNotification, certName, call);
n.flags |= Notification.FLAG_AUTO_CANCEL;
notification = n;
} else {
notification = new Notification.Builder(master)
.setContentTitle(mtmNotification)
.setContentText(certName)
.setTicker(certName)
.setSmallIcon(android.R.drawable.ic_lock_lock)
.setWhen(currentMillis)
.setContentIntent(call)
.setAutoCancel(true)
.getNotification();
}
notificationManager.notify(NOTIFICATION_ID + decisionId, notification);
}
/**
* Returns the top-most entry of the activity stack.
*
* @return the Context of the currently bound UI or the master context if none is bound
*/
Context getUI() {
return (foregroundAct != null) ? foregroundAct : master;
}
int interact(final String message, final int titleId) {
/* prepare the MTMDecision blocker object */
MTMDecision choice = new MTMDecision();
final int myId = createDecisionId(choice);
masterHandler.post(new Runnable() {
public void run() {
Intent ni = new Intent(master, MemorizingActivity.class);
ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
ni.putExtra(DECISION_INTENT_ID, myId);
ni.putExtra(DECISION_INTENT_CERT, message);
ni.putExtra(DECISION_TITLE_ID, titleId);
// we try to directly start the activity and fall back to
// making a notification. If no foreground activity is set
// (foregroundAct==null) or if the app developer set an
// invalid / expired activity, the catch-all fallback is
// deployed.
try {
foregroundAct.startActivity(ni);
} catch (Exception e) {
LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
startActivityNotification(ni, myId, message);
}
}
});
LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
try {
synchronized(choice) { choice.wait(); }
} catch (InterruptedException e) {
LOGGER.log(Level.FINER, "InterruptedException", e);
}
LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
return choice.state;
}
void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
throws CertificateException
{
switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
case MTMDecision.DECISION_ALWAYS:
storeCert(chain[0]); // only store the server cert, not the whole chain
case MTMDecision.DECISION_ONCE:
break;
default:
throw (cause);
}
}
boolean interactHostname(X509Certificate cert, String hostname)
{
switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
case MTMDecision.DECISION_ALWAYS:
storeCert(hostname, cert);
case MTMDecision.DECISION_ONCE:
return true;
default:
return false;
}
}
protected static void interactResult(int decisionId, int choice) {
MTMDecision d;
synchronized(openDecisions) {
d = openDecisions.get(decisionId);
openDecisions.remove(decisionId);
}
if (d == null) {
LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
return;
}
synchronized(d) {
d.state = choice;
d.notify();
}
}
class MemorizingHostnameVerifier implements HostnameVerifier {
private HostnameVerifier defaultVerifier;
public MemorizingHostnameVerifier(HostnameVerifier wrapped) {
defaultVerifier = wrapped;
}
@Override
public boolean verify(String hostname, SSLSession session) {
LOGGER.log(Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first");
// if the default verifier accepts the hostname, we are done
if (defaultVerifier.verify(hostname, session)) {
LOGGER.log(Level.FINE, "default verifier accepted " + hostname);
return true;
}
// otherwise, we check if the hostname is an alias for this cert in our keystore
try {
X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0];
//Log.d(TAG, "cert: " + cert);
if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) {
LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting.");
return true;
} else {
LOGGER.log(Level.FINE, "server " + hostname + " provided wrong certificate, asking user.");
return interactHostname(cert, hostname);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
} |
package jsettlers.mapcreator.main;
import go.graphics.area.Area;
import go.graphics.region.Region;
import go.graphics.swing.AreaContainer;
import go.graphics.swing.sound.SwingSoundPlayer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import jsettlers.common.buildings.EBuildingType;
import jsettlers.common.landscape.ELandscapeType;
import jsettlers.common.map.MapLoadException;
import jsettlers.common.map.object.MapDecorationObject;
import jsettlers.common.map.object.MapStoneObject;
import jsettlers.common.map.object.MapTreeObject;
import jsettlers.common.map.object.StackObject;
import jsettlers.common.mapobject.EMapObjectType;
import jsettlers.common.material.EMaterialType;
import jsettlers.common.movable.EMovableType;
import jsettlers.common.position.ISPosition2D;
import jsettlers.graphics.action.Action;
import jsettlers.graphics.action.ActionFireable;
import jsettlers.graphics.action.EActionType;
import jsettlers.graphics.action.SelectAction;
import jsettlers.graphics.map.IMapInterfaceListener;
import jsettlers.graphics.map.MapContent;
import jsettlers.graphics.map.MapInterfaceConnector;
import jsettlers.logic.map.save.MapDataSerializer;
import jsettlers.logic.map.save.MapFileHeader;
import jsettlers.logic.map.save.MapList;
import jsettlers.logic.map.save.MapLoader;
import jsettlers.mapcreator.data.MapData;
import jsettlers.mapcreator.data.MapDataDelta;
import jsettlers.mapcreator.localization.EditorLabels;
import jsettlers.mapcreator.main.DataTester.TestResultReceiver;
import jsettlers.mapcreator.main.action.AbortDrawingAction;
import jsettlers.mapcreator.main.action.CombiningActionFirerer;
import jsettlers.mapcreator.main.action.DrawLineAction;
import jsettlers.mapcreator.main.action.EndDrawingAction;
import jsettlers.mapcreator.main.action.StartDrawingAction;
import jsettlers.mapcreator.main.error.IScrollToAble;
import jsettlers.mapcreator.main.error.ShowErrorsButton;
import jsettlers.mapcreator.main.map.MapEditorControls;
import jsettlers.mapcreator.main.tools.PlaceStackToolbox;
import jsettlers.mapcreator.main.tools.ToolRenderer;
import jsettlers.mapcreator.main.tools.ToolTreeModel;
import jsettlers.mapcreator.mapview.MapGraphics;
import jsettlers.mapcreator.stat.StatisticsWindow;
import jsettlers.mapcreator.tools.SetStartpointTool;
import jsettlers.mapcreator.tools.Tool;
import jsettlers.mapcreator.tools.ToolBox;
import jsettlers.mapcreator.tools.ToolNode;
import jsettlers.mapcreator.tools.landscape.FixHeightsTool;
import jsettlers.mapcreator.tools.landscape.FlatLandscapeTool;
import jsettlers.mapcreator.tools.landscape.HeightAdder;
import jsettlers.mapcreator.tools.landscape.LandscapeHeightTool;
import jsettlers.mapcreator.tools.landscape.SetLandscapeTool;
import jsettlers.mapcreator.tools.objects.DeleteObjectTool;
import jsettlers.mapcreator.tools.objects.PlaceBuildingTool;
import jsettlers.mapcreator.tools.objects.PlaceMapObjectTool;
import jsettlers.mapcreator.tools.objects.PlaceMovableTool;
import jsettlers.mapcreator.tools.objects.PlaceTemplateTool;
import jsettlers.mapcreator.tools.objects.PlaceTemplateTool.TemplateBuilding;
import jsettlers.mapcreator.tools.objects.PlaceTemplateTool.TemplateMovable;
import jsettlers.mapcreator.tools.objects.PlaceTemplateTool.TemplateObject;
import jsettlers.mapcreator.tools.shapes.LineCircleShape;
import jsettlers.mapcreator.tools.shapes.ShapeType;
public class EditorWindow implements IMapInterfaceListener, ActionFireable, TestResultReceiver, IPlayerSetter, IScrollToAble {
private final class RadiusChangeListener implements ChangeListener {
private final LineCircleShape shape;
private RadiusChangeListener(LineCircleShape shape) {
this.shape = shape;
}
@Override
public void stateChanged(ChangeEvent arg0) {
shape.setRadius(((JSlider) arg0.getSource()).getModel().getValue());
}
}
private final class ShapeActionListener implements ActionListener {
private final ShapeType shape;
private ShapeActionListener(ShapeType shape) {
this.shape = shape;
}
@Override
public void actionPerformed(ActionEvent arg0) {
setShape(shape);
}
}
private LinkedList<ShapeType> lastUsed = new LinkedList<ShapeType>();
// @formatter:off
private final ToolNode TOOLBOX = new ToolBox("Werkzege", new ToolNode[] {
new ToolBox("Landschaft", new ToolNode[] { new SetLandscapeTool(ELandscapeType.GRASS, false),
new SetLandscapeTool(ELandscapeType.DRY_GRASS, false), new SetLandscapeTool(ELandscapeType.SAND, false),
new SetLandscapeTool(ELandscapeType.FLATTENED, false), new SetLandscapeTool(ELandscapeType.DESERT, false),
new SetLandscapeTool(ELandscapeType.EARTH, false), new SetLandscapeTool(ELandscapeType.WATER1, false),
new SetLandscapeTool(ELandscapeType.WATER2, false), new SetLandscapeTool(ELandscapeType.WATER3, false),
new SetLandscapeTool(ELandscapeType.WATER4, false), new SetLandscapeTool(ELandscapeType.WATER5, false),
new SetLandscapeTool(ELandscapeType.WATER6, false), new SetLandscapeTool(ELandscapeType.WATER7, false),
new SetLandscapeTool(ELandscapeType.WATER8, false), new SetLandscapeTool(ELandscapeType.RIVER1, true),
new SetLandscapeTool(ELandscapeType.RIVER2, true), new SetLandscapeTool(ELandscapeType.RIVER3, true),
new SetLandscapeTool(ELandscapeType.RIVER4, true), new SetLandscapeTool(ELandscapeType.MOUNTAIN, false),
new SetLandscapeTool(ELandscapeType.SNOW, false), new SetLandscapeTool(ELandscapeType.MOOR, false),
new SetLandscapeTool(ELandscapeType.FLATTENED_DESERT, false), new SetLandscapeTool(ELandscapeType.SHARP_FLATTENED_DESERT, false),
new SetLandscapeTool(ELandscapeType.GRAVEL, false), }),
new ToolBox("Höhen", new ToolNode[] { new LandscapeHeightTool(), new HeightAdder(true), new HeightAdder(false), new FlatLandscapeTool(),
new FixHeightsTool(), }),
new ToolBox("Objekte", new ToolNode[] { new PlaceMapObjectTool(MapTreeObject.getInstance()),
new PlaceMapObjectTool(MapStoneObject.getInstance(0)), new PlaceMapObjectTool(MapStoneObject.getInstance(1)),
new PlaceMapObjectTool(MapStoneObject.getInstance(2)), new PlaceMapObjectTool(MapStoneObject.getInstance(3)),
new PlaceMapObjectTool(MapStoneObject.getInstance(4)), new PlaceMapObjectTool(MapStoneObject.getInstance(5)),
new PlaceMapObjectTool(MapStoneObject.getInstance(6)), new PlaceMapObjectTool(MapStoneObject.getInstance(7)),
new PlaceMapObjectTool(MapStoneObject.getInstance(8)), new PlaceMapObjectTool(MapStoneObject.getInstance(9)),
new PlaceMapObjectTool(MapStoneObject.getInstance(10)),
new PlaceMapObjectTool(new MapDecorationObject(EMapObjectType.PLANT_DECORATION)),
new PlaceMapObjectTool(new MapDecorationObject(EMapObjectType.DESERT_DECORATION)), }),
new ToolBox("Siedler", new ToolNode[] {
new ToolBox("Arbeiter", new ToolNode[] { new PlaceMovableTool(EMovableType.BEARER, this),
new PlaceMovableTool(EMovableType.BRICKLAYER, this), new PlaceMovableTool(EMovableType.DIGGER, this),
new PlaceMovableTool(EMovableType.BAKER, this), new PlaceMovableTool(EMovableType.CHARCOAL_BURNER, this),
new PlaceMovableTool(EMovableType.FARMER, this), new PlaceMovableTool(EMovableType.FISHERMAN, this),
new PlaceMovableTool(EMovableType.FORESTER, this), new PlaceMovableTool(EMovableType.LUMBERJACK, this),
new PlaceMovableTool(EMovableType.MELTER, this), new PlaceMovableTool(EMovableType.MILLER, this),
new PlaceMovableTool(EMovableType.MINER, this), new PlaceMovableTool(EMovableType.PIG_FARMER, this),
new PlaceMovableTool(EMovableType.SAWMILLER, this), new PlaceMovableTool(EMovableType.SLAUGHTERER, this),
new PlaceMovableTool(EMovableType.SMITH, this), new PlaceMovableTool(EMovableType.STONECUTTER, this),
new PlaceMovableTool(EMovableType.WATERWORKER, this), }),
new ToolBox("Spezialisten", new ToolNode[] { new PlaceMovableTool(EMovableType.GEOLOGIST, this),
new PlaceMovableTool(EMovableType.PIONEER, this), new PlaceMovableTool(EMovableType.THIEF, this),
new PlaceMovableTool(EMovableType.DONKEY, this), }),
new ToolBox("Krieger", new ToolNode[] { new PlaceMovableTool(EMovableType.SWORDSMAN_L1, this),
new PlaceMovableTool(EMovableType.SWORDSMAN_L2, this), new PlaceMovableTool(EMovableType.SWORDSMAN_L3, this),
new PlaceMovableTool(EMovableType.BOWMAN_L1, this), new PlaceMovableTool(EMovableType.BOWMAN_L2, this),
new PlaceMovableTool(EMovableType.BOWMAN_L3, this), new PlaceMovableTool(EMovableType.PIKEMAN_L1, this),
new PlaceMovableTool(EMovableType.PIKEMAN_L2, this), new PlaceMovableTool(EMovableType.PIKEMAN_L3, this), }), }),
new ToolBox("Materialien", new ToolNode[] {
new ToolBox("Bauen", new ToolNode[] { new PlaceStackToolbox(EMaterialType.PLANK, 8),
new PlaceStackToolbox(EMaterialType.STONE, 8), new PlaceStackToolbox(EMaterialType.TRUNK, 8), }),
new ToolBox("Essen", new ToolNode[] { new PlaceStackToolbox(EMaterialType.BREAD, 8),
new PlaceStackToolbox(EMaterialType.CROP, 8), new PlaceStackToolbox(EMaterialType.FISH, 8),
new PlaceStackToolbox(EMaterialType.FLOUR, 8), new PlaceStackToolbox(EMaterialType.PIG, 8),
new PlaceStackToolbox(EMaterialType.WATER, 8), new PlaceStackToolbox(EMaterialType.WINE, 8), }),
new ToolBox("Rohstoffe", new ToolNode[] { new PlaceStackToolbox(EMaterialType.COAL, 8),
new PlaceStackToolbox(EMaterialType.IRON, 8), new PlaceStackToolbox(EMaterialType.IRONORE, 8),
new PlaceStackToolbox(EMaterialType.GOLD, 8), new PlaceStackToolbox(EMaterialType.GOLDORE, 8), }),
new ToolBox("Werkzeug", new ToolNode[] { new PlaceStackToolbox(EMaterialType.HAMMER, 8),
new PlaceStackToolbox(EMaterialType.BLADE, 8), new PlaceStackToolbox(EMaterialType.AXE, 8),
new PlaceStackToolbox(EMaterialType.SAW, 8), new PlaceStackToolbox(EMaterialType.PICK, 8),
new PlaceStackToolbox(EMaterialType.SCYTHE, 8), new PlaceStackToolbox(EMaterialType.FISHINGROD, 8), }),
new ToolBox("Waffen", new ToolNode[] { new PlaceStackToolbox(EMaterialType.SWORD, 8),
new PlaceStackToolbox(EMaterialType.BOW, 8), new PlaceStackToolbox(EMaterialType.SPEAR, 8), }), }),
new ToolBox("Gebäude", new ToolNode[] {
new ToolBox("Rohstoffe", new ToolNode[] { new PlaceBuildingTool(EBuildingType.LUMBERJACK, this),
new PlaceBuildingTool(EBuildingType.SAWMILL, this), new PlaceBuildingTool(EBuildingType.STONECUTTER, this),
new PlaceBuildingTool(EBuildingType.FORESTER, this), new PlaceBuildingTool(EBuildingType.IRONMELT, this),
new PlaceBuildingTool(EBuildingType.IRONMINE, this), new PlaceBuildingTool(EBuildingType.GOLDMELT, this),
new PlaceBuildingTool(EBuildingType.GOLDMINE, this), new PlaceBuildingTool(EBuildingType.COALMINE, this),
new PlaceBuildingTool(EBuildingType.CHARCOAL_BURNER, this), new PlaceBuildingTool(EBuildingType.TOOLSMITH, this), }),
new ToolBox("Essen", new ToolNode[] { new PlaceBuildingTool(EBuildingType.FARM, this),
new PlaceBuildingTool(EBuildingType.MILL, this), new PlaceBuildingTool(EBuildingType.BAKER, this),
new PlaceBuildingTool(EBuildingType.WATERWORKS, this), new PlaceBuildingTool(EBuildingType.PIG_FARM, this),
new PlaceBuildingTool(EBuildingType.SLAUGHTERHOUSE, this), new PlaceBuildingTool(EBuildingType.FISHER, this),
new PlaceBuildingTool(EBuildingType.DONKEY_FARM, this), new PlaceBuildingTool(EBuildingType.WINEGROWER, this), }),
new ToolBox("Militär", new ToolNode[] { new PlaceBuildingTool(EBuildingType.TOWER, this),
new PlaceBuildingTool(EBuildingType.BIG_TOWER, this), new PlaceBuildingTool(EBuildingType.CASTLE, this),
new PlaceBuildingTool(EBuildingType.WEAPONSMITH, this), new PlaceBuildingTool(EBuildingType.DOCKYARD, this), }),
new ToolBox("Sozial", new ToolNode[] { new PlaceBuildingTool(EBuildingType.SMALL_LIVINGHOUSE, this),
new PlaceBuildingTool(EBuildingType.MEDIUM_LIVINGHOUSE, this),
new PlaceBuildingTool(EBuildingType.BIG_LIVINGHOUSE, this), new PlaceBuildingTool(EBuildingType.TEMPLE, this),
new PlaceBuildingTool(EBuildingType.BIG_TEMPLE, this), new PlaceBuildingTool(EBuildingType.STOCK, this), }), }),
new ToolBox("Vorlagen", new ToolNode[] {
new PlaceTemplateTool("Start", new TemplateObject[] {
new TemplateBuilding(0, 0, EBuildingType.TOWER),
// goods
new TemplateObject(-4, 7, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(-4, 10, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(-1, 7, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(-1, 10, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(-1, 13, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(2, 7, new StackObject(EMaterialType.STONE, 8)),
new TemplateObject(2, 10, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(2, 13, new StackObject(EMaterialType.PLANK, 8)),
new TemplateObject(5, 7, new StackObject(EMaterialType.STONE, 8)),
new TemplateObject(5, 10, new StackObject(EMaterialType.STONE, 8)),
new TemplateObject(5, 13, new StackObject(EMaterialType.STONE, 8)),
new TemplateObject(8, 7, new StackObject(EMaterialType.FISH, 8)),
new TemplateObject(8, 10, new StackObject(EMaterialType.COAL, 8)),
new TemplateObject(8, 13, new StackObject(EMaterialType.STONE, 8)),
new TemplateObject(11, 7, new StackObject(EMaterialType.BREAD, 8)),
new TemplateObject(11, 10, new StackObject(EMaterialType.IRONORE, 8)),
new TemplateObject(11, 13, new StackObject(EMaterialType.BLADE, 6)),
new TemplateObject(14, 7, new StackObject(EMaterialType.MEAT, 8)),
new TemplateObject(14, 10, new StackObject(EMaterialType.FISHINGROD, 2)),
new TemplateObject(14, 13, new StackObject(EMaterialType.HAMMER, 8)),
new TemplateObject(17, 7, new StackObject(EMaterialType.SCYTHE, 2)),
// new TemplateObject(17, 10, new StackObject(EMaterialType., 2)),
new TemplateObject(17, 13, new StackObject(EMaterialType.AXE, 4)),
new TemplateObject(20, 10, new StackObject(EMaterialType.PICK, 6)),
new TemplateObject(20, 13, new StackObject(EMaterialType.SAW, 2)),
// worker
new TemplateMovable(8, 16, EMovableType.BRICKLAYER),
new TemplateMovable(9, 18, EMovableType.BRICKLAYER),
new TemplateMovable(10, 16, EMovableType.BRICKLAYER),
new TemplateMovable(11, 18, EMovableType.BRICKLAYER),
new TemplateMovable(12, 16, EMovableType.BRICKLAYER),
new TemplateMovable(14, 16, EMovableType.DIGGER),
new TemplateMovable(15, 18, EMovableType.DIGGER),
new TemplateMovable(16, 16, EMovableType.DIGGER),
new TemplateMovable(18, 17, EMovableType.SMITH),
new TemplateMovable(20, 16, EMovableType.MELTER),
// soldiers
new TemplateMovable(-11, -12, EMovableType.SWORDSMAN_L1), new TemplateMovable(-11, -14, EMovableType.SWORDSMAN_L1),
new TemplateMovable(-11, -16, EMovableType.SWORDSMAN_L1),
new TemplateMovable(-9, -10, EMovableType.SWORDSMAN_L1), new TemplateMovable(-9, -12, EMovableType.SWORDSMAN_L1),
new TemplateMovable(-9, -14, EMovableType.SWORDSMAN_L1), new TemplateMovable(-9, -16, EMovableType.BOWMAN_L1),
new TemplateMovable(-7, -10, EMovableType.PIKEMAN_L1), new TemplateMovable(-7, -12, EMovableType.PIKEMAN_L1),
new TemplateMovable(-7, -14, EMovableType.BOWMAN_L1),
new TemplateMovable(-7, -16, EMovableType.BOWMAN_L1),
new TemplateMovable(-5, -10, EMovableType.PIKEMAN_L1),
new TemplateMovable(-5, -12, EMovableType.BOWMAN_L1),
new TemplateMovable(-5, -14, EMovableType.BOWMAN_L1),
// bearer
new TemplateMovable(-2, -12, EMovableType.BEARER), new TemplateMovable(-2, -14, EMovableType.BEARER),
new TemplateMovable(-2, -16, EMovableType.BEARER),
new TemplateMovable(0, -10, EMovableType.BEARER), new TemplateMovable(0, -12, EMovableType.BEARER),
new TemplateMovable(0, -14, EMovableType.BEARER), new TemplateMovable(0, -16, EMovableType.BEARER),
new TemplateMovable(2, -10, EMovableType.BEARER), new TemplateMovable(2, -12, EMovableType.BEARER),
new TemplateMovable(2, -14, EMovableType.BEARER), new TemplateMovable(2, -16, EMovableType.BEARER),
new TemplateMovable(4, -10, EMovableType.BEARER), new TemplateMovable(4, -12, EMovableType.BEARER),
new TemplateMovable(4, -14, EMovableType.BEARER), }, this),
new PlaceTemplateTool("Holzarbeiter", new TemplateObject[] { new TemplateBuilding(0, 10, EBuildingType.LUMBERJACK),
new TemplateBuilding(0, 0, EBuildingType.FORESTER), new TemplateBuilding(3, -9, EBuildingType.LUMBERJACK),
new TemplateMovable(8, -8, EMovableType.LUMBERJACK), new TemplateMovable(7, 3, EMovableType.FORESTER),
new TemplateMovable(7, 12, EMovableType.LUMBERJACK),
}, this), }), new SetStartpointTool(this), new DeleteObjectTool(), });
// @formatter:on
private final MapData data;
private final MapGraphics map;
private Tool tool = null;
private ShapeType activeShape = null;
private JPanel shapeButtons;
private JPanel shapeSettings;
private byte currentPlayer = 0;
private ISPosition2D testFailPoint = null;
private JButton undoButton;
private LinkedList<MapDataDelta> undoDeltas = new LinkedList<MapDataDelta>();
private LinkedList<MapDataDelta> redoDeltas = new LinkedList<MapDataDelta>();
private final DataTester dataTester;
private MapInterfaceConnector connector;
private JLabel testResult;
private JButton startGameButton;
private final MapFileHeader header;
private JButton saveButton;
private JButton redoButton;
private ShowErrorsButton showErrorsButton;
public EditorWindow(MapFileHeader header, ELandscapeType ground) {
this.header = header;
short width = header.getWidth();
short height = header.getHeight();
short playerCount = header.getMaxPlayer();
data = new MapData(width, height, playerCount, ground);
map = new MapGraphics(data);
dataTester = new DataTester(data, this);
startMapEditing();
}
public EditorWindow(MapLoader loader) throws MapLoadException {
data = new MapData(loader.getMapData());
header = loader.getFileHeader();
map = new MapGraphics(data);
dataTester = new DataTester(data, this);
startMapEditing();
dataTester.start();
}
public void startMapEditing() {
JFrame window = new JFrame("map editor");
JPanel root = new JPanel();
root.setLayout(new BorderLayout(10, 10));
// map
Area area = new Area();
final Region region = new Region(Region.POSITION_CENTER);
area.add(region);
AreaContainer panel = new AreaContainer(area);
panel.setPreferredSize(new Dimension(640, 480));
panel.requestFocusInWindow();
panel.setFocusable(true);
root.add(panel, BorderLayout.CENTER);
// menu
JPanel menu = createMenu();
menu.setPreferredSize(new Dimension(300, 800));
root.add(menu, BorderLayout.EAST);
// toolbar
JToolBar toolbar = createToolbar();
root.add(toolbar, BorderLayout.NORTH);
// window
window.add(root);
window.pack();
window.setSize(1200, 800);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setLocationRelativeTo(null);
MapContent content = new MapContent(map, new SwingSoundPlayer(), new MapEditorControls(new CombiningActionFirerer(this)));
connector = content.getInterfaceConnector();
region.setContent(content);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
region.requestRedraw();
}
}, 50, 50);
connector.addListener(this);
}
private JToolBar createToolbar() {
JToolBar bar = new JToolBar();
saveButton = new JButton(EditorLabels.getLabel("save"));
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
save();
}
});
saveButton.setEnabled(false);
bar.add(saveButton);
undoButton = new JButton(EditorLabels.getLabel("undo"));
undoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
undo();
}
});
undoButton.setEnabled(false);
bar.add(undoButton);
redoButton = new JButton(EditorLabels.getLabel("redo"));
redoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
redo();
}
});
redoButton.setEnabled(false);
bar.add(redoButton);
showErrorsButton = new ShowErrorsButton(dataTester.getErrorList(), this);
bar.add(showErrorsButton);
testResult = new JLabel();
testResult.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (testFailPoint != null) {
connector.scrollTo(testFailPoint, true);
}
}
});
bar.add(testResult);
bar.add(Box.createGlue());
bar.add(new JLabel("current player:"));
final SpinnerNumberModel model = new SpinnerNumberModel(0, 0, data.getPlayerCount() - 1, 1);
JSpinner playerSpinner = new JSpinner(model);
playerSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
currentPlayer = model.getNumber().byteValue();
}
});
playerSpinner.setPreferredSize(new Dimension(50, 1));
playerSpinner.setMaximumSize(new Dimension(50, 40));
bar.add(playerSpinner);
JButton statistics = new JButton("Statistics");
statistics.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new StatisticsWindow(data);
}
});
bar.add(statistics);
startGameButton = new JButton("Play");
startGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
play();
}
});
bar.add(startGameButton);
return bar;
}
protected void save() {
try {
MapList.getDefaultList().saveMap(header, data);
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(saveButton, e.getMessage());
}
}
protected void play() {
try {
File temp = File.createTempFile("tmp_map", "");
MapDataSerializer.serialize(data, new FileOutputStream(temp));
String[] args = new String[] { "java", "-classpath", System.getProperty("java.class.path"), "jsettlers.mapcreator.main.PlayProcess",
temp.getAbsolutePath(), };
System.out.println("Starting process:");
for (String arg : args) {
System.out.print(arg + " ");
}
System.out.println();
ProcessBuilder builder = new ProcessBuilder(args);
builder.directory(new File("").getAbsoluteFile());
builder.redirectErrorStream(true);
final Process process = builder.start();
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
break;
}
if (line == null) {
break;
}
System.out.println(line);
}
}
}, "run game process");
} catch (IOException e) {
e.printStackTrace();
}
}
protected void undo() {
if (!undoDeltas.isEmpty()) {
MapDataDelta delta = undoDeltas.pollLast();
MapDataDelta inverse = data.apply(delta);
redoDeltas.addLast(inverse);
redoButton.setEnabled(true);
}
if (undoDeltas.isEmpty()) {
undoButton.setEnabled(false);
saveButton.setEnabled(false);
}
}
protected void redo() {
if (!redoDeltas.isEmpty()) {
MapDataDelta delta = redoDeltas.pollLast();
MapDataDelta inverse = data.apply(delta);
undoDeltas.addLast(inverse);
undoButton.setEnabled(true);
saveButton.setEnabled(true);
}
if (redoDeltas.isEmpty()) {
redoButton.setEnabled(false);
}
}
/**
* Ends a use step of a tool: creates a diff to the last step.
*/
private void endUseStep() {
MapDataDelta delta = data.getUndoDelta();
data.resetUndoDelta();
undoDeltas.add(delta);
redoDeltas.clear();
undoButton.setEnabled(true);
redoButton.setEnabled(false);
saveButton.setEnabled(true);
}
private JPanel createMenu() {
JPanel menu = new JPanel();
menu.setLayout(new BorderLayout());
final JTree toolshelf = new JTree(new ToolTreeModel(TOOLBOX));
menu.add(new JScrollPane(toolshelf), BorderLayout.CENTER);
toolshelf.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent arg0) {
TreePath path = arg0.getNewLeadSelectionPath();
if (path == null) {
changeTool(null);
return;
}
Object lastPathComponent = path.getLastPathComponent();
if (lastPathComponent instanceof ToolBox) {
ToolBox toolBox = (ToolBox) lastPathComponent;
TreePath newPath = path.pathByAddingChild(toolBox.getTools()[0]);
toolshelf.setSelectionPath(newPath);
} else if (lastPathComponent instanceof Tool) {
Tool newTool = (Tool) lastPathComponent;
changeTool(newTool);
}
}
});
toolshelf.setCellRenderer(new ToolRenderer());
toolshelf.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
JPanel shape = new JPanel();
shape.setLayout(new BoxLayout(shape, BoxLayout.Y_AXIS));
shape.setBorder(BorderFactory.createTitledBorder("Formen"));
shapeButtons = new JPanel();
shape.add(shapeButtons);
shapeSettings = new JPanel();
shape.add(shapeSettings);
menu.add(shape, BorderLayout.SOUTH);
return menu;
}
protected void changeTool(Tool lastPathComponent) {
tool = lastPathComponent;
updateShapeButtons();
if (tool != null) {
ShapeType shape = tool.getShapes()[0];
List<ShapeType> shapes = Arrays.asList(tool.getShapes());
for (ShapeType used : lastUsed) {
if (shapes.contains(used)) {
shape = used;
break;
}
}
lastUsed.remove(shape);
lastUsed.addFirst(shape);
setShape(shape);
} else {
setShape(null);
}
}
private void updateShapeButtons() {
shapeButtons.removeAll();
if (tool != null) {
ButtonGroup shapeGroup = new ButtonGroup();
for (ShapeType shape : tool.getShapes()) {
JToggleButton button = new JToggleButton(shape.getName());
button.setSelected(shape == activeShape);
button.addActionListener(new ShapeActionListener(shape));
shapeGroup.add(button);
shapeButtons.add(button);
}
shapeButtons.setLayout(new BoxLayout(shapeButtons, BoxLayout.LINE_AXIS));
}
shapeButtons.revalidate();
}
protected void setShape(ShapeType shape) {
activeShape = shape;
// updateShapeButtons();
shapeSettings.removeAll();
if (shape instanceof LineCircleShape) {
final LineCircleShape shape2 = (LineCircleShape) shape;
JSlider radiusSelector = new JSlider(1, 50, shape2.getRadius());
radiusSelector.addChangeListener(new RadiusChangeListener(shape2));
shapeSettings.add(radiusSelector);
}
shapeSettings.revalidate();
}
@Override
public void action(Action action) {
System.out.println("Got action: " + action.getActionType());
if (action.getActionType() == EActionType.SELECT_AREA) {
// IMapArea area = ((SelectAreaAction) action).getArea();
} else if (action instanceof DrawLineAction) {
if (tool != null) {
DrawLineAction lineAction = (DrawLineAction) action;
ShapeType shape = getActiveShape();
tool.apply(data, shape, lineAction.getStart(), lineAction.getEnd(), lineAction.getUidy());
dataTester.retest();
}
} else if (action instanceof StartDrawingAction) {
if (tool != null) {
StartDrawingAction lineAction = (StartDrawingAction) action;
ShapeType shape = getActiveShape();
tool.start(data, shape, lineAction.getPos());
dataTester.retest();
}
} else if (action instanceof EndDrawingAction) {
endUseStep();
dataTester.retest();
} else if (action instanceof AbortDrawingAction) {
MapDataDelta delta = data.getUndoDelta();
data.apply(delta);
data.resetUndoDelta();
dataTester.retest();
} else if (action instanceof SelectAction) {
if (tool != null) {
SelectAction lineAction = (SelectAction) action;
ShapeType shape = getActiveShape();
tool.start(data, shape, lineAction.getPosition());
tool.apply(data, shape, lineAction.getPosition(), lineAction.getPosition(), 0);
endUseStep();
dataTester.retest();
}
}
}
private ShapeType getActiveShape() {
return activeShape;
}
@Override
public void fireAction(Action action) {
action(action);
}
@Override
public void testResult(String result, boolean allowed, ISPosition2D failPoint) {
testFailPoint = failPoint;
startGameButton.setEnabled(allowed);
testResult.setText(result);
showErrorsButton.setEnabled(!allowed);
}
@Override
public byte getActivePlayer() {
return currentPlayer;
}
@Override
public void scrollTo(ISPosition2D pos) {
if (pos != null) {
connector.scrollTo(pos, true);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.