Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • DM/dm-docs
  • hammonds/dm-docs
  • hparraga/dm-docs
3 results
Show changes
Showing
with 1780 additions and 0 deletions
File added
File added
File added
Main-Class: gov.anl.dm.esafsync.Gui
Class-Path: ../lib/ojdbc7.jar ../lib/javax.json-api-1.0.jar ../lib/jdatepicker-1.3.4.jar
dm.daq.connection = DAQ_CONNECTION
dm.daq.datadir = DATA_DIR
dm.daqReciver.connection = DAQ_REC_CONNECTION
dm.daqReceiver.datadir = DATA_REC_DIR
dm.storageServ.connection = https://xstor-devel.xray.aps.anl.gov:22236/dm
execute() {
#echo "Executing: $@"
eval "$@"
}
cd ExperimentSynchronizer
execute lib/jdk1.7.0_51/bin/java -jar target/ExperimentSynchronizer.jar resources/config.properties
package gov.anl.dm.esafsync;
import gov.anl.dm.esafsync.serviceconn.DaqServiceConnection;
import gov.anl.dm.esafsync.serviceconn.ServiceConnection;
import gov.anl.dm.esafsync.serviceconn.StorageServiceConnection;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;
class ExperimentList extends JFrame
{
private static final long serialVersionUID = 1L;
public class DateLabelFormatter extends AbstractFormatter {
private static final long serialVersionUID = 1L;
private String datePattern = "MM-dd-yyyy";
private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
@Override
public Object stringToValue(String text) throws ParseException {
return dateFormatter.parseObject(text);
}
@Override
public String valueToString(Object value) throws ParseException {
if (value != null) {
Calendar cal = (Calendar) value;
return dateFormatter.format(cal.getTime());
}
return "";
}
public String valueToString(Date value) throws ParseException {
if (value != null) {
Date cal = (Date) value;
return dateFormatter.format(cal.getTime());
}
return "";
}
}
enum Column {
NAME("Experiment name"),
DESCRIPTION("Description"),
START_DATE("Start Date"),
END_DATE("End Date"),
MANAGER("Manager(s)"),
PI("Principal Investigator(s)"),
USER("Users");
private final String column;
private Column(String column) {
this.column = column;
}
@Override
public String toString() {
return column;
}
}
enum Role {
MANAGER("Manager"),
PI("PI"),
USER("User");
private final String role;
private Role(String role) {
this.role = role;
}
@Override
public String toString() {
return role;
}
}
class ExperimentTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
String dataValues [][];
@Override
public int getRowCount() {
return dataValues.length;
}
@Override
public int getColumnCount() {
return Column.values().length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return dataValues[rowIndex][columnIndex];
}
public String getColumnName(int col) {
return Column.values()[col].toString();
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
void setTable(String list) {
List<String[]> expTable = new ArrayList<>();
String [] rows = list.split("EXP");
for (int i=0; i<rows.length; i++) {
String [] cells = rows[i].split(",");
boolean goodRow = false;
int j = 0;
for (j = 0; j < cells[0].length(); j++) {
if ( Character.isDigit(cells[0].charAt(j)) ) {
goodRow = true;
break;
}
}
if (!goodRow) {
continue;
} else {
// parse experiment data
String[] experiment = new String[getColumnCount()+1];
experiment[Column.NAME.ordinal()] = cells[0].substring(j);
experiment[Column.DESCRIPTION.ordinal()] = cells[1].replace("$",",");
experiment[Column.START_DATE.ordinal()] = cells[3];
experiment[Column.END_DATE.ordinal()] = cells[4];
experiment[Column.MANAGER.ordinal()] = parseUsers(cells[5]);
experiment[Column.PI.ordinal()] = parseUsers(cells[6]);
int lastIndex = cells[7].indexOf("\"");
experiment[Column.USER.ordinal()] = parseUsers(cells[7].substring(0, lastIndex));
expTable.add(experiment);
}
}
dataValues = new String [expTable.size()][getColumnCount()];
for (int i=0; i < expTable.size(); i++) {
for (int j=0; j < getColumnCount(); j++) {
dataValues[i][j] = expTable.get(i)[j];
}
}
}
private String parseUsers(String userList) {
if (userList.equals("00000")) {
return "";
}
String parsedUsers = "";
String [] users = userList.split(":");
for (int i=0; i < users.length; i++) {
parsedUsers = parsedUsers + "d" + users[i] + " ";
}
return parsedUsers;
}
}
public static final String EXPERIMENT_PREFIX = "esaf";
StorageServiceConnection sconnection;
private JTable table = null;
private ExperimentTableModel tableModel = null;
private JScrollPane scrollPane;
ExperimentList(final String sector, final OracleConnection oconnection, final StorageServiceConnection sconnection, final DaqServiceConnection dconnection, final DaqServiceConnection drconnection) {
this.sconnection = sconnection;
setTitle("Experiment Import");
setSize(1000, 500);
setBackground(Color.gray);
final JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
JPanel entryPanel = new JPanel(new FlowLayout());
topPanel.add(entryPanel, BorderLayout.NORTH);
final JLabel entryLabel = new JLabel("Enter date range of experiment start date");
entryPanel.add(entryLabel);
UtilDateModel startModel = new UtilDateModel();
Properties p = new Properties();
p.put("text.today", "Today");
p.put("text.month", "Month");
p.put("text.year", "Year");
JDatePanelImpl startDatePanel = new JDatePanelImpl(startModel, p);
final JDatePickerImpl startDatePicker = new JDatePickerImpl(startDatePanel, new DateLabelFormatter());
entryPanel.add(startDatePicker);
UtilDateModel endModel = new UtilDateModel();
JDatePanelImpl endDatePanel = new JDatePanelImpl(endModel, p);
final JDatePickerImpl endDatePicker = new JDatePickerImpl(endDatePanel, new DateLabelFormatter());
entryPanel.add(endDatePicker);
final JButton submitDatesBtn = new JButton("click to get experiments list");
entryPanel.add(submitDatesBtn);
JPanel selectPanel = new JPanel(new FlowLayout());
topPanel.add(selectPanel, BorderLayout.SOUTH);
final JButton importExperimentBtn = new JButton("import selected experiments");
selectPanel.add(importExperimentBtn);
importExperimentBtn.setVisible(false);
final JButton importAndStartExperimentBtn = new JButton("import and start selected experiments");
selectPanel.add(importAndStartExperimentBtn);
importAndStartExperimentBtn.setVisible(false);
final JButton startExperimentBtn = new JButton("start selected experiments");
selectPanel.add(startExperimentBtn);
startExperimentBtn.setVisible(false);
final JButton stopExperimentBtn = new JButton("stop selected experiments");
selectPanel.add(stopExperimentBtn);
stopExperimentBtn.setVisible(false);
submitDatesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
entryLabel.setVisible(true);
submitDatesBtn.setVisible(true);
importExperimentBtn.setVisible(true);
importAndStartExperimentBtn.setVisible(true);
stopExperimentBtn.setVisible(true);
startExperimentBtn.setVisible(true);
DateLabelFormatter df = new DateLabelFormatter();
final Date startSelectedDate = (Date) startDatePicker.getModel().getValue();
String start;
String end;
try {
start = df.valueToString(startSelectedDate);
Date endSelectedDate = (Date) endDatePicker.getModel().getValue();
end = df.valueToString(endSelectedDate);
} catch (ParseException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
return;
}
String list;
try {
list = oconnection.getExperiments(sector, start, end);
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
return;
}
if (table == null) {
tableModel = new ExperimentTableModel();
tableModel.setTable(list);
table = new JTable(tableModel);
scrollPane = new JScrollPane( table );
topPanel.add( scrollPane, BorderLayout.CENTER );
table.setRowSelectionAllowed( true );
pack();
setVisible(true);
table.setVisible(true);
} else {
tableModel.setTable(list);
tableModel.fireTableStructureChanged();
}
}
});
importExperimentBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++) {
String experimentName = EXPERIMENT_PREFIX+(String)table.getModel().getValueAt(selection[i], Column.NAME.ordinal());
String description = (String)table.getModel().getValueAt(selection[i], Column.DESCRIPTION.ordinal());
String startDate = (String)table.getModel().getValueAt(selection[i], Column.START_DATE.ordinal());
String endDate = (String)table.getModel().getValueAt(selection[i], Column.END_DATE.ordinal());
if (sconnection.addExperiment(experimentName, description, startDate, endDate) != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
continue;
}
addRole((String)table.getModel().getValueAt(selection[i], Column.MANAGER.ordinal()), experimentName, Role.MANAGER);
addRole((String)table.getModel().getValueAt(selection[i], Column.PI.ordinal()), experimentName, Role.PI);
addRole((String)table.getModel().getValueAt(selection[i], Column.USER.ordinal()), experimentName, Role.USER);
if (sconnection.startExperiment(experimentName) != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
JOptionPane.showMessageDialog(null,"The experiment "+ experimentName +" did not start",
"Info",JOptionPane.WARNING_MESSAGE);
}
}
table.clearSelection();
}
});
importAndStartExperimentBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int[] selection = table.getSelectedRows();
if (selection.length > 0) {
if (dconnection.isSessionValid() && ((drconnection == null) || drconnection.isSessionValid())) {
importAndStartExperiments(selection, dconnection, drconnection);
} else {
JOptionPane.showMessageDialog(null,"Session expired. Restart the tools.",
"Info",JOptionPane.WARNING_MESSAGE);
}
}
}
});
startExperimentBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int[] selection = table.getSelectedRows();
if (selection.length > 0) {
if (dconnection.isSessionValid() && ((drconnection == null) || drconnection.isSessionValid())) {
startExperiments(selection, dconnection, drconnection);
} else {
JOptionPane.showMessageDialog(null,"Session expired. Restart the tools.",
"Info",JOptionPane.WARNING_MESSAGE);
}
}
}
});
stopExperimentBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int[] selection = table.getSelectedRows();
if (selection.length > 0) {
if (dconnection.isSessionValid() && ((drconnection == null) || drconnection.isSessionValid())) {
stopExperiments(selection, dconnection, drconnection);
} else {
JOptionPane.showMessageDialog(null,"Session expired. Restart the tools.",
"Info",JOptionPane.WARNING_MESSAGE);
}
}
}
});
}
private void importAndStartExperiments(int[] selection, DaqServiceConnection dconnection, DaqServiceConnection drconnection) {
for (int i = 0; i < selection.length; i++) {
String experimentName = EXPERIMENT_PREFIX+(String)table.getModel().getValueAt(selection[i], Column.NAME.ordinal());
String description = (String)table.getModel().getValueAt(selection[i], Column.DESCRIPTION.ordinal());
String startDate = (String)table.getModel().getValueAt(selection[i], Column.START_DATE.ordinal());
String endDate = (String)table.getModel().getValueAt(selection[i], Column.END_DATE.ordinal());
if (sconnection.addExperiment(experimentName, description, startDate, endDate) != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
continue;
}
addRole((String)table.getModel().getValueAt(selection[i], Column.MANAGER.ordinal()), experimentName, Role.MANAGER);
addRole((String)table.getModel().getValueAt(selection[i], Column.PI.ordinal()), experimentName, Role.PI);
addRole((String)table.getModel().getValueAt(selection[i], Column.USER.ordinal()), experimentName, Role.USER);
if (sconnection.startExperiment(experimentName) == ServiceConnection.ServiceConnectionStatus.SUCCESS) {
// convert date
String startDateDir;
try {
startDateDir = convertDate2Dir(startDate);
} catch (ParseException e) {
startDateDir = startDate;
}
if (drconnection != null) {
drconnection.startDaq(experimentName, startDateDir);
}
dconnection.startDaq(experimentName, startDateDir);
} else {
JOptionPane.showMessageDialog(null,"The experiment "+ experimentName +" did not start",
"Info",JOptionPane.WARNING_MESSAGE);
}
}
table.clearSelection();
}
private void startExperiments(int[] selection, DaqServiceConnection dconnection, DaqServiceConnection drconnection) {
for (int i = 0; i < selection.length; i++) {
String startDate = (String)table.getModel().getValueAt(selection[i], Column.START_DATE.ordinal());
// convert date
String startDateDir;
try {
startDateDir = convertDate2Dir(startDate);
} catch (ParseException e) {
startDateDir = startDate;
}
String experimentName = EXPERIMENT_PREFIX+(String)table.getModel().getValueAt(selection[i], Column.NAME.ordinal());
if (drconnection != null) {
drconnection.startDaq(experimentName, startDateDir);
}
dconnection.startDaq(experimentName, startDateDir);
}
table.clearSelection();
}
private void stopExperiments(int[] selection, DaqServiceConnection dconnection, DaqServiceConnection drconnection) {
for (int i = 0; i < selection.length; i++) {
String experimentName = EXPERIMENT_PREFIX+(String)table.getModel().getValueAt(selection[i], Column.NAME.ordinal());
dconnection.stopDaq(experimentName);
if (drconnection != null) {
drconnection.stopDaq(experimentName);
}
}
table.clearSelection();
}
private void addRole(String userList, String experimentName, Role role) {
if ((userList == null) || userList.isEmpty()) {
return;
}
String [] users = userList.split(" ");
for (int i = 0; i < users.length; i++) {
sconnection.addExperimentUser(users[i], experimentName, role.toString());
}
}
private String convertDate2Dir(String startDate) throws ParseException {
String month = startDate.substring(3,6);
String numMonth = null;
if (month.equals("JAN")) {
numMonth = "01";
} else if (month.equals("FEB")) {
numMonth = "02";
} else if (month.equals("MAR")) {
numMonth = "03";
} else if (month.equals("APR")) {
numMonth = "04";
} else if (month.equals("MAY")) {
numMonth = "05";
} else if (month.equals("JUN")) {
numMonth = "06";
} else if (month.equals("JUL")) {
numMonth = "07";
} else if (month.equals("AUG")) {
numMonth = "08";
} else if (month.equals("SEP")) {
numMonth = "09";
} else if (month.equals("OCT")) {
numMonth = "10";
} else if (month.equals("NOV")) {
numMonth = "11";
} else if (month.equals("DEC")) {
numMonth = "12";
}
return "20" + startDate.substring(7, 9) + "-" + numMonth;
}
}
package gov.anl.dm.esafsync;
import gov.anl.dm.esafsync.serviceconn.DaqServiceConnection;
import gov.anl.dm.esafsync.serviceconn.ServiceConnection;
import gov.anl.dm.esafsync.serviceconn.StorageServiceConnection;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
class Gui
{
public static void main(String arg[]) throws ParseException
{
String configFile = arg[0];
final Properties configProperties = new Properties();
setConfig(configFile, configProperties);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Gui(configProperties);
}
});
}
private Gui(Properties configProperties) {
// System.setProperty("javax.net.ssl.trustStore", configProperties.getProperty("dm.truststore"));
final OracleConnection oconnection = new OracleConnection();
try {
oconnection.connect(configProperties);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
System.exit(0);
}
final StorageServiceConnection sconnection = new StorageServiceConnection();
if (sconnection.init(configProperties.getProperty("dm.storageServ.connection")) != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
System.exit(0);
}
String daqurl = configProperties.getProperty("dm.daq.connection");
String dataDir = configProperties.getProperty("dm.daq.datadir");
DaqServiceConnection dconnection = new DaqServiceConnection(daqurl, dataDir);
if (dconnection.init() != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
System.exit(0);
}
DaqServiceConnection drconnection = null;
try {
String daqReceiverurl = configProperties.getProperty("dm.daqReciver.connection");
String dataReceiverDir = configProperties.getProperty("dm.daqReceiver.datadir");
if ((daqReceiverurl != null) && (dataReceiverDir != null)) {
drconnection = new DaqServiceConnection(daqReceiverurl, dataReceiverDir);
if (drconnection.init() != ServiceConnection.ServiceConnectionStatus.SUCCESS) {
System.exit(0);
}
}
} catch (Exception e) {
// possible null exception if property not defined
}
try
{
LoginWindow frame = new LoginWindow(sconnection, oconnection, dconnection, drconnection);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (sconnection != null) {
sconnection.close();
}
if (oconnection != null) {
oconnection.close();
}
System.exit(0);
}
});
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
private static void setConfig(String config, Properties configProperties) {
InputStream configInputStream = null;
try {
configInputStream = new FileInputStream(config);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(0);
}
if (configInputStream != null) {
try {
configProperties.load(configInputStream);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
System.exit(0);
}
} else {
System.exit(-1);
}
}
}
package gov.anl.dm.esafsync;
import gov.anl.dm.esafsync.serviceconn.DaqServiceConnection;
import gov.anl.dm.esafsync.serviceconn.ServiceConnection;
import gov.anl.dm.esafsync.serviceconn.StorageServiceConnection;
import javax.swing.*;
import java.awt.event.*;
public final class LoginWindow extends JFrame {
private static final long serialVersionUID = 1L;
StorageServiceConnection sconnection;
OracleConnection oconnection;
JPanel panel;
LoginWindow(final StorageServiceConnection sconnection, final OracleConnection oconnection, final DaqServiceConnection dconnection, final DaqServiceConnection drconnection) {
this.sconnection = sconnection;
this.oconnection = oconnection;
setTitle("Experiment Import Login");
JPanel panel = new JPanel();
add(panel);
panel.setLayout(null);
JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
final JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 40, 80, 25);
panel.add(passwordLabel);
final JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 40, 160, 25);
panel.add(passwordText);
JLabel sectorLabel = new JLabel("Sector");
sectorLabel.setBounds(10, 70, 80, 25);
panel.add(sectorLabel);
final JTextField sectorText = new JTextField(20);
sectorText.setBounds(100, 70, 160, 25);
panel.add(sectorText);
JButton submitButton = new JButton("submit");
submitButton.setBounds(10, 120, 80, 25);
panel.add(submitButton);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// String user = userText.getText().trim();
// String pass = new String(passwordText.getPassword());
String user = "dm";
String pass = "dbUser";
if ((user == null) || (user.isEmpty()) || (pass == null) || (pass.isEmpty())) {
JOptionPane.showMessageDialog(null,"enter login and password",
"Error",JOptionPane.ERROR_MESSAGE);
} else {
// sconnection.setLogin(user, pass);
// dconnection.setLogin(user, pass);
int aaResult = sconnection.login(user, pass);
if (dconnection.login(user, pass) != aaResult) {
JOptionPane.showMessageDialog(null,"inconsistent login response",
"Error",JOptionPane.ERROR_MESSAGE);
return;
}
if ((drconnection != null) && (drconnection.login(user, pass) != aaResult)) {
JOptionPane.showMessageDialog(null,"inconsistent login response",
"Error",JOptionPane.ERROR_MESSAGE);
return;
}
switch (aaResult) {
case ServiceConnection.ServiceConnectionStatus.SUCCESS:
setVisible(false);
ExperimentList page=new ExperimentList(sectorText.getText().trim(), oconnection, sconnection, dconnection, drconnection);
page.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
page.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
sconnection.close();
oconnection.close();
System.exit(0);
}
});
page.setVisible(true);
break;
case ServiceConnection.ServiceConnectionStatus.AUTHORIZATION_ERROR:
userText.setText("");
passwordText.setText("");
JOptionPane.showMessageDialog(null,"not authorized user",
"Error",JOptionPane.ERROR_MESSAGE);
break;
case ServiceConnection.ServiceConnectionStatus.AUTHENTICATION_ERROR:
userText.setText("");
passwordText.setText("");
JOptionPane.showMessageDialog(null,"Incorrect login or password",
"Error",JOptionPane.ERROR_MESSAGE);
break;
default:
// error message generated from exception
}
}
}
});
}
}
package gov.anl.dm.esafsync;
import java.sql.CallableStatement;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Properties;
public class OracleConnection {
Connection connection = null;
Statement statement;
void connect(Properties config) throws SQLException {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
connection = DriverManager.getConnection(
"jdbc:oracle:thin:@ra.aps.anl.gov:1527:aps1",
"glob_conn",
"ur2ytkownicy2u");
}
String getExperiments(String sector, String lower, String upper) throws SQLException {
CallableStatement callableStatement =
connection.prepareCall("{? = call safety.esaf_exp0001.get_exps(?,?,?,?)}");
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.setObject(2, "");
callableStatement.setString(3, sector);
callableStatement.setString(4, lower);
callableStatement.setString(5, upper);
callableStatement.execute();
return callableStatement.getString(1);
}
void close() {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
// nothing to do here
}
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class DaqServiceConnection extends ServiceConnection{
class Keyword {
static final String DAQ_EXPERIMENT_NAME = "experimentName";
static final String DAQ_DATA_DIRECTORY = "dataDirectory";
}
class StorageServUrl {
static final String START_DAQ = "/experiments/startDaq";
static final String STOP_DAQ = "/experiments/stopDaq";
}
private String url;
private String dataDir;
public DaqServiceConnection(String url, String dataDir) {
this.url = url;
this.dataDir = dataDir;
}
public final int init() {
return super.init(url);
}
public void startDaq(String experimentName, String startDateDir) {
String directory;
String dateDirectory;
if (dataDir.endsWith("/")) {
dateDirectory = dataDir + startDateDir;
directory = dataDir + startDateDir + "/" + experimentName;
} else {
dateDirectory = dataDir + "/" + startDateDir;
directory = dataDir + "/" + startDateDir + "/" + experimentName;
}
Map<String, String> data = new HashMap<>();
data.put(Keyword.DAQ_EXPERIMENT_NAME, encode(experimentName));
data.put(Keyword.DAQ_DATA_DIRECTORY, encode(directory));
invokeSessionPostRequest(StorageServUrl.START_DAQ, data);
}
public void stopDaq(String experimentName) {
Map<String, String> data = new HashMap<>();
data.put(Keyword.DAQ_EXPERIMENT_NAME, encode(experimentName));
invokeSessionPostRequest(StorageServUrl.STOP_DAQ, data);
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* Dummy trust manager class.
*
* A trivial implementation of <code>X509TrustManager</code> that doesn't
* actually check the validity of a certificate. This allows us to make SSL
* connections to internal servers without requiring the installation and
* maintenance of certificates in the client keystore.
*
* @see NoServerVerificationSSLSocketFactory
*/
public class NoOpTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] cert, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] cert, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
/**
* SSL socket factory that does not verify server credentials.
*
* A minor extension of <code>SSLSocketFactory</code> that installs a dummy
* trust manager. This allows creation of SSL sockets that don't verify the
* server certificates.
*
* @see NoOpTrustManager
*/
public class NoServerVerificationSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;
/**
* Default constructor.
*/
public NoServerVerificationSSLSocketFactory() {
try {
TrustManager tm = new NoOpTrustManager();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, // No KeyManager required
new TrustManager[]{tm},
new java.security.SecureRandom());
factory = (SSLSocketFactory) sslcontext.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
/**
* Get default (no server verification) socket factory.
*
* @return socket factory
*/
public static SocketFactory getDefault() {
return new NoServerVerificationSSLSocketFactory();
}
/**
* Create SSL socket layered over an existing socket connected to the named
* host, at a given port.
*
* @param socket existing socket
* @param host
* @param port
* @param autoClose
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException {
return factory.createSocket(socket, host, port, autoClose);
}
/**
* Create a socket and connect it to the specified remote address/port, and
* bind it to the specified local address/port.
*
* @param address server network address
* @param port server port
* @param localAddress client network address
* @param localPort client port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(address, port, localAddress, localPort);
}
/**
* Create a socket and connect it to the specified remote address/port.
*
* @param address server network address
* @param port server port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(InetAddress address, int port) throws IOException {
return factory.createSocket(address, port);
}
/**
* Create a socket and connect it to the specified remote host/port, and
* bind it to the specified local address/port.
*
* @param host server host
* @param port server port
* @param localAddress client network address
* @param localPort client port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(host, port, localAddress, localPort);
}
/**
* Create a socket and connect it to the specified remote host/port, and
* bind it to the specified local address/port.
*
* @param host server host
* @param port server port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(String host, int port) throws IOException {
return factory.createSocket(host, port);
}
/**
* Get default cipher suites from socket factory.
*
* @return list of default ciphers
*/
@Override
public String[] getDefaultCipherSuites() {
return factory.getSupportedCipherSuites();
}
/**
* Get supported cipher suites from socket factory.
*
* @return list of supported ciphers
*/
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
// import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JOptionPane;
public class ServiceConnection {
class DmHttpHeaders {
static final String DM_SET_COOKIE_HEADER = "Set-Cookie";
final static String DM_SESSION_ROLE_HTTP_HEADER = "Dm-Session-Role";
final static String DM_STATUS_CODE_HTTP_HEADER = "Dm-Status-Code";
final static String DM_STATUS_MESSAGE_HTTP_HEADER = "Dm-Status-Message";
final static String DM_EXCEPTION_TYPE_HTTP_HEADER = "Dm-Exception-Type";
}
class DmHttpStatus {
static final int DM_HTTP_OK = 200;
static final int DM_HTTP_UNAUTHORIZED = 401;
static final int DM_HTTP_INTERNAL_ERROR = 500;
}
class StorageServUrl {
static final String LOGIN_REQUEST = "/login";
}
class DmStatus {
static final int DM_OK = 0;
static final int DM_ERROR = 1;
static final int DM_INTERNAL_ERROR = 2;
static final int DM_COMMUNICATION_ERROR = 3;
static final int DM_CONFIGURATION_ERROR = 4;
static final int DM_AUTHORIZATION_ERROR = 5;
static final int DM_AUTHENTICATION_ERROR = 6;
static final int DM_DB_ERROR = 7;
static final int DM_URL_ERROR = 8;
static final int DM_TIMEOUT = 9;
static final int DM_INVALID_ARGUMENT = 10;
static final int DM_INVALID_REQUEST = 11;
static final int DM_INVALID_SESSION = 12;
static final int DM_COMMAND_FAILED =13;
static final int DM_OBJECT_NOT_FOUND = 14;
static final int DM_OBJECT_ALREADY_EXISTS = 15;
static final int DM_INVALID_OBJECT_STATE = 16;
}
class Keyword {
static final String USERNAME = "username";
static final String PASSWORD = "password";
}
public class ServiceConnectionStatus {
public static final int SUCCESS = 0;
public static final int AUTHENTICATION_ERROR = -2;
public static final int AUTHORIZATION_ERROR = -3;
public static final int INVALID_OPERATION = -4;
public static final int CONNECTION_ERROR = -5;
public static final int PROTOCOL_ERROR = -6;
public static final int ERROR = -1;
}
private final class Login {
private String username;
private String password;
private Login(String username, String password) {
this.username = username;
this.password = password;
}
private void clear() {
this.username = null;
this.password = null;
}
private int login() {
int result = ServiceConnection.this.login(username, password);
clear();
return result;
}
}
static final String ESAF_EXPERIMENT_TYPE = "1";
protected URL serviceUrl;
private Session session = new Session();
private Login login;
private boolean initialized = false;
public final int init(String serviceUrl) {
if (serviceUrl == null) {
JOptionPane.showMessageDialog(null,"service url is not specified.", "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnectionStatus.ERROR;
}
try {
this.serviceUrl = new URL(serviceUrl);
} catch (MalformedURLException ex) {
JOptionPane.showMessageDialog(null,"Malformed service url: " + serviceUrl, "Error",JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.ERROR;
}
String protocol = this.serviceUrl.getProtocol();
if (protocol == null) {
JOptionPane.showMessageDialog(null,"Unsupported service protocol specified in " + serviceUrl, "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnectionStatus.ERROR;
}
HttpsURLConnection.setDefaultSSLSocketFactory(new NoServerVerificationSSLSocketFactory());
initialized = true;
return ServiceConnectionStatus.SUCCESS;
}
public boolean isInitialized() {
return initialized;
}
public boolean isSessionValid() {
return session.isValid();
}
private URL getServiceUrl() {
return serviceUrl;
}
private int checkHttpResponse(HttpsURLConnection connection) {
int code = 0;
String exceptionType = connection.getHeaderField(DmHttpHeaders.DM_EXCEPTION_TYPE_HTTP_HEADER);
if (exceptionType != null) {
String statusMessage = connection.getHeaderField(DmHttpHeaders.DM_STATUS_MESSAGE_HTTP_HEADER);
String statusCode = connection.getHeaderField(DmHttpHeaders.DM_STATUS_CODE_HTTP_HEADER);
code = Integer.parseInt(statusCode);
JOptionPane.showMessageDialog(null,exceptionType +" "+ code +" "+ statusMessage, "Error",JOptionPane.ERROR_MESSAGE);
}
switch (code) {
case DmStatus.DM_OK :
return ServiceConnectionStatus.SUCCESS;
case DmStatus.DM_AUTHENTICATION_ERROR:
return ServiceConnectionStatus.AUTHENTICATION_ERROR;
case DmStatus.DM_AUTHORIZATION_ERROR:
return ServiceConnectionStatus.AUTHORIZATION_ERROR;
case DmStatus.DM_COMMUNICATION_ERROR:
case DmStatus.DM_CONFIGURATION_ERROR:
case DmStatus.DM_ERROR:
case DmStatus.DM_INVALID_SESSION:
case DmStatus.DM_TIMEOUT:
case DmStatus.DM_URL_ERROR:
return ServiceConnectionStatus.ERROR;
default:
return ServiceConnectionStatus.INVALID_OPERATION;
}
}
private String getFullRequestUrl(String requestUrl) {
String url = serviceUrl + requestUrl;
return url;
}
private static String preparePostData(Map<String, String> data) {
try {
String postData = "";
String separator = "";
for (String key : data.keySet()) {
postData += separator + key + "=" + URLEncoder.encode(data.get(key), "UTF8");
separator = "&";
}
return postData;
} catch (UnsupportedEncodingException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
return null;
}
}
private void updateSessionCookie(HttpsURLConnection connection) {
String cookie = connection.getHeaderField(DmHttpHeaders.DM_SET_COOKIE_HEADER);
if (cookie != null) {
session.setCookie(cookie);
}
String sessionRole = connection.getHeaderField(DmHttpHeaders.DM_SESSION_ROLE_HTTP_HEADER);
if (sessionRole != null) {
session.setRole(Session.Role.fromString(sessionRole));
}
}
private static int sendPostData(Map<String, String> data, HttpsURLConnection connection) {
String postData = preparePostData(data);
try (DataOutputStream dos = new DataOutputStream(connection.getOutputStream())) {
dos.writeBytes(postData);
dos.flush();
return ServiceConnectionStatus.SUCCESS;
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
JOptionPane.showMessageDialog(null, "misconfigured service or closed ", "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnectionStatus.CONNECTION_ERROR;
}
}
private static String readHttpResponse(HttpsURLConnection connection) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
sb.append('\n');
}
return sb.toString();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
return null;
}
}
private static void setCookieRequestHeader(HttpsURLConnection connection, String sessionCookie) {
if (sessionCookie != null) {
connection.setRequestProperty("Cookie", sessionCookie);
}
}
private static int setPostRequestHeaders(HttpsURLConnection connection, String sessionCookie) {
int resp = setPostRequestHeaders(connection);
if (resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
setCookieRequestHeader(connection, sessionCookie);
return resp;
}
private static int setPostRequestHeaders(HttpsURLConnection connection) {
try {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return ServiceConnectionStatus.SUCCESS;
} catch (ProtocolException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.PROTOCOL_ERROR;
}
}
protected int invokeSessionPostRequest(String requestUrl, Map<String, String> data) {
String urlString = getFullRequestUrl(requestUrl);
HttpsURLConnection connection = null;
try {
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
int resp = setPostRequestHeaders(connection, sessionCookie);
if ( resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
resp = sendPostData(data, connection);
if ( resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
updateSessionCookie(connection);
resp = checkHttpResponse(connection);
readHttpResponse(connection);
return resp;
} catch (Exception ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.ERROR;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static int setPutRequestHeaders(HttpsURLConnection connection, String sessionCookie) {
int resp = setPutRequestHeaders(connection);
if ( resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
setCookieRequestHeader(connection, sessionCookie);
return resp;
}
private static int setPutRequestHeaders(HttpsURLConnection connection) {
try {
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return ServiceConnectionStatus.SUCCESS;
} catch (ProtocolException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.PROTOCOL_ERROR;
}
}
protected int invokeSessionPutRequest(String requestUrl, Map<String, String> data) {
String urlString = getFullRequestUrl(requestUrl);
HttpsURLConnection connection = null;
try {
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
int resp = setPutRequestHeaders(connection, sessionCookie);
if ( resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
resp = sendPostData(data, connection);
if ( resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
updateSessionCookie(connection);
resp = checkHttpResponse(connection);
readHttpResponse(connection);
return resp;
} catch (Exception ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.ERROR;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
// // this method works with java 8 java.util.Base64
// protected String encode(String s) {
// byte[] encoded1 = Base64.getEncoder().encode(s.getBytes());
// String encoded2 = Base64.getEncoder().encodeToString(encoded1);
// return encoded2;
// }
public static String encode(String input) {
try {
// Input is twice encoded in order to avoid issues like
// '+' being interpreted as space
if (input == null) {
return input;
}
String s1 = DatatypeConverter.printBase64Binary(input.getBytes());
String s2 = DatatypeConverter.printBase64Binary(s1.getBytes());
return s2;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// public static String decode(String input) {
// try {
// // Input is twice encoded in order to avoid issues like
// // '+' being interpreted as space
// byte[] ba1 = DatatypeConverter.parseBase64Binary(input);
// byte[] ba2 = DatatypeConverter.parseBase64Binary(new String(ba1));
// return new String(ba2);
// } catch (Exception ex) {
// ex.printStackTrace();
// return null;
// }
// }
// private String verifySessionCookie() {
// return session.verifyCookie();
// }
//
// private static String getResponseHeaders(HttpsURLConnection connection) {
// String headerString = "";
// Map<String, List<String>> headerMap = connection.getHeaderFields();
// for (String key : headerMap.keySet()) {
// List<String> values = headerMap.get(key);
// headerString += key + ": " + values + "\n";
// }
// return headerString;
// }
//
// private String invokeSessionGetRequest(String requestUrl) {
// String urlString = getFullRequestUrl(requestUrl);
// HttpsURLConnection connection = null;
// try {
// String sessionCookie = session.verifyCookie();
// URL url = new URL(urlString);
// connection = (HttpsURLConnection) url.openConnection();
//
// setGetRequestHeaders(connection, sessionCookie);
// updateSessionCookie(connection);
// checkHttpResponse(connection);
// return readHttpResponse(connection);
// } catch (Exception ex) {
// String errorMsg = "Cannot connect to " + getServiceUrl();
// JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
// JOptionPane.showMessageDialog(null, ex.getMessage());
// return null;
// } finally {
// if (connection != null) {
// connection.disconnect();
// }
// }
// }
//
// private String invokeGetRequest(String requestUrl) {
// String urlString = getFullRequestUrl(requestUrl);
// HttpsURLConnection connection = null;
// try {
// URL url = new URL(urlString);
// connection = (HttpsURLConnection) url.openConnection();
// updateSessionCookie(connection);
// checkHttpResponse(connection);
// return readHttpResponse(connection);
// } catch (Exception ex) {
// String errorMsg = "Cannot connect to " + getServiceUrl();
// JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
// JOptionPane.showMessageDialog(null, ex.getMessage());
// return null;
// } finally {
// if (connection != null) {
// connection.disconnect();
// }
// }
// }
//
// private String invokeSessionDeleteRequest(String requestUrl) {
// String urlString = getFullRequestUrl(requestUrl);
// HttpsURLConnection connection = null;
// try {
// String sessionCookie = session.verifyCookie();
// URL url = new URL(urlString);
// connection = (HttpsURLConnection) url.openConnection();
//
// setDeleteRequestHeaders(connection, sessionCookie);
// updateSessionCookie(connection);
// checkHttpResponse(connection);
// return readHttpResponse(connection);
// } catch (Exception ex) {
// String errorMsg = "Cannot connect to " + getServiceUrl();
// JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
// JOptionPane.showMessageDialog(null, ex.getMessage());
// return null;
// } finally {
// if (connection != null) {
// connection.disconnect();
// }
// }
// }
//
// private static void setGetRequestHeaders(HttpsURLConnection connection, String sessionCookie) {
// setGetRequestHeaders(connection);
// setCookieRequestHeader(connection, sessionCookie);
// }
//
// private static void setGetRequestHeaders(HttpsURLConnection connection) {
// try {
// connection.setRequestMethod("GET");
// } catch (ProtocolException ex) {
// JOptionPane.showMessageDialog(null, ex.getMessage());
// }
// }
//
// private static void setDeleteRequestHeaders(HttpsURLConnection connection, String sessionCookie) {
// setDeleteRequestHeaders(connection);
// setCookieRequestHeader(connection, sessionCookie);
// }
//
// private static void setDeleteRequestHeaders(HttpsURLConnection connection) {
// try {
// connection.setRequestMethod("DELETE");
// } catch (ProtocolException ex) {
// JOptionPane.showMessageDialog(null, ex.getMessage());
// }
// }
//
//
// private void getData(HttpsURLConnection connection) {
// BufferedReader in;
// try {
// in = new BufferedReader(
// new InputStreamReader(connection.getInputStream()));
// String inputLine;
// StringBuffer response = new StringBuffer();
//
// while ((inputLine = in.readLine()) != null) {
// response.append(inputLine);
// }
// } catch (IOException e) {
// JOptionPane.showMessageDialog(null, e.getMessage());
// }
// }
public final void setLogin(String username, String password) {
this.login = new Login(username, password);
}
public final int login() {
return login.login();
}
public final int login(String username, String password) {
HttpsURLConnection connection = null;
try {
String urlString = getFullRequestUrl(StorageServUrl.LOGIN_REQUEST);
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
setPostRequestHeaders(connection);
HashMap<String, String> loginData = new HashMap<>();
loginData.put(Keyword.USERNAME, username);
loginData.put(Keyword.PASSWORD, password);
int resp = sendPostData(loginData, connection);
if (resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
resp = checkHttpResponse(connection);
if (resp != ServiceConnectionStatus.SUCCESS) {
return resp;
}
session.setUsername(username);
// session.setId(sessionId);
updateSessionCookie(connection);
return ServiceConnectionStatus.SUCCESS;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
JOptionPane.showMessageDialog(null,errorMsg, "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnectionStatus.ERROR;
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
return ServiceConnectionStatus.ERROR;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public void close() {
session = null;
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.io.Serializable;
import java.net.HttpCookie;
import javax.swing.JOptionPane;
/**
* CDB session class, used for keeping all session-related information (session
* id, username, role, etc.).
*/
public class Session implements Serializable {
public enum Role {
USER("User"),
ADMIN("Administrator");
private final String type;
private Role(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
public static Role fromString(String type) {
Role role = null;
switch (type) {
case "User":
role = USER;
break;
case "Administrator":
role = ADMIN;
break;
}
return role;
}
}
private static final long serialVersionUID = 1L;
private String id = null;
private String username = null;
private String cookie = null;
private Role role = null;
public Session() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCookie() {
return cookie;
}
public void setCookie(String cookie) {
this.cookie = cookie;
}
public String verifyCookie() {
if (cookie == null) {
JOptionPane.showMessageDialog(null, "Valid session has not been established.", "Info",JOptionPane.INFORMATION_MESSAGE);
} else {
HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
if (httpCookie.hasExpired()) {
JOptionPane.showMessageDialog(null, "Session has expired.", "Info",JOptionPane.INFORMATION_MESSAGE);
}
}
return cookie;
}
public boolean isValid() {
if (cookie == null) {
return false;
} else {
HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
if (httpCookie.hasExpired()) {
return false;
}
}
return true;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public boolean isAdminRole() {
if (role != null) {
return role.equals(Role.ADMIN);
}
return false;
}
public boolean isUserRole() {
if (role != null) {
return role.equals(Role.USER);
}
return false;
}
@Override
public String toString() {
String result = "{ ";
String delimiter = "";
if (username != null) {
result += "username :" + username;
delimiter = "; ";
}
if (id != null) {
result += delimiter + "id : " + id;
delimiter = "; ";
}
if (cookie != null) {
result += delimiter + "cookie : " + cookie;
}
result += " }";
return result;
}
}
package gov.anl.dm.esafsync.serviceconn;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class StorageServiceConnection extends ServiceConnection{
class Keyword {
static final String EXPERIMENT_NAME = "name";
static final String EXPERIMENT_DESCRIPTION = "description";
static final String EXPERIMENT_TYPE_ID = "experimentTypeId";
static final String EXPERIMENT_START_DATE = "startDate";
static final String EXPERIMENT_END_DATE = "endDate";
}
class StorageServUrl {
static final String EXPERIMENT = "/experiments";
static final String EXPERIMENT_USER = "/usersByExperiment";
static final String START_EXPERIMENT = "/experiments/start";
}
public int addExperiment(String name, String description, String startDate, String endDate) {
Map<String, String> data = new HashMap<>();
if (name == null) {
JOptionPane.showMessageDialog(null, "The experiment name is null", "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnection.ServiceConnectionStatus.ERROR;
} else {
data.put(Keyword.EXPERIMENT_NAME, encode(name));
}
if (description != null) {
data.put(Keyword.EXPERIMENT_DESCRIPTION, encode(description));
}
if (startDate != null) {
data.put(Keyword.EXPERIMENT_START_DATE, encode(startDate));
}
if (endDate != null) {
data.put(Keyword.EXPERIMENT_END_DATE, encode(endDate));
}
data.put(Keyword.EXPERIMENT_TYPE_ID, ESAF_EXPERIMENT_TYPE);
return invokeSessionPostRequest(StorageServUrl.EXPERIMENT, data);
}
public int addExperimentUser(String userName, String experimentName, String role) {
Map<String, String> data = new HashMap<>();
return invokeSessionPostRequest(StorageServUrl.EXPERIMENT_USER + "/" + userName + "/" + experimentName + "/" + role, data);
}
public int startExperiment(String name) {
Map<String, String> data = new HashMap<>();
if (name == null) {
JOptionPane.showMessageDialog(null, "The experiment name is null", "Error",JOptionPane.ERROR_MESSAGE);
return ServiceConnection.ServiceConnectionStatus.ERROR;
} else {
data.put(Keyword.EXPERIMENT_NAME, encode(name));
}
return invokeSessionPutRequest(StorageServUrl.START_EXPERIMENT, data);
}
}
all:
for d in $(SUBDIRS); do $(MAKE) -C $$d $(ARCH); done
dist:
for d in $(SUBDIRS); do $(MAKE) -C $$d $(ARCH); done
clean:
for d in $(SUBDIRS); do $(MAKE) -C $$d clean; done
distclean:
for d in $(SUBDIRS); do $(MAKE) -C $$d distclean; done
for d in $(SUBDIRS); do rm -f `find $$d -name 'RELEASE.local'`; done
tidy: distclean