Exemplo n.º 1
0
 public void excluir(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlExcluir = "DELETE FROM oriundo WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlExcluir);
     ps.setInt(1, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Ecluido Com Sucesso: ", "Mensagem do Sistema - Excluir", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Excluir", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
Exemplo n.º 2
0
 public List<Oriundo> listar() throws SQLException {
   List<Oriundo> resultado = new ArrayList<Oriundo>();
   conexao propCon = new conexao();
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           propCon.config.getString("usuario"),
           propCon.config.getString("senha"));
   PreparedStatement ps = null;
   ResultSet rs = null;
   String sqlListar = "SELECT * FROM oriundo Order by codigo DESC";
   Oriundo oriundo;
   try {
     ps = con.prepareStatement(sqlListar);
     rs = ps.executeQuery();
     // if(rs==null){
     // return null;
     // }
     while (rs.next()) {
       oriundo = new Oriundo();
       oriundo.setCodigo(rs.getInt("codigo"));
       oriundo.setDescricao(rs.getString("descricao"));
       oriundo.setData_cadastro(rs.getDate("data_cadastro"));
       oriundo.setDia_fechamento(rs.getInt("dia_fechamento"));
       oriundo.setDia_pag(rs.getInt("dia_pag"));
       resultado.add(oriundo);
     }
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Localizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
   return resultado;
 }
Exemplo n.º 3
0
  public Collection<domain.BridgeInfo> findBlock(double height, double length, double width) {
    connection = getConnection();
    Collection<domain.BridgeInfo> brigeInf = new ArrayList<>();

    String query =
        "SELECT OBJECTID, COLLOQUIAL_NAME_1, COLLOQUIAL_NAME_2, COLLOQUIAL_NAME_3, "
            + "CAST(MIN_CLEARANCE AS FLOAT) AS MIN_CLEARANCE, "
            + "CAST(OVERALL_LENGTH AS FLOAT) AS OVERALL_LENGTH, "
            + "CAST(OVERALL_WIDTH AS FLOAT) AS OVERALL_WIDTH, LAT, LONGIT FROM guest.Tbl_bridge_structure_vic "
            + "WHERE CAST(MIN_CLEARANCE AS FLOAT) > ? "
            + "AND CAST(OVERALL_LENGTH AS FLOAT) > ? AND CAST(OVERALL_WIDTH AS FLOAT) > ?;";

    try {
      preps = connection.prepareStatement(query);

      preps.setDouble(1, height);
      preps.setDouble(2, length);
      preps.setDouble(3, width);
      ResultSet rset = preps.executeQuery();

      while (rset.next()) {
        domain.BridgeInfo bridge = new BridgeInfo();

        bridge.setObjectId(rset.getString(1));
        bridge.setCollName1(rset.getString(2));
        bridge.setCollName2(rset.getString(3));
        bridge.setCollName3(rset.getString(4));
        bridge.setMinClearance(rset.getDouble(5));
        bridge.setLength(rset.getDouble(6));
        bridge.setWidth(rset.getDouble(7));
        bridge.setLat(rset.getDouble(8));
        bridge.setLongit(rset.getDouble(9));
        brigeInf.add(bridge);
      }

      connection.close();
      rset.close();

    } catch (SQLException ex) {
      Logger.getLogger(jdbc.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
      System.out.println(ex.getMessage());
    }
    System.out.println(brigeInf.size());
    return brigeInf;
  }
Exemplo n.º 4
0
 public Oriundo localizar(Integer codigo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   ResultSet rs = null;
   String sqlLocalizar = "SELECT * FROM oriundo WHERE codigo=?";
   Oriundo oriundo = new Oriundo();
   try {
     ps = con.prepareStatement(sqlLocalizar);
     ps.setInt(1, codigo);
     rs = ps.executeQuery();
     // if(!rs.next()){
     // return null;
     // }
     oriundo.setCodigo(rs.getInt("codigo"));
     oriundo.setDescricao(rs.getString("descricao"));
     oriundo.setData_cadastro(rs.getDate("data_cadastro"));
     oriundo.setDia_fechamento(rs.getInt("dia_fechamento"));
     oriundo.setDia_pag(rs.getInt("dia_pag"));
     return oriundo;
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Localizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
   return oriundo;
 }
Exemplo n.º 5
0
 public void atualizar(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlAtualizar =
       "UPDATE oriundo SET descricao=?, data_cadastro=?, dia_fechamento=?, dia_pag=? WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlAtualizar);
     ps.setString(1, oriundo.getDescricao());
     ps.setDate(2, oriundo.getData_cadastro());
     ps.setInt(3, oriundo.getDia_fechamento());
     ps.setInt(4, oriundo.getDia_pag());
     ps.setInt(5, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Atualizado Com Sucesso: ", "Mensagem do Sistema - Atualizar", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Atualizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
Exemplo n.º 6
0
 public void salvar(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlSalvar =
       "INSERT INTO oriundo (descricao, data_cadastro, dia_fechamento, dia_pag ) VALUES (?, ?, ?, ?)";
   try {
     ps = con.prepareStatement(sqlSalvar);
     ps.setString(1, oriundo.getDescricao());
     ps.setDate(2, oriundo.getData_cadastro());
     ps.setInt(3, oriundo.getDia_fechamento());
     ps.setInt(4, oriundo.getDia_pag());
     ps.executeUpdate();
     // JOptionPane.showMessageDialog(null, "Inserido Com Sucesso: ", "Mensagem do Sistema -
     // Salvar", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Salvar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
Exemplo n.º 7
0
  public void start() {

    Connection connection = null; // manages connection
    Connection connection2 = null;
    Statement statement = null; // query statement
    Statement statement2 = null;
    wm = new double[20][Data.windows_size];
    String QueryKinasesName = "%" + Data.kinease + "%";
    // data.code = data.codenames[3];
    String QueryCodeName = Data.code;
    int windows_size = Data.windows_size;

    // int windows_size = 9;

    int shift = windows_size / 2;

    try {
      Class.forName(JDBC_DRIVER); // load database driver class
      for (windows_size = Data.windows_size; windows_size <= Data.windows_size; windows_size += 2) {
        shift = windows_size / 2;
        // establish connection to database
        connection = DriverManager.getConnection(DATABASE_URL, "", "");
        connection2 = DriverManager.getConnection(DATABASE_URL, "", "");
        // create Statement for querying database
        statement = connection.createStatement();
        statement2 = connection2.createStatement();
        String ACC = null;
        String SEQUENCE = null;
        String KINASES = null;
        String LIKE = "LIKE";
        // int POSITION = 0;
        // int index = 0;
        String temp = null;
        // int numtemp = 0;
        // int LENGTH = (int) 0;
        // int count = 0;
        double[] totalAAcount = new double[windows_size];

        double weightmatrix[][] = new double[windows_size][128]; // windowssize;aa;

        String statementquery1 =
            "SELECT Mid(sequence,(position-"
                + shift
                + "),"
                + windows_size
                + ") AS TARGET, index,code,length,position,sequence FROM Dataset_041106 WHERE ((position-"
                + shift
                + ")>1) AND ((position +"
                + shift
                + ")<length) AND kinases "
                + LIKE
                + " '"
                + QueryKinasesName
                + "' AND (code LIKE '"
                + QueryCodeName
                + "')";
        System.out.println("#" + statementquery1);
        /// fout.println("#"+statementquery1);
        ResultSet resultSet1 = statement.executeQuery(statementquery1);
        int seqsize = 0;
        while ((resultSet1.next())) {
          String posseq = resultSet1.getString("TARGET");
          seqsize = posseq.length();
          if (posseq.charAt(0) != 'X' && posseq.charAt(seqsize - 1) != 'X') { // �h����t

            for (int i = 0; i < seqsize; i++) {

              weightmatrix[i][posseq.charAt(i)]++;
            }
            // possequence.addElement(posseq);
          }
        } // end while
        char[] aaMap = {
          'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W',
          'Y', 'V', 'X'
        };
        double[] expmatrix = {
          0.0701313443873091,
          0.0582393695201718,
          0.0359362961736045,
          0.0520743144385134,
          0.0172010453343506,
          0.0498574962335004,
          0.0796465136978452,
          0.0624720283551962,
          0.0241405228512130,
          0.0416989778376737,
          0.0934441156861220,
          0.0632334844952389,
          0.0213293464067050,
          0.0324554733241482,
          0.0651181982370858,
          0.0881672518230193,
          0.0524630941595624,
          0.0101093184162382,
          0.0244701177088640,
          0.0578116909136386
        };
        // double[] aaMapfreq = new double[windows_size];
        double freq = 0;
        for (int j = 0; j < weightmatrix.length; j++) {
          for (int i = 0; i < aaMap.length - 1; i++) {
            totalAAcount[j] += weightmatrix[j][aaMap[i]];
          }
        }

        for (int i = 0; i < aaMap.length - 1; i++) {
          // profilefout.print(aaMap[i]);
          for (int j = 0; j < windows_size; j++) {

            freq = ((weightmatrix[j][aaMap[i]]) / (totalAAcount[j])) + 1;

            wm[i][j] = Math.log10((freq / expmatrix[i])) / Math.log10(2.0);

            //  profilefout.print(","+aaMapfreq[i]);

          }
          // profilefout.println();
        }

        // fout.close();
        // profilefout.close();

        resultSet1.close();
        connection.close();
      }

    } // end try
    catch (ClassNotFoundException classNotFound) {
      classNotFound.printStackTrace();
      System.exit(1);
    } catch (NullPointerException nullpointerException) {
      nullpointerException.printStackTrace();
      System.exit(1);

    } catch (SQLException ex) {
      /** @todo Handle this exception */
      /*        } catch (IOException ex) {
       */
      /** @todo Handle this exception */
    } catch (NoClassDefFoundError ex) {

    } finally { // ensure statement and connection are closed properly
      try {
        statement.close();
        statement2.close();

        connection.close();

        connection2.close();
      } catch (Exception exception) { // end try
        exception.printStackTrace();
        System.exit(1);
      } // end catch
    } // end finally
  } // end main
Exemplo n.º 8
0
  public void start2() {

    wm = new double[20][Data.windows_size];
    String QueryKinasesName = "%" + Data.kinease + "%";
    // data.code = data.codenames[3];
    String QueryCodeName = Data.code;
    int windows_size = Data.windows_size;

    // int windows_size = 9;

    int shift = windows_size / 2;

    try {

      {
        shift = windows_size / 2;
        // establish connection to database

        String ACC = null;
        String SEQUENCE = null;
        String KINASES = null;
        String LIKE = "LIKE";
        // int POSITION = 0;
        // int index = 0;
        String temp = null;
        // int numtemp = 0;
        // int LENGTH = (int) 0;
        // int count = 0;
        double[] totalAAcount = new double[windows_size];

        double weightmatrix[][] = new double[windows_size][128]; // windowssize;aa;

        /// fout.println("#"+statementquery1);

        int seqsize = 0;

        for (int i = 0; i < pwmseq.size(); i++) {
          String posseq = pwmseq.elementAt(i).toString();
          seqsize = posseq.length();
          {
            for (int j = 0; j < seqsize; j++) {

              weightmatrix[j][posseq.charAt(j)]++;
            }
            // possequence.addElement(posseq);
          }
        } // end while
        char[] aaMap = {
          'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W',
          'Y', 'V', 'X'
        };
        double[] expmatrix = {
          0.0701313443873091,
          0.0582393695201718,
          0.0359362961736045,
          0.0520743144385134,
          0.0172010453343506,
          0.0498574962335004,
          0.0796465136978452,
          0.0624720283551962,
          0.0241405228512130,
          0.0416989778376737,
          0.0934441156861220,
          0.0632334844952389,
          0.0213293464067050,
          0.0324554733241482,
          0.0651181982370858,
          0.0881672518230193,
          0.0524630941595624,
          0.0101093184162382,
          0.0244701177088640,
          0.0578116909136386
        };
        // double[] aaMapfreq = new double[windows_size];
        double freq = 0;
        for (int j = 0; j < weightmatrix.length; j++) {
          for (int i = 0; i < aaMap.length - 1; i++) {
            totalAAcount[j] += weightmatrix[j][aaMap[i]];
          }
        }

        for (int i = 0; i < aaMap.length - 1; i++) {
          // profilefout.print(aaMap[i]);
          for (int j = 0; j < windows_size; j++) {

            freq = ((weightmatrix[j][aaMap[i]] + 0.05) / (totalAAcount[j] + 1));

            wm[i][j] = Math.log10((freq / expmatrix[i])) / Math.log10(2.0);

            //  profilefout.print(","+aaMapfreq[i]);

          }
          // profilefout.println();
        }

        // fout.close();
        // profilefout.close();

      }

    } // end try
    catch (NullPointerException nullpointerException) {
      nullpointerException.printStackTrace();
      System.exit(1);

    } catch (NoClassDefFoundError ex) {

    } finally { // ensure statement and connection are closed properly
      try {

      } catch (Exception exception) { // end try
        exception.printStackTrace();
        System.exit(1);
      } // end catch
    } // end finally
  } // end main
Exemplo n.º 9
0
  // ----This function getting search terms and inserts/updates counter with time slots handling----
  // ---------the function making shore the data is always up to date-----------
  // ----------------------------------------------------------------------------------------
  @SuppressWarnings("deprecation")
  public void update_search_terms(
      String text, double num_of_slots, double max_time_frame_hours, String query)
      throws MongoException {
    // long starttime = System.currentTimeMillis();
    log4j.info(
        "starting function update_search_terms, num_of_slots = "
            + num_of_slots
            + ", max_time_frame_hours = "
            + max_time_frame_hours
            + ", query = "
            + query);
    String[] textarray = text.split(" "); // split tweet text into a words array
    log4j.info("split tweet text into a word array");
    BasicDBObject objterm = new BasicDBObject();
    DBObject objtoupd = new BasicDBObject();
    DBObject update = new BasicDBObject();
    DBObject curr_slot = new BasicDBObject();

    log4j.info("starting function update_search_terms");
    curr_slot = this.collslot.findOne(); // get current time slot information
    this.current_slot_start_time =
        (long) (Double.parseDouble((curr_slot.get("slot_start_time").toString())));
    Date resultdate = new Date(this.current_slot_start_time);
    log4j.info("current_slot_start_time is : " + resultdate.toLocaleString());
    this.current_slot_index = Integer.parseInt(curr_slot.get("current_slot").toString());
    log4j.info("current time slot is  : " + this.current_slot_index);
    long difference = System.currentTimeMillis() - this.current_slot_start_time;

    if (difference > this.slot_time_millis) { // starting a new time slot
      // update current slot information
      this.current_slot_start_time += (long) this.slot_time_millis;
      this.current_slot_index = (int) ((this.current_slot_index + 1) % num_of_slots);
      log4j.info("new slot time has come, new slot is slot number " + this.current_slot_index);
      curr_slot.put("current_slot", this.current_slot_index);
      curr_slot.put("slot_start_time", this.current_slot_start_time);
      curr_slot.put(
          "slot_start_time_string", new Date(this.current_slot_start_time).toLocaleString());
      log4j.info("updating new current slot time and number in db");
      this.collslot.save(curr_slot);

      DBCursor terms =
          this.collsearch.find(); // get all search_terms documents to update new slot to zero
      while (terms.hasNext()) {
        try {
          // update new slot to zero and reducing from over_all the old data in all documents
          DBObject term = terms.next();
          if (term.get("search_term") != null) {
            objtoupd.put("search_term", term.get("search_term"));
            term.put("slot" + this.current_slot_index, 0);
            term.put("current_slot", this.current_slot_index);
            term.put(
                "over_all",
                Integer.parseInt(term.get("over_all").toString())
                    - Integer.parseInt(term.get("slot" + this.current_slot_index).toString()));

            this.collsearch.save(term);
          }
        } catch (NullPointerException e) {
          e.printStackTrace();
          log4j.info(e);
        }
      }
    }
    // start looking for new search terms in text
    log4j.info("going over the tweet text");
    query = query.replaceAll("%40", "@"); // utf-8 code of @
    query = query.replaceAll("%23", "#"); // utf-8 code of #
    DBObject nodes = new BasicDBObject();
    nodes.put("parent", query);
    nodes =
        colltree.findOne(nodes); // check if there is a document for parent in tree_nodes collection
    if (nodes == null) // there is no document in tree_nodes
    {
      nodes = new BasicDBObject();
      nodes.put("son", "no");
      nodes.put("parent", query);
    } else // there is document in tree_nodes
    {
      nodes.put("in_process", 1); // mark as busy
      this.colltree.save(nodes);
      // nodes.put("son", nodes.get("son").toString() + "");
    }
    for (int i = 0; i < textarray.length; i++) { // loop over the words of the tweet
      if (textarray[i].trim().startsWith("@") || textarray[i].trim().startsWith("#")) {
        String thisterm = textarray[i].trim(); // cut white spaces
        String[] no_ddot = thisterm.split("[:,., ,;,\n]");
        thisterm = no_ddot[0];
        thisterm = thisterm.replaceAll("%40", "@");
        thisterm = thisterm.replaceAll("%23", "#");
        if (thisterm.length() > 1) {
          log4j.info("search word: " + thisterm);
          objterm.put("search_term", thisterm); // object to find the search word in collection
          log4j.info("inserting tree nodes to mongodb");
          if (String.valueOf(query)
              != String.valueOf(thisterm)) { // query and search term not equal
            if (nodes.get("son").toString() == "no") // no document in collection yet
            {

              nodes.put("son", thisterm);
            } else // there is document in collection
            {
              nodes.put("son", nodes.get("son").toString() + "," + thisterm);
            }
            // nodes.put("son", thisterm);

            // neo4j.addNode(query, thisterm, log4j);
          }

          // objtoupd = collsearch.findOne(objterm); // find the search word in collection
          try {
            DBObject term =
                this.collsearch.findOne(objterm); // get document os search_term if exists
            // update current slot and over_all for existing document
            term.put("over_all", Integer.parseInt(term.get("over_all").toString()) + 1);
            term.put(
                "slot" + current_slot_index,
                Integer.parseInt(term.get("slot" + this.current_slot_index).toString()) + 1);
            // term.put("current_slot_start_time_millis", current_slot_start_time);
            log4j.info("updating counter in current slot for word: " + thisterm);
            this.collsearch.update(objterm, term);
          } catch (NullPointerException e) { // there is no document for search term in collection
            // creating a new document
            log4j.info(thisterm + " is not yet in collection , inserting it");
            DBObject newline = new BasicDBObject();
            newline.put("search_term", thisterm);
            newline.put("over_all", 1);
            newline.put("max_id", 0);
            newline.put("current_slot", current_slot_index);
            newline.put("current_slot_start_time_millis", current_slot_start_time);
            // creating all slots for document
            for (int j = 0; j < num_of_slots; j++) {
              if (j == current_slot_index) {
                newline.put("slot" + current_slot_index, 1); // current slot = 1
              } else {
                newline.put("slot" + j, 0); // non current slot = 0
              }
            }

            this.collsearch.insert(newline);
          }
        }
        nodes.put("in_process", 0); // update tree_nodes document as not busy
        this.colltree.save(nodes);
      }
    }
    log4j.info("end update_search_terms");
  }
Exemplo n.º 10
0
  public Document getUomUpload(YFSEnvironment env, Document inXML) throws Exception {
    /** try-catch block added by Arun Sekhar on 01-Feb-2011 for CENT tool logging * */
    Element UOMElement1 = null;
    try {
      int rSet = 0;
      String finalQuery = null;
      NodeList UOMList = inXML.getElementsByTagName("Uom");
      for (int UOMNo = 0; UOMNo < UOMList.getLength(); UOMNo++) {
        String uniqueSequenceNo = getUniqueSequenceNo(env);

        UOMElement1 = (Element) UOMList.item(UOMNo);
        String Uom = UOMElement1.getAttribute("Uom");
        String UomDescription = UOMElement1.getAttribute("UomDescription");

        Document getUomListInputDoc = YFCDocument.createDocument("Uom").getDocument();
        getUomListInputDoc.getDocumentElement().setAttribute("Uom", Uom);
        getUomListInputDoc.getDocumentElement().setAttribute("OrganizationCode", "DEFAULT");
        env.setApiTemplate("getUomList", getUomListTemplate);
        Document getUomListOutputDoc = api.invoke(env, "getUomList", getUomListInputDoc);
        log.info("The output of getUomList is: " + SCXmlUtil.getString(getUomListInputDoc));
        env.clearApiTemplate("getUomList");
        if (getUomListOutputDoc.getDocumentElement().getElementsByTagName("Uom").getLength() > 0) {
          Element uomElement =
              (Element)
                  getUomListOutputDoc.getDocumentElement().getElementsByTagName("Uom").item(0);
          String uomKey = "";
          uomKey = uomElement.getAttribute("UomKey");
          log.info("The uomkey retrieved is: " + uomKey);
          if (uomKey != null && uomKey.trim().length() > 0) {
            finalQuery =
                "UPDATE YFS_UOM SET UOM_DESCRIPTION = '"
                    + UomDescription
                    + "' WHERE UOM_KEY='"
                    + uomKey
                    + "'";
            log.info("The query for uom is: " + finalQuery);
          }
        } else {

          finalQuery =
              "INSERT INTO YFS_UOM(UOM_KEY,ORGANIZATION_CODE,UOM_TYPE,UOM,UOM_DESCRIPTION,CREATEUSERID,MODIFYUSERID,CREATEPROGID,MODIFYPROGID) VALUES('"
                  + uniqueSequenceNo
                  + "','DEFAULT','QUANTITY','"
                  + Uom
                  + "','"
                  + UomDescription
                  + "','xpxBatchLoadAgent','xpxBatchLoadAgent','xpxBatchLoadAgent','xpxBatchLoadAgent')";
          log.info("The query for uom is: " + finalQuery);
        }
        rSet = fireQuery(env, finalQuery, inXML);
        /*if(rSet!=-1)
        {
        	log.info(UomDescription+"YFS_UOM Record not Inserted in YFS_UOM table");

        }*/

        Document getItemUomMasterListInputDoc =
            YFCDocument.createDocument("ItemUOMMaster").getDocument();
        getItemUomMasterListInputDoc.getDocumentElement().setAttribute("UnitOfMeasure", Uom);
        getItemUomMasterListInputDoc.getDocumentElement().setAttribute("OrganizationCode", "xpedx");
        env.setApiTemplate("getItemUOMMasterList", getItemUomMasterListTemplate);
        Document getItemUomMasterListOutputDoc =
            api.invoke(env, "getItemUOMMasterList", getItemUomMasterListInputDoc);
        log.info(
            "The output of getItemUOMMasterList is: "
                + SCXmlUtil.getString(getItemUomMasterListOutputDoc));
        env.clearApiTemplate("getItemUOMMasterList");
        if (getItemUomMasterListOutputDoc
                .getDocumentElement()
                .getElementsByTagName("ItemUOMMaster")
                .getLength()
            > 0) {
          Element itemUommasterElement =
              (Element)
                  getItemUomMasterListOutputDoc
                      .getDocumentElement()
                      .getElementsByTagName("ItemUOMMaster")
                      .item(0);
          String itemUommasterKey = "";
          itemUommasterKey = itemUommasterElement.getAttribute("ItemUOMMasterKey");
          log.info("The item uom master key is: " + itemUommasterKey);
          if (itemUommasterKey != null && itemUommasterKey.trim().length() > 0) {
            finalQuery =
                "UPDATE YFS_ITEM_UOM_MASTER SET DESCRIPTION = '"
                    + UomDescription
                    + "' WHERE ITEM_UOM_MASTER_KEY='"
                    + itemUommasterKey
                    + "'";
            log.info("The query for item_uom_master is: " + finalQuery);
          }
        } else {
          finalQuery =
              "INSERT INTO YFS_ITEM_UOM_MASTER(ITEM_UOM_MASTER_KEY,ORGANIZATION_CODE,UOM ,UOM_TYPE ,ITEM_GROUP_CODE,DESCRIPTION ,ALLOW_FRACTIONS_IN_CONVERSION,IS_INVENTORY_UOM ,IS_ORDERING_UOM,CREATEUSERID,MODIFYUSERID,CREATEPROGID,MODIFYPROGID)values('"
                  + uniqueSequenceNo
                  + "','xpedx','"
                  + Uom
                  + "','QUANTITY','PROD','"
                  + UomDescription
                  + "','N','Y','Y','xpxBatchLoadAgent','xpxBatchLoadAgent','xpxBatchLoadAgent','xpxBatchLoadAgent')";
          log.info("The query for item_uom_master is: " + finalQuery);
        }
        rSet = fireQuery(env, finalQuery, inXML);
        /*if(rSet!=-1)
        {
        	//log.info(UomDescription+"YFS_ITEM_UOM_MASTER Record not Inserted");
        }*/
      }
    } catch (NullPointerException ne) {
      log.error("------------Failed XML Needs to Catch for Re-Processing XML START ----------");
      log.error(SCXmlUtil.getString(UOMElement1));
      log.error("------------Failed XML Needs to Catch for Re-Processing XML END ----------");
      log.error("NullPointerException: " + ne.getStackTrace());
      prepareErrorObject(ne, XPXLiterals.UOM_B_TRANS_TYPE, XPXLiterals.NE_ERROR_CLASS, env, inXML);
      throw ne;
    } catch (YFSException yfe) {
      log.error("------------Failed XML Needs to Catch for Re-Processing XML START ----------");
      log.error(SCXmlUtil.getString(UOMElement1));
      log.error("------------Failed XML Needs to Catch for Re-Processing XML END ----------");
      log.error("YFSException: " + yfe.getStackTrace());
      prepareErrorObject(
          yfe, XPXLiterals.UOM_B_TRANS_TYPE, XPXLiterals.YFE_ERROR_CLASS, env, inXML);
      throw yfe;
    } catch (Exception e) {
      log.error("------------Failed XML Needs to Catch for Re-Processing XML START ----------");
      log.error(SCXmlUtil.getString(UOMElement1));
      log.error("------------Failed XML Needs to Catch for Re-Processing XML END ----------");
      log.error("Exception: " + e.getStackTrace());
      prepareErrorObject(e, XPXLiterals.UOM_B_TRANS_TYPE, XPXLiterals.E_ERROR_CLASS, env, inXML);
      throw e;
    }
    return inXML;
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String id = request.getParameter("hashID");
    JSONObject result = new JSONObject();

    if (id != null && id.trim().isEmpty()) {
      response.setContentType("text/plain");
      response.setStatus(400);
      out.println("Empty hash ID");
      return;
    }

    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    String password;
    try {
      // Read the SQL password from a file
      BufferedReader reader = null;
      try {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("SQLpw.txt");
        reader = new BufferedReader(new InputStreamReader(inputStream));
        password = reader.readLine();
      } catch (NullPointerException e) {
        e.getStackTrace();
        password = "";
      }

      // create a mysql database connection
      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost/lodstories";
      Class.forName(myDriver);
      conn = DriverManager.getConnection(myUrl, "root", password);
      st = conn.createStatement();
      rs = st.executeQuery("SELECT hash,title,author FROM hash_objects where id='" + id + "'");

      if (!rs.next()) {
        response.setContentType("text/plain");
        response.setStatus(400);
        out.println("Error retrieving hash object");
        return;
      }

      result.put("hash", rs.getString("hash"));
      result.put("title", rs.getString("title"));
      result.put("author", rs.getString("author"));
      // result.put("path", rs.getString("path"));
      // result.put("rating", rs.getInt("rating"));

      // Update the lastAccessed field
      st.executeUpdate(
          "UPDATE hash_objects SET lastAccessed=CURRENT_TIMESTAMP() WHERE id='" + id + "'");

      response.setContentType("application/json");

      response.setCharacterEncoding("UTF-8");
      out.println(result);
    } catch (ClassNotFoundException e) {
      System.err.println("Could not connect to driver!");
      System.err.println(e.getMessage());

    } catch (SQLException ex) {
      System.err.println(
          "SQLException: "
              + ex.getMessage()
              + ", SQLState: "
              + ex.getSQLState()
              + "VendorError: "
              + ex.getErrorCode());
    } catch (JSONException ex) {
      ex.printStackTrace();
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
      if (st != null) {
        try {
          st.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }
  }