Advertisement
Guest User

Untitled

a guest
Jun 7th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.74 KB | None | 0 0
  1. import org.apache.activemq.ActiveMQConnectionFactory;
  2. import javax.jms.*;
  3. import java.lang.IllegalAccessException;
  4. import java.lang.reflect.*;
  5. import java.util.TreeMap;
  6. import java.util.ArrayList;
  7. import javax.xml.bind.*;
  8. import java.io.*;
  9. import generate.*;
  10. import java.sql.*;
  11. import java.math.BigInteger;
  12.  
  13. //import temp.*;
  14.  
  15. public class DBApp implements MessageListener {
  16.  
  17. private static ActiveMQConnectionFactory connectionFactory;
  18. private static javax.jms.Connection connection;
  19. private static Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  20. private static Destination requestDest;
  21. private static Destination responseDest;
  22. private static MessageProducer producer;
  23. private static MessageConsumer consumer;
  24.  
  25. public DBApp (String port, String String reqName, String resName) {
  26.  
  27. setUpQueues(port, reqName, resName);
  28.  
  29. }
  30.  
  31. private static void setUpQueues(String port, String reqName, String resName) {
  32.  
  33. // Setup the main connection and the MessageProducer to send the xml requests.
  34. try {
  35. // Create a ConnectionFactory.
  36. connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + port);
  37.  
  38. // Create a Connection.
  39. connection = connectionFactory.createConnection();
  40. //System.out.println("ActiveMQ Connection started on port " + port + "...\n");
  41.  
  42. // Create a Session.
  43. session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  44.  
  45. // Create the Queue.
  46. requestDest = session.createQueue(reqName);
  47. //System.out.println("BRCH Request Queue created...\n");
  48.  
  49. // Create the MessageProducer.
  50. producer = session.createProducer(requestDest);
  51.  
  52. } catch (javax.jms.JMSException e) {
  53. System.out.println("Error with ActiveMQ connection: " + e);
  54. System.exit(1);
  55. } catch (Exception e) {
  56. System.out.println("A problem occured with starting the ActiveMQ connection: " + e);
  57. System.exit(1);
  58. }
  59.  
  60. // Setup the MessageConsumer
  61. try {
  62. responseDest = session.createQueue(resName);
  63. //System.out.println("BRCH Response Queue created...\n");
  64.  
  65. consumer = session.createConsumer(responseDest);
  66. consumer.setMessageListener(this);
  67.  
  68. } catch (JMSException e) {
  69. System.out.println("Error with MessageConsumer creation: " + e);
  70. System.exit(1);
  71. }
  72.  
  73. try {
  74. // All setup is complete, so start the connection.
  75. connection.start();
  76. } catch (JMSException e) {
  77. System.out.println("Error when starting connection: " + e);
  78. }
  79.  
  80.  
  81. }
  82.  
  83. /*
  84. * Passes a message to the listener.
  85. * @param message The <code>Message</code> to be passed to the listener.
  86. */
  87. public void onMessage (Message message) {
  88.  
  89. String content = "";
  90.  
  91. // Only deal with text messages.
  92. if (message instanceof TextMessage) {
  93.  
  94. try {
  95. content = ((TextMessage) message).getText();
  96. } catch (JMSException e) {
  97. System.out.println("Error reading message " + e);
  98. }
  99. }
  100.  
  101.  
  102. }
  103.  
  104. //////////////////////////////////////////////////////////////////////////
  105. //UNMARSHALLS THE XML FILE PASSED IN AS AN ARGUMENT /////////////////////
  106. //RETURNS THE OBJECT REPRESENTING THE ROOT XML (GOES INTO ENVELOPE/BODY/
  107. ///////////////////////////////////////////////////////////////////////
  108. public static Body stripSoapTags(Unmarshaller unm, String filepath) throws JAXBException{
  109. Envelope env = (Envelope)unm.unmarshal(new File(filepath));
  110. Body bd = (Body)env.getBody();
  111. return bd;
  112. }
  113.  
  114.  
  115. ////////////////////////////////////////////////////////////////
  116. //GIVEN AN OBJECT REPRESENTING XML (AFTER USING STRIPSOAPTAGS)/
  117. //RETURNS THE ACTIVE ROOT XML NODE AS AN OBJECT///////////////
  118. /////////////////////////////////////////////////////////////
  119. public static String getXMLRootTag(Object o) throws IllegalAccessException, InvocationTargetException{
  120. Class cls = o.getClass();
  121. String methodName;
  122. for (Method m : cls.getMethods()){
  123. methodName = m.getName();
  124. if (methodName.startsWith("get") && ! methodName.equals("getClass")){
  125. if (m.invoke(o) != null){
  126. return methodName;
  127. }
  128. }
  129.  
  130. }
  131. return null;
  132. }
  133.  
  134.  
  135. public static ArrayList setAllElements(Object o)throws IOException, FileNotFoundException{
  136.  
  137. BufferedReader in = new BufferedReader(new FileReader("XML.prop"));
  138. String line = in.readLine();
  139. ArrayList resp = new ArrayList();
  140.  
  141. while (line != null){
  142.  
  143. if (line.equals("#")){
  144. while (!line.equals("#")){
  145. resp.add(line);
  146. }
  147. }
  148. line = in.readLine();
  149. }
  150. return resp;
  151. }
  152.  
  153.  
  154. ////////////////////////////////////////////////////////
  155. //RECURSIVELY RETURNS A MAP OF <TAG> ::=> <TEXT-VALUE>/
  156. //////////////////////////////////////////////////////
  157. public static TreeMap getAllElements(Object o, TreeMap map) throws IllegalAccessException, InvocationTargetException{
  158. Class cls = o.getClass();
  159. String methodName;
  160. for (Method m : cls.getMethods()){
  161. methodName = m.getName();
  162. //CHECK IF IT IS A 'USELESS' GET METHOD
  163. if (methodName.startsWith("get") && ! methodName.equals("getClass") && ! methodName.equals("getInteger") && ! methodName.equals("getLowestSetBit")){
  164. //CHECK IF GET METHOD HAS STRING/BIGINT RETURN TYPE
  165. 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")){
  166. //USEFUL GET METHOD BUT
  167. //BUT ONLY HAS TAG-CHILDREN
  168. //RECURSE ON CHILDREN
  169. Object p = m.invoke(o);
  170. getAllElements(p,map);
  171. }else{
  172. //ELEMENT HAS TEXT CHILDREN
  173. //CHECK IF NULL SINCE SOME METHODS
  174. //MAY NOT GET USED
  175. if (m.invoke(o) != null){
  176. map.put(m.getName(),m.invoke(o));
  177. }
  178. }
  179. }
  180. }
  181. return map;
  182. }
  183.  
  184.  
  185. ///////////////////////////////////////////////////////////////////////////
  186. //RETURNS AN ARRAYLIST ORDERED BY HOW ELEMENTS APPEAR IN STORED PROCEDURE/
  187. //0-th ELEMENT IS THE NAME OF THE STORED PROCEDURE TO CALL///////////////
  188. //i-th ELEMENT IS THE i-th ARGUMENT/////////////////////////////////////
  189. ///////////////////////////////////////////////////////////////////////
  190. public static ArrayList getStoredProcedureOrder (TreeMap map, String XMLroot)throws IOException{
  191. int index;
  192. int count = 1;
  193. String element, storedProcedure;
  194. ArrayList ret = new ArrayList();
  195. BufferedReader in = new BufferedReader(new FileReader("XML.prop"));
  196. String line = in.readLine();
  197.  
  198. while (line != null){
  199. //CHECK FOR ':<ELEMENT> <STORED PROCEDURE>'
  200. if (line.startsWith(":")){
  201. index = line.indexOf(" ");
  202. element = line.substring(1,index);
  203. storedProcedure = line.substring(index+1);
  204.  
  205. if (XMLroot.equals(element)){
  206. ret.add(0,storedProcedure);
  207. line = in.readLine();
  208. while(! line.equals("#")){
  209. ret.add(count,map.get(line));
  210. line = in.readLine();
  211. count++;
  212. }
  213. }
  214. }
  215. line = in.readLine();
  216. }
  217. in.close();
  218. return ret;
  219. }
  220.  
  221.  
  222. ////////////////////
  223. //INITIALIZES JDBC/
  224. //////////////////
  225. public static void initializeJDBC() {
  226. try {
  227. Class.forName("org.postgresql.Driver");
  228. }catch (ClassNotFoundException cnfe) {
  229. System.err.println("Couldn't find driver class:");
  230. cnfe.printStackTrace();
  231. }
  232. }
  233.  
  234. /////////////////////////////////////////////////
  235. //CONNECT TO THE DATABASE, RETURNS A CONNECTION/
  236. ///////////////////////////////////////////////
  237. public static java.sql.Connection connectDB(String URL, String username, String password) {
  238.  
  239. try {
  240. java.sql.Connection connection = DriverManager.getConnection("jdbc:postgresql:"+URL,username,password);
  241. return connection;
  242. }catch (Exception e) {
  243. return null;
  244. }
  245. }
  246.  
  247.  
  248. /////////////////////////////////////////
  249. //CLOSES THE CONNECTION TO THE DATABASE/
  250. ///////////////////////////////////////
  251. public static boolean disconnectDB(java.sql.Connection conection) {
  252. try {
  253. conection.close();
  254. return true;
  255. }catch (Exception e) {
  256. return false;
  257. }
  258. }
  259.  
  260.  
  261. ////////////////////////////////////////////////////////////
  262. //RETURNS A STRING THAT WILL BE THE STORED PROCEDURE CALL//
  263. //THE ARRAYLIST IS GENERATED FROM GETSTOREDPROCEDUREORDER/
  264. /////////////////////////////////////////////////////////
  265. public static String getStoredProcedureCall(ArrayList values){
  266. //BEGIN STRING FORMAT
  267. String ret = "{ call "+values.get(0)+" (";
  268. int size = values.size()-1;
  269.  
  270. //AT LEAST 1 IN PARAMETER (2 BECAUSE 1 IS ALREADY THE SP)
  271. if (size >= 1){
  272. ret += "?";
  273. for (int i=1; i<size; i++){
  274. ret += ",?";
  275. }
  276. ret += ") } ";
  277. //NO IN PARAMETERS
  278. }else{
  279. ret+= ") }";
  280. return ret;
  281. }
  282.  
  283. return ret;
  284.  
  285. }
  286.  
  287.  
  288.  
  289. /////////////////
  290. ////////////////
  291. //MAIN METHOD//
  292. //////////////
  293. /////////////
  294. public static void main (String args[]) throws JAXBException, JMSException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException, IOException, SQLException {
  295.  
  296. if (args.length != 3) {
  297.  
  298. System.out.println("Missing arguments");
  299. System.exit(1);
  300. }
  301.  
  302. DBApp app = new DBApp(args[0],args[1],args[2]);
  303.  
  304.  
  305. //LINK TO JAXB OBJECT FILES
  306. JAXBContext jc = JAXBContext.newInstance("generate");
  307. //CREATE UNMARSHALLER
  308. Unmarshaller unm = jc.createUnmarshaller();
  309.  
  310. //STRIP SOAP TAGS AND GET THE 'REAL' ROOT OF THE XML DOCUMENT
  311. Body o = stripSoapTags(unm, "xml-requests-log/18.xml");
  312. Method m = o.getClass().getMethod(getXMLRootTag(o));
  313. Object p = m.invoke(o);
  314.  
  315. //GET ALL THE ELEMENT VALUES
  316. TreeMap map = new TreeMap();
  317. map = getAllElements(p,map);
  318.  
  319. //GET THE NAME OF THE STORED PROCEDURE TO RUN
  320. ArrayList dbValues = getStoredProcedureOrder(map, getXMLRootTag(o));
  321. System.out.println(dbValues.size());
  322.  
  323. //GET THE STRING THAT WILL BE PASSED AS THE STORED PROCEDURE
  324. String spCall = getStoredProcedureCall(dbValues);
  325.  
  326.  
  327. ////////////////////
  328. //JDBC STARTS HERE/
  329. //////////////////
  330. initializeJDBC();
  331. java.sql.Connection conn = connectDB("csc309h-g8roland","g8roland","");
  332. CallableStatement sql = conn.prepareCall(spCall);
  333. System.out.println(spCall);
  334.  
  335. for (int i=1; i<dbValues.size(); i++){
  336. System.out.println(dbValues.get(i));
  337. if (dbValues.get(i) instanceof String){
  338. sql.setString(i,(String)dbValues.get(i));
  339. }else if (dbValues.get(i) instanceof java.math.BigDecimal){
  340. sql.setBigDecimal(i,(java.math.BigDecimal)dbValues.get(i));
  341. }else if (dbValues.get(i) instanceof java.math.BigInteger){
  342. sql.setLong(i,((java.math.BigInteger)dbValues.get(i)).longValue());
  343. }
  344. }
  345.  
  346. ResultSet res = sql.executeQuery();
  347. //COLUMN RELATED INFORMATION
  348. ResultSetMetaData met = res.getMetaData();
  349.  
  350. //CREATE A MAP OF RETURNED VALUES AND THEIR COLUMN NAME
  351. ArrayList responseArr = new ArrayList();
  352.  
  353. while(res.next()){
  354. ArrayList resp = new ArrayList();
  355. for (int i = 1; i <= met.getColumnCount(); i++){
  356. resp.add(res.getString(i));
  357. System.out.println(met.getColumnName(i)+" "+res.getString(i));
  358. }
  359. responseArr.add(resp);
  360. }
  361.  
  362. conn.close();
  363.  
  364.  
  365. //BEGIN UNMARSHALLIN BY FIRST GETTING AT THE RESPONSE
  366. //RESPONSE IS THE REQUEST WITH '-RESPONSE' APPENDED
  367. //jc = JAXBContext.newInstance("temp");
  368. unm = jc.createUnmarshaller();
  369. o = stripSoapTags(unm, "edit-content"+"-response.xml");
  370. m = o.getClass().getMethod(getXMLRootTag(o));
  371. p = m.invoke(o);
  372. System.out.println("got here");
  373. ArrayList setMethods = setAllElements(o);
  374.  
  375. for (int i = 0; i<responseArr.size(); i++){
  376. for (int j=0; j<setMethods.size(); j++){
  377. System.out.println("here"+setMethods.get(i));
  378. //Method r = o.getClass().getMethod(setMethods.get(i));
  379. //ArrayList arr = responseArr.get(i);
  380. //r.invoke(p,arr.get(j));
  381. }
  382. }
  383.  
  384. StringWriter sw = new StringWriter();
  385. Marshaller mrsh = jc.createMarshaller();
  386. mrsh.marshal(o,sw);
  387.  
  388. TextMessage returnMessage = session.createTextMessage(sw.toString());
  389.  
  390.  
  391. System.out.println(sw.toString());
  392.  
  393.  
  394.  
  395.  
  396.  
  397. }//END OF MAIN
  398. }//END OF CLASS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement