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 1272 additions and 0 deletions
package gov.anl.aps.dm.sync;
public class DmUser {
String username;
String firstName;
String lastName;
String middleName;
String email;
String badge;
String password;
void clear() {
username = null;
firstName = null;
lastName = null;
middleName = null;
email = null;
badge = null;
password = null;
}
}
package gov.anl.aps.dm.sync;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OracleConnection {
Connection connection = null;
private Logger logger;
public OracleConnection(Logger logger) {
this.logger = logger;
}
void connect(Properties config) throws SQLException {
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
} catch (SQLException e) {
logger.log(Level.SEVERE, "Can't establish Oracle Driver", e);
throw e;
}
// logger.log(Level.INFO, "Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(
config.getProperty("oracle.database.connection"),
config.getProperty("oracle.database.username"),
config.getProperty("oracle.database.password"));
} catch (SQLException e) {
logger.log(Level.SEVERE, "Can't connect to Oracle data base", e);
throw e;
}
}
ResultSet getUsers(String table) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeQuery("select * from " + table);
} catch (SQLException ex) {
logger.log(Level.SEVERE, "table {0} does not exist", table);
throw ex;
}
}
void close() {
try {
connection.close();
} catch (SQLException ex) {
logger.log(Level.SEVERE, "problem closing Oracle connection ", ex);
}
}
}
package gov.anl.aps.dm.sync;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PsqlConnection {
Connection connection = null;
private final Map<String, Timestamp> dmUsers = new HashMap<>(); // <username, lastUpdate>
private PreparedStatement insertQuery;
private PreparedStatement updateQuery;
private final String userTable = "user_info";
private Logger logger;
public PsqlConnection(Logger logger) {
this.logger = logger;
}
void connect(Properties config) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Can't establish PosgreSQL Driver", e);
System.exit(0);
}
// logger.log(Level.INFO, "PostgreSQL JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(
config.getProperty("dm.database.connection"),
config.getProperty("dm.database.username"),
config.getProperty("dm.database.password"));
} catch (SQLException e) {
logger.log(Level.SEVERE, "Can't connect to PostgreSQL data base");
throw e;
}
}
void init() throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
} catch (SQLException ex) {
logger.log(Level.SEVERE, "can't create statement for postgreSQL connection");
throw ex;
}
ResultSet results = null;
try {
if (statement != null) {
results = statement.executeQuery("SELECT * FROM " + userTable + ";");
}
} catch (SQLException ex) {
logger.log(Level.SEVERE, "can't execute SELECT query from " + userTable + " table");
throw ex;
}
try {
if (results != null) {
while (results.next()) {
String username = results.getString("username");
Timestamp lastUpdate = results.getTimestamp("last_update");
dmUsers.put(username, lastUpdate);
}
results.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, "query results processing error ", ex);
}
// prepare statements
try {
insertQuery = connection.prepareStatement ("INSERT INTO user_info (username, first_name, last_name, middle_name, email, badge, is_local_user, last_update) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
updateQuery = connection.prepareStatement ("UPDATE user_info SET email = ?, last_name = ?, last_update = ? WHERE username = ?");
} catch (SQLException ex) {
logger.log(Level.SEVERE, "Can't get peaparedStatement from connection ", ex);
throw ex;
}
}
protected Timestamp getUserLastUpdate(String username) {
return dmUsers.get(username);
}
boolean isUser(String username) {
return dmUsers.containsKey(username);
}
void addUser(DmUser dmuser, Timestamp currentTime) {
try {
insertQuery.setString(1, dmuser.username);
insertQuery.setString(2, dmuser.firstName);
insertQuery.setString(3, dmuser.lastName);
insertQuery.setString(4, dmuser.middleName);
insertQuery.setString(5, dmuser.email);
insertQuery.setString(6, dmuser.badge);
insertQuery.setBoolean(7, false);
insertQuery.setTimestamp(8, currentTime);
insertQuery.execute();
} catch (SQLException ex) {
logger.log(Level.SEVERE, "can't execute query to add user ", ex);
}
}
void updateUser(DmUser dmuser, Timestamp currentTime) {
try {
updateQuery.setString(1, dmuser.email);
updateQuery.setString(2, dmuser.lastName);
updateQuery.setTimestamp(3, currentTime);
updateQuery.setString(4, dmuser.username);
updateQuery.executeUpdate();
} catch (SQLException ex) {
logger.log(Level.SEVERE, "can't execute query to update user", ex);
}
}
void close() {
try {
insertQuery.close();
updateQuery.close();
connection.close();
} catch (SQLException ex) {
logger.log(Level.SEVERE, "problem closing PostgreSQL connection ", ex);
}
}
}
package gov.anl.aps.dm.sync;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Synchronizer {
private OracleConnection oConnection;
private PsqlConnection pConnection;
private final Properties config = new Properties();
private final Properties tableRows = new Properties();
private final String oracleTable = "oracleTable.properties";
private FileHandler fileHandler;
private static final Logger logger = Logger.getLogger("AccountSynchronizerLogger");
public static void main(String[] argv) {
Synchronizer sync = new Synchronizer();
sync.loadProperties(argv[0]);
sync.initLogger();
sync.oConnection = new OracleConnection(logger);
sync.pConnection = new PsqlConnection(logger);
sync.connectAndInit();
sync.synchronize();
}
private void loadProperties(String configFile) {
InputStream configInputStream = null;
try {
configInputStream = new FileInputStream(configFile);
} catch (Exception e) {
e.printStackTrace();
}
if (configInputStream != null) {
try {
this.config.load(configInputStream);
} catch (IOException ex) {
initDefaultLogger();
logger.log(Level.SEVERE, "can't load configuration ", ex);
System.exit(-1);
}
} else {
initDefaultLogger();
logger.log(Level.SEVERE, "can't find configuration file");
System.exit(-1);
}
InputStream tableInputStream = getClass().getClassLoader().getResourceAsStream(oracleTable);
if (tableInputStream != null) {
try {
this.tableRows.load(tableInputStream);
} catch (IOException ex) {
logger.log(Level.SEVERE, "can't load Oracle table rows definitions ", ex);
System.exit(-1);
}
}
}
private void initDefaultLogger() {
try {
fileHandler = new FileHandler("accountSynchronizer.log");
logger.addHandler(fileHandler);
logger.log(Level.WARNING, "Using default logger ");
} catch (SecurityException | IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
}
private void initLogger() {
String pattern = config.getProperty("log.file");
int limit = 0;
int count = 0;
try {
String limitProperty = config.getProperty("log.limit");
limit = Integer.decode(limitProperty);
count = Integer.decode(config.getProperty("log.count"));
} catch (NumberFormatException e) {
initDefaultLogger();
logger.log(Level.WARNING, "The logger limit or count are not configured properly. ", e);
System.exit(-1);
}
try {
fileHandler = new FileHandler(pattern, limit, count);
logger.addHandler(fileHandler);
} catch (SecurityException | IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
private void connectAndInit() {
try {
pConnection.connect(config);
}
catch (SQLException e) {
System.exit(-1);
}
try {
oConnection.connect(config);
}
catch (SQLException e) {
pConnection.close();
System.exit(-1);
}
try {
pConnection.init();
}
catch (SQLException e) {
pConnection.close();
oConnection.close();
System.exit(-1);
}
}
private void synchronize() {
java.util.Calendar cal = java.util.Calendar.getInstance();
Timestamp current = new Timestamp(cal.getTimeInMillis());
DmUser dmuser = new DmUser();
try {
ResultSet results = oConnection.getUsers(config.getProperty("oracle.database.table"));
while (results.next()) {
String badge = results.getString("BADGE_NO");
String username = config.getProperty("user.userid.prefix") + badge;
if (pConnection.isUser(username)) {
Timestamp userLastUpdate = pConnection.getUserLastUpdate(username);
if ((results.getTimestamp("LAST_CHANGE_DATE") == null) || (userLastUpdate == null) || (results.getTimestamp("LAST_CHANGE_DATE").compareTo(userLastUpdate) >= 0)) {
// update user
dmuser.email = results.getString("EMAIL");
dmuser.username = username;
dmuser.lastName = results.getString("LAST_NAME");
pConnection.updateUser(dmuser, current);
dmuser.clear();
}
} else {
// add user
dmuser.badge = badge;
dmuser.email = results.getString("EMAIL");
dmuser.firstName = results.getString("FIRST_NAME");
dmuser.lastName = results.getString("LAST_NAME");
dmuser.middleName = results.getString("MIDDLE_NAME");
dmuser.username = username;
pConnection.addUser(dmuser, current);
dmuser.clear();
}
}
} catch (SQLException ex) {
logger.log(Level.SEVERE, "table processing error ", ex);
}
finally {
pConnection.close();
oConnection.close();
}
}
}
File added
File added
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="/local/bfrosik/sync/lib/ojdbc7.jar"/>
<classpathentry kind="lib" path="/local/bfrosik/sync/lib/postgresql-9.4-1201.jdbc4.jar"/>
<classpathentry kind="lib" path="/local/bfrosik/sync/lib/javax.json-api-1.0.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Synchronizer</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
#!/bin/sh
DM_SVN_URL=https://subversion.xray.aps.anl.gov/DataManagement
execute() {
echo "Executing: $@"
eval "$@"
}
# load tools
execute svn export $DM_SVN_URL/trunk/tools/ExperimentSynchronizer ExperimentSynchronizer
EXPSYNC_DIR=ExperimentSynchronizer
cd $EXPSYNC_DIR/lib
# load java 7
execute svn export $DM_SVN_URL/support/src/jdk-7u51-linux-x64.tar.gz
JAVA_VERSION=7u51
tar zxf jdk-${JAVA_VERSION}*.tar.gz
cd ../resources
read -p "Enter Data Acquisition Service Host: " DAQ_SERVICE_HOST
read -p "Enter Experiment Data Root Directory (on DAQ): " DAQ_DATA_DIR
read -p "Enter Data Processing Host: " DAQ_REC_SERVICE_HOST
read -p "Enter Experiment Data Root Directory (on data processing node): " DAQ_REC_DATA_DIR
echo "Generating config file"
cmd="cat config.properties.template \
| sed 's?DAQ_CONNECTION?https://$DAQ_SERVICE_HOST:33336/dm?g' \
| sed 's?DATA_DIR?$DAQ_DATA_DIR?g' \
| sed 's?DAQ_REC_CONNECTION?https://$DAQ_REC_SERVICE_HOST:33336/dm?g' \
| sed 's?DATA_REC_DIR?$DAQ_REC_DATA_DIR?g' \
> config.properties"
eval $cmd || exit 1
cd ..
mkdir bin
execute lib/jdk1.7.0_51/bin/javac -classpath lib/*:resources/* -d bin/ src/gov/anl/dm/esafsync/*.java src/gov/anl/dm/esafsync/serviceconn/*.java
mkdir target
execute lib/jdk1.7.0_51/bin/jar cfm target/ExperimentSynchronizer.jar manifest.txt -C bin/ .
chmod 775 run_expSync.sh
cd ..
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);
}
}