Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.activemq.ActiveMQConnectionFactory;
- import javax.jms.*;
- import java.lang.IllegalAccessException;
- import java.lang.reflect.*;
- import java.util.TreeMap;
- import java.util.ArrayList;
- import javax.xml.bind.*;
- import java.io.*;
- import generate.*;
- import java.sql.*;
- import java.math.BigInteger;
- //import temp.*;
- public class DBApp implements MessageListener {
- private static ActiveMQConnectionFactory connectionFactory;
- private static javax.jms.Connection connection;
- private static Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- private static Destination requestDest;
- private static Destination responseDest;
- private static MessageProducer producer;
- private static MessageConsumer consumer;
- public DBApp (String port, String String reqName, String resName) {
- setUpQueues(port, reqName, resName);
- }
- private static void setUpQueues(String port, String reqName, String resName) {
- // Setup the main connection and the MessageProducer to send the xml requests.
- try {
- // Create a ConnectionFactory.
- connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + port);
- // Create a Connection.
- connection = connectionFactory.createConnection();
- //System.out.println("ActiveMQ Connection started on port " + port + "...\n");
- // Create a Session.
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- // Create the Queue.
- requestDest = session.createQueue(reqName);
- //System.out.println("BRCH Request Queue created...\n");
- // Create the MessageProducer.
- producer = session.createProducer(requestDest);
- } catch (javax.jms.JMSException e) {
- System.out.println("Error with ActiveMQ connection: " + e);
- System.exit(1);
- } catch (Exception e) {
- System.out.println("A problem occured with starting the ActiveMQ connection: " + e);
- System.exit(1);
- }
- // Setup the MessageConsumer
- try {
- responseDest = session.createQueue(resName);
- //System.out.println("BRCH Response Queue created...\n");
- consumer = session.createConsumer(responseDest);
- consumer.setMessageListener(this);
- } catch (JMSException e) {
- System.out.println("Error with MessageConsumer creation: " + e);
- System.exit(1);
- }
- try {
- // All setup is complete, so start the connection.
- connection.start();
- } catch (JMSException e) {
- System.out.println("Error when starting connection: " + e);
- }
- }
- /*
- * Passes a message to the listener.
- * @param message The <code>Message</code> to be passed to the listener.
- */
- public void onMessage (Message message) {
- String content = "";
- // Only deal with text messages.
- if (message instanceof TextMessage) {
- try {
- content = ((TextMessage) message).getText();
- } catch (JMSException e) {
- System.out.println("Error reading message " + e);
- }
- }
- }
- //////////////////////////////////////////////////////////////////////////
- //UNMARSHALLS THE XML FILE PASSED IN AS AN ARGUMENT /////////////////////
- //RETURNS THE OBJECT REPRESENTING THE ROOT XML (GOES INTO ENVELOPE/BODY/
- ///////////////////////////////////////////////////////////////////////
- public static Body stripSoapTags(Unmarshaller unm, String filepath) throws JAXBException{
- Envelope env = (Envelope)unm.unmarshal(new File(filepath));
- Body bd = (Body)env.getBody();
- return bd;
- }
- ////////////////////////////////////////////////////////////////
- //GIVEN AN OBJECT REPRESENTING XML (AFTER USING STRIPSOAPTAGS)/
- //RETURNS THE ACTIVE ROOT XML NODE AS AN OBJECT///////////////
- /////////////////////////////////////////////////////////////
- public static String getXMLRootTag(Object o) throws IllegalAccessException, InvocationTargetException{
- Class cls = o.getClass();
- String methodName;
- for (Method m : cls.getMethods()){
- methodName = m.getName();
- if (methodName.startsWith("get") && ! methodName.equals("getClass")){
- if (m.invoke(o) != null){
- return methodName;
- }
- }
- }
- return null;
- }
- public static ArrayList setAllElements(Object o)throws IOException, FileNotFoundException{
- BufferedReader in = new BufferedReader(new FileReader("XML.prop"));
- String line = in.readLine();
- ArrayList resp = new ArrayList();
- while (line != null){
- if (line.equals("#")){
- while (!line.equals("#")){
- resp.add(line);
- }
- }
- line = in.readLine();
- }
- return resp;
- }
- ////////////////////////////////////////////////////////
- //RECURSIVELY RETURNS A MAP OF <TAG> ::=> <TEXT-VALUE>/
- //////////////////////////////////////////////////////
- public static TreeMap getAllElements(Object o, TreeMap map) throws IllegalAccessException, InvocationTargetException{
- Class cls = o.getClass();
- String methodName;
- for (Method m : cls.getMethods()){
- methodName = m.getName();
- //CHECK IF IT IS A 'USELESS' GET METHOD
- if (methodName.startsWith("get") && ! methodName.equals("getClass") && ! methodName.equals("getInteger") && ! methodName.equals("getLowestSetBit")){
- //CHECK IF GET METHOD HAS STRING/BIGINT RETURN TYPE
- if (! m.getReturnType().toString().equals("class java.lang.String") && ! m.getReturnType().toString().equals("class java.math.BigDecimal") && ! m.getReturnType().toString().equals("class java.math.BigInteger")){
- //USEFUL GET METHOD BUT
- //BUT ONLY HAS TAG-CHILDREN
- //RECURSE ON CHILDREN
- Object p = m.invoke(o);
- getAllElements(p,map);
- }else{
- //ELEMENT HAS TEXT CHILDREN
- //CHECK IF NULL SINCE SOME METHODS
- //MAY NOT GET USED
- if (m.invoke(o) != null){
- map.put(m.getName(),m.invoke(o));
- }
- }
- }
- }
- return map;
- }
- ///////////////////////////////////////////////////////////////////////////
- //RETURNS AN ARRAYLIST ORDERED BY HOW ELEMENTS APPEAR IN STORED PROCEDURE/
- //0-th ELEMENT IS THE NAME OF THE STORED PROCEDURE TO CALL///////////////
- //i-th ELEMENT IS THE i-th ARGUMENT/////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////
- public static ArrayList getStoredProcedureOrder (TreeMap map, String XMLroot)throws IOException{
- int index;
- int count = 1;
- String element, storedProcedure;
- ArrayList ret = new ArrayList();
- BufferedReader in = new BufferedReader(new FileReader("XML.prop"));
- String line = in.readLine();
- while (line != null){
- //CHECK FOR ':<ELEMENT> <STORED PROCEDURE>'
- if (line.startsWith(":")){
- index = line.indexOf(" ");
- element = line.substring(1,index);
- storedProcedure = line.substring(index+1);
- if (XMLroot.equals(element)){
- ret.add(0,storedProcedure);
- line = in.readLine();
- while(! line.equals("#")){
- ret.add(count,map.get(line));
- line = in.readLine();
- count++;
- }
- }
- }
- line = in.readLine();
- }
- in.close();
- return ret;
- }
- ////////////////////
- //INITIALIZES JDBC/
- //////////////////
- public static void initializeJDBC() {
- try {
- Class.forName("org.postgresql.Driver");
- }catch (ClassNotFoundException cnfe) {
- System.err.println("Couldn't find driver class:");
- cnfe.printStackTrace();
- }
- }
- /////////////////////////////////////////////////
- //CONNECT TO THE DATABASE, RETURNS A CONNECTION/
- ///////////////////////////////////////////////
- public static java.sql.Connection connectDB(String URL, String username, String password) {
- try {
- java.sql.Connection connection = DriverManager.getConnection("jdbc:postgresql:"+URL,username,password);
- return connection;
- }catch (Exception e) {
- return null;
- }
- }
- /////////////////////////////////////////
- //CLOSES THE CONNECTION TO THE DATABASE/
- ///////////////////////////////////////
- public static boolean disconnectDB(java.sql.Connection conection) {
- try {
- conection.close();
- return true;
- }catch (Exception e) {
- return false;
- }
- }
- ////////////////////////////////////////////////////////////
- //RETURNS A STRING THAT WILL BE THE STORED PROCEDURE CALL//
- //THE ARRAYLIST IS GENERATED FROM GETSTOREDPROCEDUREORDER/
- /////////////////////////////////////////////////////////
- public static String getStoredProcedureCall(ArrayList values){
- //BEGIN STRING FORMAT
- String ret = "{ call "+values.get(0)+" (";
- int size = values.size()-1;
- //AT LEAST 1 IN PARAMETER (2 BECAUSE 1 IS ALREADY THE SP)
- if (size >= 1){
- ret += "?";
- for (int i=1; i<size; i++){
- ret += ",?";
- }
- ret += ") } ";
- //NO IN PARAMETERS
- }else{
- ret+= ") }";
- return ret;
- }
- return ret;
- }
- /////////////////
- ////////////////
- //MAIN METHOD//
- //////////////
- /////////////
- public static void main (String args[]) throws JAXBException, JMSException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException, IOException, SQLException {
- if (args.length != 3) {
- System.out.println("Missing arguments");
- System.exit(1);
- }
- DBApp app = new DBApp(args[0],args[1],args[2]);
- //LINK TO JAXB OBJECT FILES
- JAXBContext jc = JAXBContext.newInstance("generate");
- //CREATE UNMARSHALLER
- Unmarshaller unm = jc.createUnmarshaller();
- //STRIP SOAP TAGS AND GET THE 'REAL' ROOT OF THE XML DOCUMENT
- Body o = stripSoapTags(unm, "xml-requests-log/18.xml");
- Method m = o.getClass().getMethod(getXMLRootTag(o));
- Object p = m.invoke(o);
- //GET ALL THE ELEMENT VALUES
- TreeMap map = new TreeMap();
- map = getAllElements(p,map);
- //GET THE NAME OF THE STORED PROCEDURE TO RUN
- ArrayList dbValues = getStoredProcedureOrder(map, getXMLRootTag(o));
- System.out.println(dbValues.size());
- //GET THE STRING THAT WILL BE PASSED AS THE STORED PROCEDURE
- String spCall = getStoredProcedureCall(dbValues);
- ////////////////////
- //JDBC STARTS HERE/
- //////////////////
- initializeJDBC();
- java.sql.Connection conn = connectDB("csc309h-g8roland","g8roland","");
- CallableStatement sql = conn.prepareCall(spCall);
- System.out.println(spCall);
- for (int i=1; i<dbValues.size(); i++){
- System.out.println(dbValues.get(i));
- if (dbValues.get(i) instanceof String){
- sql.setString(i,(String)dbValues.get(i));
- }else if (dbValues.get(i) instanceof java.math.BigDecimal){
- sql.setBigDecimal(i,(java.math.BigDecimal)dbValues.get(i));
- }else if (dbValues.get(i) instanceof java.math.BigInteger){
- sql.setLong(i,((java.math.BigInteger)dbValues.get(i)).longValue());
- }
- }
- ResultSet res = sql.executeQuery();
- //COLUMN RELATED INFORMATION
- ResultSetMetaData met = res.getMetaData();
- //CREATE A MAP OF RETURNED VALUES AND THEIR COLUMN NAME
- ArrayList responseArr = new ArrayList();
- while(res.next()){
- ArrayList resp = new ArrayList();
- for (int i = 1; i <= met.getColumnCount(); i++){
- resp.add(res.getString(i));
- System.out.println(met.getColumnName(i)+" "+res.getString(i));
- }
- responseArr.add(resp);
- }
- conn.close();
- //BEGIN UNMARSHALLIN BY FIRST GETTING AT THE RESPONSE
- //RESPONSE IS THE REQUEST WITH '-RESPONSE' APPENDED
- //jc = JAXBContext.newInstance("temp");
- unm = jc.createUnmarshaller();
- o = stripSoapTags(unm, "edit-content"+"-response.xml");
- m = o.getClass().getMethod(getXMLRootTag(o));
- p = m.invoke(o);
- System.out.println("got here");
- ArrayList setMethods = setAllElements(o);
- for (int i = 0; i<responseArr.size(); i++){
- for (int j=0; j<setMethods.size(); j++){
- System.out.println("here"+setMethods.get(i));
- //Method r = o.getClass().getMethod(setMethods.get(i));
- //ArrayList arr = responseArr.get(i);
- //r.invoke(p,arr.get(j));
- }
- }
- StringWriter sw = new StringWriter();
- Marshaller mrsh = jc.createMarshaller();
- mrsh.marshal(o,sw);
- TextMessage returnMessage = session.createTextMessage(sw.toString());
- System.out.println(sw.toString());
- }//END OF MAIN
- }//END OF CLASS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement