Exemplo n.º 1
1
 /*
  * create method, that read from a txt file and read the MySQL language and write to the database.
  */
 public void createDB() {
   try {
     BufferedReader br = new BufferedReader(new FileReader("db_schema.txt"));
     String line = null;
     StringBuilder sb = new StringBuilder();
     while ((line = br.readLine()) != null) {
       sb.append(line);
       if (sb.length() > 0
           && sb.charAt(sb.length() - 1) == ';') { // see if it is the end of one line of command
         statement.executeUpdate(sb.toString());
         sb = new StringBuilder();
       }
     }
     br.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 2
0
  /**
   * Test that <code>Clob.getCharacterStream(long,long)</code> works on CLOBs that are streamed from
   * store. (DERBY-2891)
   */
  public void testGetCharacterStreamLongOnLargeClob() throws Exception {
    getConnection().setAutoCommit(false);

    // create large (>32k) clob that can be read from store
    final int size = 33000;
    StringBuilder sb = new StringBuilder(size);
    for (int i = 0; i < size; i += 10) {
      sb.append("1234567890");
    }

    final int id = BlobClobTestSetup.getID();
    PreparedStatement ps =
        prepareStatement("insert into blobclob(id, clobdata) values (?,cast(? as clob))");
    ps.setInt(1, id);
    ps.setString(2, sb.toString());
    ps.executeUpdate();
    ps.close();

    Statement s = createStatement();
    ResultSet rs = s.executeQuery("select clobdata from blobclob where id = " + id);
    assertTrue(rs.next());
    Clob c = rs.getClob(1);

    // request a small region of the clob
    BufferedReader r = new BufferedReader(c.getCharacterStream(4L, 3L));
    assertEquals("456", r.readLine());

    r.close();
    c.free();
    rs.close();
    s.close();
    rollback();
  }
  /**
   * read the file with filename substrings -- existing files with those substrings will not get
   * preserved to preserve-dir.
   *
   * @author [email protected]
   * @date Thu Apr 5 17:43:37 2012
   */
  void initializeNoPreserve(String sFilename) {
    m_lNoPreserveSubstrings = new ArrayList<String>(10);

    BufferedReader in = null;

    try {
      in = new BufferedReader(new FileReader(sFilename));

      String s;
      while ((s = in.readLine()) != null) {
        s = s.trim();

        System.out.println("will not preserve files with substring: " + s);

        m_lNoPreserveSubstrings.add(s.trim());
      }
    } catch (Exception e) {
      System.out.println("ERROR: Failed to get no-preserve substrings: " + e);
      return;
    } finally {
      try {
        in.close();
      } catch (Exception e2) {
      }
    }
  }
Exemplo n.º 4
0
  public static String getFooter(String context) {
    try {
      FileReader fileReader =
          new FileReader(findResourceOnFileSystem("servletResponseTemplate.htm"));
      BufferedReader buffread = new BufferedReader(fileReader);
      String templateFile = "", line;
      StringBuffer SBreader = new StringBuffer();
      while ((line = buffread.readLine()) != null) {
        SBreader.append(line).append("\n");
      }
      fileReader.close();
      buffread.close();
      templateFile = SBreader.toString();
      templateFile =
          templateFile.replaceAll(
              "BOTTOMGRAPHIC", CommonConfiguration.getURLToFooterGraphic(context));

      int end_header = templateFile.indexOf("INSERT_HERE");
      return (templateFile.substring(end_header + 11));
    } catch (Exception e) {
      // out.println("I couldn't find the template file to read from.");
      e.printStackTrace();
      String error =
          "An error occurred while attempting to read from an HTML template file. This probably will not affect the success of the operation you were trying to perform.</p></body></html>";
      return error;
    }
  }
Exemplo n.º 5
0
 /** Load data. */
 private ArrayList loadData() {
   try {
     ArrayList vos = new ArrayList();
     BufferedReader br =
         new BufferedReader(new InputStreamReader(new FileInputStream("orders.txt")));
     String line = null;
     SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
     OrdersVO vo = null;
     String[] t = null;
     while ((line = br.readLine()) != null) {
       t = line.split(";");
       vo = new OrdersVO();
       vos.add(vo);
       vo.setOrderDate(sdf.parse(t[0]));
       vo.setCategory(t[1]);
       vo.setSubCategory(t[2]);
       vo.setCountry(t[3]);
       vo.setZone(t[4]);
       vo.setAgent(t[5]);
       vo.setItem(t[6]);
       vo.setSellQty(new BigDecimal(t[7]));
       vo.setSellAmount(new BigDecimal(t[8]));
     }
     br.close();
     return vos;
   } catch (Exception ex) {
     ex.printStackTrace();
     return new ArrayList();
   }
 }
Exemplo n.º 6
0
  static void fun() {
    PrintStream toSoc;

    try {
      ServerSocket f = new ServerSocket(9090);
      while (true) {
        Socket t = f.accept();
        BufferedReader fromSoc = new BufferedReader(new InputStreamReader(t.getInputStream()));
        String video = fromSoc.readLine();
        System.out.println(video);
        searcher obj = new searcher();
        boolean fs;
        fs = obj.search(video);
        if (fs == true) {
          System.out.println("stream will starts");
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("stream starts");

        } else {
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("sorry");
        }
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Exemplo n.º 7
0
  public static String getDbConfig(String field) {
    String value = "";
    try {
      File directory = new File(".");
      String path = directory.getCanonicalPath();
      String s = File.separator;
      FileInputStream fstream =
          new FileInputStream(path + s + "src" + s + "config" + s + "dbconfig.cfg");

      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        if (strLine.indexOf("password") >= 0 && field.equals("password") == true) {
          value = strLine.substring(strLine.indexOf('\t') + 1);
          break;
        }

        if (strLine.indexOf("username") >= 0 && field.equals("username") == true) {
          value = strLine.substring(strLine.indexOf('\t') + 1);
        }
      }

    } catch (IOException e) {
      JOptionPane.showMessageDialog(null, e);
    }

    return value;
  }
  public static void main(String[] args) {
    try {
      Driver d = new SimpleDriver();
      conn = d.connect("jdbc:simpledb://localhost", null);

      Reader rdr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(rdr);

      while (true) {
        // process one line of input
        System.out.print("\nSQL> ");
        String cmd = br.readLine().trim();
        System.out.println();
        if (cmd.startsWith("exit")) break;
        else if (cmd.startsWith("select")) doQuery(cmd);
        else doUpdate(cmd);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 9
0
  static void task1() throws FileNotFoundException, IOException, SQLException {
    // Read Input
    System.out.println("Task1 Started...");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    String task1Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(task1Input.split(":")[1].split("=")[1].split("%")[0].trim());
    if (supportPercent >= 0) {
      System.out.println("Task1 Support Percent :" + supportPercent);
      // Prepare query
      String task1Sql =
          "select  temp.iname,(temp.counttrans/temp2.uniquetrans)*100 as percent"
              + " from (select i.itemname iname,count(t.transid) counttrans from trans t, items i"
              + " where i.itemid = t.itemid group by i.itemname having count(t.transid)>=(select count(distinct transid)*"
              + supportPercent / 100
              + " from trans)"
              + ") temp , (select count(distinct transid) uniquetrans from trans) temp2 order by percent";

      PreparedStatement selTask1 = con.prepareStatement(task1Sql);
      ResultSet rsTask1 = selTask1.executeQuery();

      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.1"));
      while (rsTask1.next()) {
        bw.write("{" + rsTask1.getString(1) + "}, s=" + rsTask1.getDouble(2) + "%");
        bw.newLine();
      }
      rsTask1.close();
      bw.close();
      System.out.println("Task1 Completed...\n");
    } else System.out.println("Support percent should be a positive number");
  }
Exemplo n.º 10
0
  public void readStyle(String FileNameParam) throws IOException {

    try {
      BufferedReader myBuf = new BufferedReader(new FileReader(FileNameParam));
      String myLine;
      while ((myLine = myBuf.readLine()) != null) this.MailStyle += myLine;
      myBuf.close();

    } catch (IOException ioe) {
      throw ioe;
    }
  }
Exemplo n.º 11
0
  public void handleInitialCampaignMessage(InitialCampaignMessage campaignMessage) {
    System.out.println(campaignMessage.toString());
    /**
     * ***********************************Open and read the camplog
     * file******************************************************
     */
    String str = null;
    try {
      //  int count = 0;
      FileReader file = new FileReader("camLog.txt");
      BufferedReader reader = new BufferedReader(file);

      str = reader.readLine();

      campaignData.count = Integer.parseInt(str);

    } catch (IOException e) {

    }

    System.out.println("********^^^^^^^^^^^^^^^^^^^^******************" + campaignData.count);

    /**
     * ***********************************end
     * file****************************************************************************
     */
    w.day = 0;

    initialCampaignMessage = campaignMessage;
    demandAgentAddress = campaignMessage.getDemandAgentAddress();
    adxAgentAddress = campaignMessage.getAdxAgentAddress();

    CampaignData campaignData = new CampaignData(initialCampaignMessage);
    campaignData.setBudget(initialCampaignMessage.getBudgetMillis() / 1000.0);
    d.currCampaign = campaignData;
    initTotalPopularity(campaignData);
    genCampaignQueries(campaignData);

    /*
     * The initial campaign is already allocated to our agent so we add it
     * to our allocated-campaigns list.
     */
    System.out.println("Day " + w.day + ": Allocated campaign - " + campaignData);
    d.campaigns.put(initialCampaignMessage.getId(), campaignData);
    for (int i = 0; i < 60; i++) {
      d.campTrack.add(new ArrayList<Integer>());
      d.otherCampTrack.add(new ArrayList<Integer>());
    }
    for (int i = (int) d.currCampaign.dayStart; i <= (int) d.currCampaign.dayEnd; i++) {
      d.campTrack.get(i).add(d.currCampaign.id);
    }
  }
 private static String readFile(String filename) throws IOException {
   //    String lineSep = System.getProperty("\n");
   BufferedReader br = new BufferedReader(new FileReader(filename));
   String nextLine = "";
   StringBuffer sb = new StringBuffer();
   while ((nextLine = br.readLine()) != null) {
     sb.append(nextLine);
     //
     // note:
     //   BufferedReader strips the EOL character.
     //
     //    sb.append(lineSep);
   }
   getLogWriter().fine("***********\n " + sb);
   return sb.toString();
 }
Exemplo n.º 13
0
  private static void readLinkFile(boolean isHighway) {
    System.out.println("read link file...");
    int debug = 0;
    try {
      FileInputStream fstream =
          new FileInputStream(root + "/" + (isHighway ? highwayLinkFile : arterialLinkFile));
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        debug++;
        String[] nodes = strLine.split(";");
        int linkId = Integer.parseInt(nodes[0]);
        String allDir = nodes[1];
        String streetName = nodes[2];
        int funcClass = Integer.parseInt(nodes[3]);
        ArrayList<PairInfo> nodeList = getPairListFromStr(nodes[4]);
        int speedCat = Integer.parseInt(nodes[5]);
        String dirTravel = nodes[6];
        int startNode = Integer.parseInt(nodes[7]);
        int endNode = Integer.parseInt(nodes[8]);

        LinkInfo linkInfo =
            new LinkInfo(
                linkId,
                funcClass,
                streetName,
                startNode,
                endNode,
                nodeList,
                dirTravel,
                speedCat,
                allDir);

        if (isHighway) highwayLinkList.add(linkInfo);
        else arterialLinkList.add(linkInfo);

        if (debug % 100000 == 0) System.out.println("record " + debug + " finish!");
      }
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      System.err.println("Error Code: " + debug);
    }
    System.out.println("read link file finish!");
  }
Exemplo n.º 14
0
  private String shell_exec(String cmdline) {
    String line = "";
    try {

      // windows
      // Process p = Runtime.getRuntime().exec(cmdline);
      // linux
      Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmdline});

      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while ((line += input.readLine()) != null) {}
      input.close();
    } catch (Exception err) {
      err.printStackTrace();
    }
    return line;
  }
Exemplo n.º 15
0
  // Loads a String of text from a specified file.
  // This is generally used to load an email template for automated emailing
  public static String getText(String fileName) {
    try {
      StringBuffer SBreader = new StringBuffer();
      String line;
      FileReader fileReader = new FileReader(findResourceOnFileSystem(fileName));

      BufferedReader buffread = new BufferedReader(fileReader);
      while ((line = buffread.readLine()) != null) {
        SBreader.append(line + "\n");
      }
      line = SBreader.toString();
      fileReader.close();
      buffread.close();
      return line;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String data;

    java.util.logging.Logger log_gsrc = java.util.logging.Logger.getLogger("local-logger");

    BufferedReader bufread2 = null;
    InputStreamReader inread2 = null;

    data = ""; /* init data */

    try {
      inread2 = new InputStreamReader(System.in);
      bufread2 = new BufferedReader(inread2);

      /* FIX: read key from console */
      data = bufread2.readLine();
    } catch (IOException e) {
      log_gsrc.warning("Error reading from console");
    } finally {
      try {
        if (bufread2 != null) {
          bufread2.close();
        }
      } catch (IOException e) {
        log_gsrc.warning("Error closing bufread2");
      } finally {
        try {
          if (inread2 != null) {
            inread2.close();
          }
        } catch (IOException e) {
          log_gsrc.warning("Error closing inread2");
        }
      }
    }

    (new CWE321_Hard_Coded_Cryptographic_Key__basic_51b()).goodG2B_sink(data);
  }
Exemplo n.º 17
0
  public static void main(String args[]) {
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
      PhotoConfig config = new PhotoConfig();
      PhotoSecurity security = new PhotoSecurity();

      String user = null;
      if (args.length < 1) {
        System.out.print("Enter username:  "******"Enter password:  "******"New password is " + newpw);

      Class.forName(config.get("dbDriverName"));
      Connection db =
          DriverManager.getConnection(
              config.get("dbSource"), config.get("dbUser"), config.get("dbPass"));
      String query =
          "update wwwusers set password='******'\n" + "\twhere username='******'";
      Statement st = db.createStatement();
      st.executeUpdate(query);
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
Exemplo n.º 18
0
  public String obtenerServer() {
    String server = "";
    File archivo = null;
    FileReader fr = null;
    BufferedReader br = null;

    try {
      // Apertura del fichero y creacion de BufferedReader para poder
      // hacer una lectura comoda (disponer del metodo readLine()).
      // archivo = new File ("C:\\rpt\\server.txt");
      archivo = new File(objUtils.HostSystem + "server.txt");
      fr = new FileReader(archivo);
      br = new BufferedReader(fr);

      // Lectura del fichero
      String linea;
      while ((linea = br.readLine()) != null) {
        server = linea.toString();
        // System.out.println(server);
      }
      return server;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    } finally {
      // En el finally cerramos el fichero, para asegurarnos
      // que se cierra tanto si todo va bien como si salta
      // una excepcion.
      try {
        if (null != fr) {
          fr.close();
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
  }
Exemplo n.º 19
0
  public static String getHeader(HttpServletRequest request) {
    try {
      FileReader fileReader =
          new FileReader(findResourceOnFileSystem("servletResponseTemplate.htm"));
      BufferedReader buffread = new BufferedReader(fileReader);
      String templateFile = "", line;
      StringBuffer SBreader = new StringBuffer();
      while ((line = buffread.readLine()) != null) {
        SBreader.append(line).append("\n");
      }
      fileReader.close();
      buffread.close();
      templateFile = SBreader.toString();

      String context = getContext(request);

      // process the CSS string
      templateFile =
          templateFile.replaceAll(
              "CSSURL", CommonConfiguration.getCSSURLLocation(request, context));

      // set the top header graphic
      templateFile =
          templateFile.replaceAll(
              "TOPGRAPHIC", CommonConfiguration.getURLToMastheadGraphic(context));

      int end_header = templateFile.indexOf("INSERT_HERE");
      return (templateFile.substring(0, end_header));
    } catch (Exception e) {
      // out.println("I couldn't find the template file to read from.");
      e.printStackTrace();
      String error =
          "<html><body><p>An error occurred while attempting to read from the template file servletResponseTemplate.htm. This probably will not affect the success of the operation you were trying to perform.";
      return error;
    }
  }
Exemplo n.º 20
0
  public static void main(String args[]) {
    try {

      URL url = new URL(args[0]);
      InputStream is = url.openStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));

      String line;
      String buffer = "";
      while ((line = br.readLine()) != null) buffer += line;

      br.close();
      is.close();
      Object[] obj = {buffer};
      HTMLtoXML me = new HTMLtoXML();
      me.invoke(obj);
      obj = me.getOutputValues();
      System.out.println((String) obj[0]);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    return;
  }
Exemplo n.º 21
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    try {
      Socket s = new Socket(hostin, portin);
      InputStream ins = s.getInputStream();
      OutputStream os = s.getOutputStream();
      ir = new BufferedReader(new InputStreamReader(ins));
      pw = new PrintWriter(new OutputStreamWriter(os), true);

      pw.print(nick);
      while (true) {
        String line = ir.readLine();
        jta.append(line + "\n");
        jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum());
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 22
0
  // *****************************************************
  // Process the initial request from Proshop_main
  // *****************************************************
  //
  @SuppressWarnings("deprecation")
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    //
    //  Prevent caching so sessions are not mangled
    //
    resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1
    resp.setDateHeader("Expires", 0); // prevents caching at the proxy server

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    HttpSession session = SystemUtils.verifyPro(req, out); // check for intruder

    if (session == null) {

      return;
    }

    String club = (String) session.getAttribute("club"); // get club name
    String templott = (String) session.getAttribute("lottery"); // get lottery support indicator
    int lottery = Integer.parseInt(templott);

    //
    //  Call is to display the new features page.
    //
    //  Display a page to provide a link to the new feature page
    //
    out.println("<html><head>");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");
    out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">");
    out.println("<title> \"ForeTees Proshop Announcement Page\"</title>");
    //   out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/web utilities/foretees.css\"
    // type=\"text/css\"></link>");
    out.println(
        "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>");
    out.println("</head>");
    out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\">");

    SystemUtils.getProshopSubMenu(req, out, lottery);

    File f;
    FileReader fr;
    BufferedReader br;
    String tmp = "";
    String path = "";

    try {
      path = req.getRealPath("");
      tmp = "/proshop_features.htm"; // "/" +rev+
      f = new File(path + tmp);
      fr = new FileReader(f);
      br = new BufferedReader(fr);
      if (!f.isFile()) {
        // do nothing
      }
    } catch (FileNotFoundException e) {
      out.println("<br><br><p align=center>Missing New Features Page.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    } catch (SecurityException se) {
      out.println("<br><br><p align=center>Access Denied.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    }

    while ((tmp = br.readLine()) != null) out.println(tmp);

    br.close();

    out.println("</BODY></HTML>");
    out.close();
  } // end of doGet
Exemplo n.º 23
0
  public static void main(String args[]) {
    Connection con = null;
    Statement stm = null;
    try {
      int count;
      System.out.println("1...");

      Class.forName("com.timesten.jdbc.TimesTenDriver").newInstance();
      System.out.println("2...");

      con = DriverManager.getConnection("jdbc:timesten:direct:WebNmsDB ", "root", "");
      System.out.println("3...");
      stm = con.createStatement();

      System.out.println("connection established");
      for (int j = 1; j <= 10; j++) {
        System.out.println("enter 1 to add record");
        System.out.println("enter 2 to rem record");
        System.out.println("enter 3 to view all the records");
        System.out.println("enter 4 to view particular record");
        System.out.println("enter 5 to exit");
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(reader);
        String str = br.readLine();
        int i = Integer.parseInt(str);
        String quote = "'";
        ResultSet rs = null;
        switch (i) {
          case 1:
            System.out.println("Enter the name ");
            InputStreamReader reader1 = new InputStreamReader(System.in);
            BufferedReader br1 = new BufferedReader(reader1);
            String str1 = br1.readLine();
            System.out.println("Enter the DOB as YYYY-MM-DD");
            InputStreamReader reader2 = new InputStreamReader(System.in);
            BufferedReader br2 = new BufferedReader(reader2);
            String str2 = br2.readLine();
            System.out.println("Enter the DOJ as YYYY-MM-DD");
            InputStreamReader reader3 = new InputStreamReader(System.in);
            BufferedReader br3 = new BufferedReader(reader3);
            String str3 = br3.readLine();
            System.out.println("Enter the class");
            InputStreamReader reader4 = new InputStreamReader(System.in);
            BufferedReader br4 = new BufferedReader(reader4);
            String str4 = br4.readLine();
            stm.executeUpdate(
                "Insert into student (Name,DOB,DOJ,Class) values("
                    + quote
                    + str1
                    + quote
                    + ","
                    + quote
                    + str2
                    + quote
                    + ","
                    + quote
                    + str2
                    + quote
                    + ","
                    + quote
                    + str4
                    + quote
                    + ");");
            // stm.close();
            break;
          case 2:
            System.out.println("Enter the name whose record to be deleted");
            InputStreamReader reader5 = new InputStreamReader(System.in);
            BufferedReader br5 = new BufferedReader(reader5);
            String str5 = br5.readLine();
            stm.executeUpdate("delete from student where Name=" + quote + str5 + quote + ";");
            break;
          case 3:
            stm.executeQuery("select * from Node;");
            rs = stm.getResultSet();
            System.out.println("Name 		DOB	 		DOJ		 	CLASS");
            while (rs.next() != false) {
              String name = rs.getString("NAME");
              System.out.print(name + "		");
              String dob = rs.getString("ISROUTER");
              System.out.print(dob + "		");
              String doj = rs.getString("OWNERNAME");
              /*System.out.print(doj+"		");
              int Class=rs.getInt("class");
              System.out.println(Class+"	");*/
            }
            break;
          case 4:
            System.out.println("Enter the name whose record to be viewed");
            InputStreamReader reader6 = new InputStreamReader(System.in);
            BufferedReader br6 = new BufferedReader(reader6);
            String str6 = br6.readLine();
            stm.executeQuery("select * from student where Name=" + quote + str6 + quote + ";");
            rs = stm.getResultSet();
            System.out.println("Name 		DOB	 		DOJ		 	CLASS");

            while (rs.next() != false) {
              String name = rs.getString("Name");
              System.out.print(name + "		");
              String dob = rs.getString("DOB");
              System.out.print(dob + "		");
              String doj = rs.getString("DOJ");
              System.out.print(doj + "		");
              int Class = rs.getInt("class");
              System.out.println(Class + "	");
            }
            break;
          case 5:
            System.out.println("Logging out");
            System.exit(0);
        }
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    switch (6) {
      case 6:
        {
          data = "pass";
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        {
          java.util.logging.Logger log_good_source =
              java.util.logging.Logger.getLogger("local-logger");
          BufferedReader bufread2 = null;
          InputStreamReader inread2 = null;
          Properties prop = new Properties();
          IO.writeLine("Enter the password: "******"";
          try {
            inread2 = new InputStreamReader(System.in);
            bufread2 = new BufferedReader(inread2);
            /* FIX: password is read from stdin */
            data = bufread2.readLine();
          } catch (Exception e) {
            log_good_source.warning("Exception in try");
          } finally {
            try {
              if (bufread2 != null) {
                bufread2.close();
              }
            } catch (IOException e) {
              log_good_source.warning("Error closing bufread2");
            } finally {
              try {
                if (inread2 != null) {
                  inread2.close();
                }
              } catch (IOException e) {
                log_good_source.warning("Error closing inread2");
              }
            }
          }
        }
        break;
    }

    java.util.logging.Logger log2 = java.util.logging.Logger.getLogger("local-logger");

    Connection conn2 = null;
    PreparedStatement st = null;
    ResultSet rs2 = null;
    String pw = data;
    try {
      /* POTENTIAL FLAW: use of hard-coded password */
      conn2 = DriverManager.getConnection("data-url", "root", pw);
      st = conn2.prepareStatement("select * from test_table");
      rs2 = st.executeQuery();
    } catch (SQLException e) {
      log2.warning("Error with database connection");
    } finally {
      try {
        if (rs2 != null) {
          rs2.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing rs2");
      } finally {
        try {
          if (st != null) {
            st.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing st");
        } finally {
          try {
            if (conn2 != null) {
              conn2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn2");
          }
        }
      }
    }
  }
Exemplo n.º 25
0
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter webPageOutput = null;
   try {
     webPageOutput = response.getWriter();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "getWriter error : " + error, false, context);
   }
   HttpSession session = request.getSession();
   session.setAttribute("redirect", request.getRequestURL() + "?" + request.getQueryString());
   Connection database = null;
   try {
     database = pool.getConnection(servletName);
   } catch (SQLException error) {
     Routines.writeToLog(servletName, "Unable to connect to database : " + error, false, context);
   }
   if (Routines.loginCheck(true, request, response, database, context)) {
     return;
   }
   String server = context.getInitParameter("server");
   boolean liveSever = false;
   if (server == null) {
     server = "";
   }
   if (server.equals("live")) {
     response.setHeader("Refresh", "60");
   }
   Routines.WriteHTMLHead(
       "View System Log", // title
       false, // showMenu
       13, // menuHighLight
       false, // seasonsMenu
       false, // weeksMenu
       false, // scores
       false, // standings
       false, // gameCenter
       false, // schedules
       false, // previews
       false, // teamCenter
       false, // draft
       database, // database
       request, // request
       response, // response
       webPageOutput, // webPageOutput
       context); // context
   webPageOutput.println("<CENTER>");
   webPageOutput.println(
       "<IMG SRC=\"../Images/Admin.gif\"" + " WIDTH='125' HEIGHT='115' ALT='Admin'>");
   webPageOutput.println("</CENTER>");
   pool.returnConnection(database);
   webPageOutput.println(Routines.spaceLines(1));
   Routines.tableStart(false, webPageOutput);
   Routines.tableHeader("System Log", 0, webPageOutput);
   Routines.tableDataStart(true, false, false, true, true, 0, 0, "scoresrow", webPageOutput);
   boolean firstLine = true;
   int numOfLines = 0;
   try {
     String file = context.getRealPath("/");
     FileReader logFile = new FileReader(file + "/Data/log.txt");
     BufferedReader logFileBuffer = new BufferedReader(logFile);
     boolean endOfFile = false;
     while (!endOfFile) {
       String logFileText = logFileBuffer.readLine();
       if (logFileText == null) {
         endOfFile = true;
       } else {
         if (firstLine) {
           firstLine = false;
         } else {
           webPageOutput.println(Routines.spaceLines(1));
         }
         numOfLines++;
         webPageOutput.println(logFileText);
       }
     }
     logFileBuffer.close();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "Problem with log file : " + error, false, context);
   }
   Routines.tableDataEnd(false, true, true, webPageOutput);
   Routines.tableEnd(webPageOutput);
   if (numOfLines < 20) {
     webPageOutput.println(Routines.spaceLines(20 - numOfLines));
   }
   Routines.WriteHTMLTail(request, response, webPageOutput);
 }
Exemplo n.º 26
0
  public static void main(
      String args[]) { // String args[] ist ein Feld von Stringreferenzen, die beim Programmaufruf
    // erhalten werden k�nnen (siehe auch:
    // http://www.gailer-net.de/tutorials/java/Notes/chap49B/ch49B_9.html)

    boolean fertig = false; // beendet switch-case Anweisung
    String name = "dbsys34"; // Variablen f�r Name und Passwort
    String passwd = "spion!";
    BufferedReader in =
        new BufferedReader(new InputStreamReader(System.in)); // zum Einlesen von Tastatur n�tig
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    String line = null; // Variable f�r Benutzereingabe
    int wahl = 0; // Variable f�r SwitchCase

    // AUSGABE auf die Konsole
    System.out.println(""); // Leerzeile ausgeben
    System.out.println("--- Dies ist Datenbank-Java-Aufgabe ---");
    System.out.println("");

    // --- DIALOG mit Benutzer ---
    /*		try {
        		System.out.print("Benutzername: ");
        		name = in.readLine();					// Einlesen der Eingabe "Benutzername"
    	System.out.print("Passwort: ");
    	passwd = in.readLine();					// Einlesen der Eingabe "Passwort"
    }
    // --- Abfangen des m�glichen Fehlers ---
    catch (IOException e) {
    	System.out.println("Fehler beim Lesen der Eingabe: " + e);
    	System.exit(-1);
      	}*/

    // --- Block f�r Verbindung mit Datenbank ---
    try {
      DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); // Treiber laden
      String url = "jdbc:oracle:thin:@rzdb01.fh-konstanz.de:1521:o9204"; // String f�r DB-Connection
      // (vgl.Skript)
      conn = DriverManager.getConnection(url, name, passwd); // Verbindung erstellen

      conn.setTransactionIsolation(
          conn.TRANSACTION_SERIALIZABLE); // Transaction Isolations-Level setzen: Serialisierbarkeit
      // als Korrektheitskriterium
      conn.setAutoCommit(false); // Kein automatisches Commit nach jedem SQL statement
      System.out.println("... zur Datenbank verbunden!"); // Ausgabe f�r den Benutzer
      conn.setAutoCommit(true); // Automatisches speichern aktivieren
      stmt = conn.createStatement(); // Statement-Objekt erzeugen

      while (!fertig) {
        System.out.println("\nHallo Benutzer! Was wollen Sie tun?");
        System.out.println("1: Kunde einfuegen");
        System.out.println("2: Kunde suchen");
        System.out.println("3: Ferienwohnung einfuegen");
        System.out.println("4: Ferienwohnung suchen");
        System.out.println("5: Ferienwohnung buchen");
        System.out.println("Zum Beenden bitte \"0\" druecken");

        // Einlesen der Benutzerwahl
        try {
          line = in.readLine();
        }
        // Fehler beim Einlesen
        catch (IOException ioe) {
          System.out.println("Fehler beim Lesen der Eingabe: " + ioe);
          fertig = true;
          continue;
        }
        // Konvertierung in int-Wert
        try {
          wahl = Integer.parseInt(line);
        } catch (NumberFormatException nfe) {
          System.out.println("Falsche Eingabe!");
          continue;
        }
        switch (wahl) {
          case 0:
            fertig = true;
            break;

            // {{{ Kunde einfuegen
          case 1:
            String vorname = null,
                nachname = null,
                plz = null,
                stadt = null,
                strasse = null,
                hsnr = null,
                blz = null,
                kontonr = null,
                landcode = null;

            try {
              System.out.println("Bitte Daten des Kunden eingeben.");
              System.out.print("Vorname: ");
              vorname = in.readLine();
              System.out.print("Nachname: ");
              nachname = in.readLine();
              System.out.print("PLZ (max. 5 Stellen): ");
              plz = in.readLine();
              System.out.print("Stadt: ");
              stadt = in.readLine();
              System.out.print("Strasse: ");
              strasse = in.readLine();
              System.out.print("Hausnr.: ");
              hsnr = in.readLine();
              System.out.print("BLZ: ");
              blz = in.readLine();
              System.out.print("Kontonr.: ");
              kontonr = in.readLine();
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO kunde "
                    + "VALUES ( (SELECT MAX(kdnr)+1 FROM kunde), '"
                    + vorname
                    + "', "
                    + "         '"
                    + nachname
                    + "', "
                    + "         "
                    + Integer.parseInt(plz)
                    + ", "
                    + "         '"
                    + stadt
                    + "', "
                    + "         '"
                    + strasse
                    + "', "
                    + "         '"
                    + hsnr
                    + "', "
                    + "         "
                    + Integer.parseInt(blz)
                    + ", "
                    + "         "
                    + Integer.parseInt(kontonr)
                    + ", "
                    + "         '"
                    + landcode
                    + "' )");

            System.out.println("Der Kunde wurde erfolgreich eingefuegt!");

            break;
            // }}}

            // {{{ Kunde suchen
          case 2:
            String suchVorname = null, suchNachname = null;

            try {
              System.out.println("Bitte Namen des zu suchenden Kunden eingeben.");
              System.out.print("Vorname: ");
              suchVorname = in.readLine();
              System.out.print("Nachname: ");
              suchNachname = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // ... und Abfrage senden
            String sSql =
                "SELECT * FROM kunde "
                    + "WHERE vorname LIKE '%"
                    + suchVorname
                    + "%' AND "
                    + "nachname LIKE '%"
                    + suchNachname
                    + "%'";
            rset = stmt.executeQuery(sSql);

            System.out.println("[DEBUG] " + sSql);
            System.out.println("Suchergebnisse: ");
            while (rset.next()) {
              System.out.println(
                  rset.getInt("kdnr")
                      + " "
                      + rset.getString("vorname")
                      + " "
                      + rset.getString("nachname")
                      + " "
                      + rset.getInt("zip")
                      + " "
                      + rset.getString("stadt")
                      + " "
                      + rset.getString("strasse")
                      + " "
                      + rset.getString("hsnr")
                      + " "
                      + rset.getInt("blz")
                      + " "
                      + rset.getInt("kontonr")
                      + " "
                      + rset.getString("landcode"));
              /*
                                          System.out.format("5%d 25%s 25%s 5%d 25%s 25%s 4%s 15%d 15%d 2%s",
                                                            rset.getInt("kdnr"),
                                                            rset.getString("vorname"),
                                                            rset.getString("nachname"),
                                                            rset.getInt("zip"),
                                                            rset.getString("stadt"),
                                                            rset.getString("strasse"),
                                                            rset.getString("hsnr"),
                                                            rset.getInt("blz"),
                                                            rset.getInt("kontonr"),
                                                            rset.getString("landcode"));
              */
            }
            break;
            // }}}

            // {{{ Wohnung einfuegen
          case 3:
            String zimmer = null, groesse = null, preis = null, sauna = null, schwbad = null;
            plz = null;
            landcode = null;

            try {
              System.out.println("Bitte Daten der Wohnung eingeben.");
              System.out.print("Anzahl Zimmer: ");
              zimmer = in.readLine();
              System.out.print("Groesse [qm]: ");
              groesse = in.readLine();
              System.out.print("Preis/Tag [EUR]: ");
              preis = in.readLine();
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
              System.out.print("Sauna? [0 = nein, 1 = ja]: ");
              sauna = in.readLine();
              System.out.print("Schwimmbad? [0 = nein, 1 = ja]: ");
              sauna = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO ferienwohnung "
                    + "VALUES ( (SELECT MAX(fwnr)+1 FROM ferienwohnung), "
                    + "         "
                    + Integer.parseInt(zimmer)
                    + ", "
                    + "         "
                    + Integer.parseInt(groesse)
                    + ", "
                    + "         "
                    + Integer.parseInt(plz)
                    + ", "
                    + "         "
                    + Integer.parseInt(preis)
                    + ", "
                    + "         '"
                    + landcode
                    + "', "
                    + "         "
                    + Integer.parseInt(sauna)
                    + ", "
                    + "         "
                    + Integer.parseInt(schwbad)
                    + ")");

            System.out.println("Die Wohnung wurde erfolgreich eingefuegt!");
            break;
            // }}}

            // {{{ Wohnung suchen
          case 4:
            String datumAnreise = null, datumAbreise = null;
            zimmer = null;

            try {
              System.out.println("Bitte Daten der zu suchenden Wohnung eingeben.");
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
              System.out.print("Anzahl Zimmer: ");
              zimmer = in.readLine();
              System.out.print("Anreisedatum [YYYY-MM-DD]: ");
              datumAnreise = in.readLine();
              System.out.print("Abreisedatum [YYYY-MM-DD]: ");
              datumAbreise = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Abfrage senden
            sSql =
                "SELECT f.* FROM ferienwohnung f "
                    + "LEFT OUTER JOIN buchung b "
                    + "ON ( b.fwnr = f.fwnr ) "
                    + "WHERE "
                    + "("
                    + " (     b.von < TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD') "
                    + "   AND b.bis < TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD') ) "
                    + " OR "
                    + " (     b.von > TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD') "
                    + " AND b.bis > TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD') ) "
                    + " OR "
                    + " ( b.bunr IS NULL ) "
                    + ")"
                    + "AND f.anz_zimmer = "
                    + Integer.parseInt(zimmer);
            rset = stmt.executeQuery(sSql);

            System.out.println("[DEBUG] " + sSql);
            System.out.println("Suchergebnisse: ");
            while (rset.next()) {
              System.out.println(
                  rset.getInt("fwnr")
                      + " "
                      + rset.getString("anz_zimmer")
                      + " "
                      + rset.getString("groesse")
                      + " "
                      + rset.getInt("preis")
                      + " "
                      + rset.getString("landcode")
                      + " "
                      + rset.getString("hat_sauna")
                      + " "
                      + rset.getString("hat_schwb"));
            }
            break;
            // }}}

            // {{{ Wohnung buchen
          case 5:
            String kdnr = null, fwnr = null;
            datumAnreise = null;
            datumAbreise = null;

            try {
              System.out.println("Bitte Daten der Buchung eingeben.");
              System.out.print("Kunden-Nr.: ");
              kdnr = in.readLine();
              System.out.print("Ferienwohnung-Nr.: ");
              fwnr = in.readLine();
              System.out.print("Anreisedatum [YYYY-MM-DD]: ");
              datumAnreise = in.readLine();
              System.out.print("Abreisedatum [YYYY-MM-DD]: ");
              datumAbreise = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Pruefen, ob Kunde/Fw existent?

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO buchung "
                    + "VALUES ( (SELECT MAX(bunr)+1 FROM buchung), "
                    + "         SYSDATE, "
                    + "         TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD'), "
                    + "         TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD'), "
                    + "         "
                    + Integer.parseInt(kdnr)
                    + ", "
                    + "         "
                    + Integer.parseInt(fwnr)
                    + " )");

            System.out.println("Die Buchung wurde erfolgreich eingefuegt!");
            break;
            // }}}
        }
      }
      // Verbindung trennen
      stmt.close();
      conn.close();
    } catch (SQLException se) // Fehler abfangen
    {
      System.out.println("");
      System.out.println(
          "SQL Exception occurred while establishing connection to DBS: " + se.getMessage());
      System.out.println("- SQL state  : " + se.getSQLState());
      System.out.println("- Message    : " + se.getMessage());
      System.out.println("- Vendor code: " + se.getErrorCode());
      System.out.println("");
      System.out.println("EXITING WITH FAILURE ... !!!");
      System.out.println("");
      System.exit(-1);
    }
    System.out.println("");
    System.out.println("PROGRAM FINISHED!!!");
  }
Exemplo n.º 27
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

    // Load config file
    String configFile = null;
    if (args.length > 0) configFile = args[0];

    try {
      if (configFile == null) {
        System.out.println("Database config file not set.");
        return;
      } else properties.load(new FileInputStream(configFile));
    } catch (IOException e) {
      System.out.println("Error opening config file.");
    }

    String url = properties.getProperty("databaseUrl");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String dir = System.getProperty("user.dir"); // Current working directory
    Connection con = null;

    // Try to open file containing javac output
    String output = "";
    try {
      BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt"));

      while (outputReader.ready()) output += outputReader.readLine() + '\n';

      // Close file
      outputReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error opening compilation output file.");
      return;
    } catch (IOException e) {
      System.out.println("I/O Exception Occured.");
      return;
    }

    boolean hasDriver = false;
    // Create class for the driver
    try {
      Class.forName("com.mysql.jdbc.Driver");
      hasDriver = true;
    } catch (Exception e) {
      System.out.println("Failed to load MySQL JDBC driver class.");
    }

    // Create connection to database if the driver was found
    if (hasDriver) {
      try {
        con = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
        System.out.println("Couldn't get connection!");
      }
    }

    // Check that a connection was made
    if (con != null) {
      long userEventId = -1;

      // Store results from the report into the database
      try {
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId
        String userId = rd.readLine(); // Store userId from text file
        rd.close();

        // Insert the report into the table and get the auto_increment id for it
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')");
        ResultSet result = stmt.getGeneratedKeys();
        result.next();
        userEventId = result.getLong(1);

        // Close the statement
        stmt.close();

        // Prepare statement for adding the compilation error to the userEvent
        PreparedStatement compErrorPrepStmt =
            con.prepareStatement(
                "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)");

        // Insert userEventId and docletId into the database
        compErrorPrepStmt.setLong(1, userEventId);
        compErrorPrepStmt.setString(2, output);
        compErrorPrepStmt.executeUpdate();

        // Close the prepare statements
        compErrorPrepStmt.close();
      } catch (Exception e) {
        System.out.println("Exception Occurred");
        System.out.println(e);
      }

      // Store the java files for the report
      try {
        // Prepare statement for storing files
        PreparedStatement filePrepStmt =
            con.prepareStatement(
                "INSERT INTO files(userEventId, filename, contents) VALUES ("
                    + userEventId
                    + ", ?, ?)");

        // Get the list of files from source.txt
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/source.txt")); // Read userId.txt to get userId
        while (rd.ready()) {
          String filename = rd.readLine(); // Store userId from text file
          // Remove the "src/" from the beginning to get the real file name
          String realname = filename.substring(4);
          filePrepStmt.setString(1, realname);

          // Read in the contents of the files
          String contents = "";
          File javaFile = new File(dir + "/" + filename);
          int length = (int) javaFile.length();

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
Exemplo n.º 28
0
  public boolean parserCpYieldTxt(File txtFile) throws Exception {
    FileInputStream fIn = null;
    String fileNameUid = "";
    try {
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM");

      // Using Find Target "|=124" or ",=44" Count
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

      logger.debug(
          "File "
              + txtFile.getAbsolutePath()
              + "  "
              + txtFile.getName()
              + "  "
              + new MimetypesFileTypeMap().getContentType(txtFile));

      // 1.0 讀入檔案, 建立資料流
      fIn = new FileInputStream(txtFile);
      // FileInputStream fIn2 = new FileInputStream(csvFile);
      InputStreamReader isr = null;
      BufferedReader br = null;
      isr = new InputStreamReader(fIn, "UTF-8");
      br = new BufferedReader(isr);

      // byte[] byteArray = new byte[new Long(csvFile.length()).intValue()];
      // 讀入File Data Byte.....
      // fIn2.read(byteArray);
      logger.debug(txtFile.getName() + "<--讀入資料檔...成功");
      // Using get sign  "\n" 抓行數...

      // 1.1 讀入行數資料, 略過行數
      int l = -1;
      List<String> lineDataList = new ArrayList<String>();
      for (int i = 0; i <= l; i++) {
        br.readLine();
      }
      while (br.ready()) {
        String line = br.readLine();
        line = null != line ? line : "";
        // logger.debug(line);
        if (!line.trim().equals("")) {
          lineDataList.add(line);
        }
      }

      // 1.2 確認有資料開使處理
      if (lineDataList != null) {
        CpYieldParserDao cpYieldParserDao = new CpYieldParserDao();

        CpYieldLotTo cpYieldLotTo = new CpYieldLotTo();

        String cpYieldUuid = UUID.randomUUID().toString().toUpperCase();
        logger.debug("lineDataList.size() " + lineDataList.size());

        fileNameUid =
            FilenameUtils.getBaseName(txtFile.getName())
                + "_"
                + cpYieldUuid
                + "."
                + FilenameUtils.getExtension(txtFile.getName());

        File bkFolder =
            new File(fileOutUrl + File.separator + df2.format(calendar.getTime()).toString());

        bkFolder.mkdir();

        File bkFile = new File(bkFolder.getPath().toString() + File.separator + fileNameUid);
        // 1.2.1 處理每行資料
        String tmpWaferID = lineDataList.get(1);
        String arrayWafer[] = tmpWaferID.split("=")[1].trim().split("-");

        // logger.debug("arrayWafer[] " + arrayWafer.length);

        // 1.3 Prepare Data
        String cpLot = arrayWafer[0].trim();
        String waferId = arrayWafer[1].trim();
        String machineId = arrayWafer[2].trim();
        Integer cpTestTimes = cpYieldParserDao.getMaxCpTestTimes(cpLot, waferId);

        String xMaxCoor = lineDataList.get(2).split("=")[1].trim();
        String yMaxCoor = lineDataList.get(3).split("=")[1].trim();
        String flat = lineDataList.get(4).split("=")[1].trim();

        logger.debug("xMaxCoor " + xMaxCoor);
        logger.debug("yMaxCoor " + yMaxCoor);
        logger.debug("flat " + flat);

        // 1.3 Find Bin Data
        int sb = 0, eb = 0;
        for (int i = 0; i < lineDataList.size(); i++) {
          if (lineDataList.get(i).indexOf("Wafer Bin Summary") >= 0) {
            sb = i + 1;
            break;
          }
        }
        for (int i = sb; i < lineDataList.size(); i++) {
          if (lineDataList.get(i).indexOf("bin") < 0) {
            eb = i - 1;
            break;
          }
        }

        logger.debug("sb " + sb);
        logger.debug(lineDataList.get(sb).trim());
        logger.debug("eb " + eb);
        logger.debug(lineDataList.get(eb).trim());
        // 1.3.1 Get Bin Data
        List<CpYieldLotBinTo> cpYieldLotBins = new ArrayList<CpYieldLotBinTo>();
        String cpYieldBinUuid;

        String bin;
        Integer die;
        String percentage;
        String binString;

        for (int j = sb; j <= eb; j++) {
          cpYieldBinUuid = UUID.randomUUID().toString().toUpperCase();
          CpYieldLotBinTo cpYieldLotBinTo = new CpYieldLotBinTo();

          cpYieldLotBinTo.setCpYieldBinUuid(cpYieldBinUuid);
          cpYieldLotBinTo.setCpYieldUuid(cpYieldUuid);

          binString = lineDataList.get(j).trim();
          binString = binString.replaceAll("bin", "").trim();
          // Get Bin
          bin = binString.substring(0, binString.indexOf(" "));
          logger.debug("bin " + bin);
          // Get Die
          bin = binString.substring(0, binString.indexOf(" "));
          binString = binString.replaceAll(bin, "").trim();
          die = Integer.parseInt(binString.substring(0, binString.indexOf(" ")));
          logger.debug("die " + die);
          // Get Percentage
          binString = binString.replaceAll(die.toString(), "").trim();
          percentage = binString.substring(0, binString.length() - 1);
          logger.debug("percentage " + percentage);

          cpYieldLotBinTo.setBin(bin);
          cpYieldLotBinTo.setDie(die);
          cpYieldLotBinTo.setPercentage(percentage);

          cpYieldLotBins.add(cpYieldLotBinTo);
        }

        // 1.4 Die Data
        Integer passDie;
        Integer failDie;
        Integer totelDie;
        for (int i = eb + 1; i < lineDataList.size(); i++) {
          // pass die
          if (lineDataList.get(i).trim().indexOf("pass die") >= 0) {
            passDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("passDie " + passDie);
            cpYieldLotTo.setPassDie(passDie);
            continue;
          }
          // fail die
          if (lineDataList.get(i).trim().indexOf("fail die") >= 0) {
            failDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("failDie " + failDie);
            cpYieldLotTo.setFailDie(failDie);
            continue;
          }
          // totel die
          if (lineDataList.get(i).trim().indexOf("totel die") >= 0) {
            totelDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("totelDie " + totelDie);
            cpYieldLotTo.setTotelDie(totelDie);
            continue;
          }
        }

        // 1.5 Set data in To
        cpYieldLotTo.setCpYieldUuid(cpYieldUuid);
        cpYieldLotTo.setCpTestTimes(cpTestTimes);
        cpYieldLotTo.setCpLot(cpLot);
        cpYieldLotTo.setWaferId(waferId);
        cpYieldLotTo.setMachineId(machineId);
        cpYieldLotTo.setxMaxCoor(xMaxCoor);
        cpYieldLotTo.setyMaxCoor(yMaxCoor);
        cpYieldLotTo.setFlat(flat);

        String fileMimeType = new MimetypesFileTypeMap().getContentType(txtFile);
        cpYieldLotTo.setFileName(
            df2.format(calendar.getTime()).toString() + File.separator + fileNameUid);
        cpYieldLotTo.setFileMimeType(fileMimeType);
        cpYieldLotTo.setFtpFlag("N");

        fIn.close();
        br.close();

        Methods.copyFile(txtFile, bkFile);
        txtFile.delete();
        // 1.6 DataBasse
        // 1.6.1 Insert CP Lot Table
        cpYieldParserDao.insertCpYieldLot(cpYieldLotTo);
        cpYieldParserDao.insertCpYieldLotBin(cpYieldLotBins);
      }

      fIn.close();
      br.close();

      logger.info(txtFile.getName() + " is Parser complete");
      logger.info(fileNameUid + " is Parser complete");

      // logger.debug(tapeList.size());
      logger.info("---------------------------------");
    } catch (Exception e) {
      if (fIn != null) {
        fIn.close();
      }
      logger.info("ERROR MOVE FILE");
      Methods.copyFile(txtFile, new File(fileErrorUrl + "\\" + txtFile.getName()));
      txtFile.delete();

      StackTraceElement[] messages = e.getStackTrace();
      Exception ex = new Exception(txtFile.getName());
      ex.setStackTrace(messages);
      ex.printStackTrace();
      throw ex;
    } finally {
      try {
        if (fIn != null) {
          fIn.close();
        }
      } catch (IOException ie) {
        StackTraceElement[] messages = ie.getStackTrace();
        int length = messages.length;
        String error = "";
        for (int i = 0; i < length; i++) {
          error = error + "toString:" + messages[i].toString() + "\r\n";
        }
        ie.printStackTrace();
        logger.error(error);
        return false;
      }
    }
    return true;
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setHeader("Cache-Control", "nocache");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    StringWriter result = new StringWriter();

    // get received JSON data from request
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String postData = "";
    if (br != null) {
      postData = br.readLine();
    }

    try {
      JSONObject json = (JSONObject) new JSONParser().parse(postData);
      JSONObject resultObj = new JSONObject();
      JSONArray list = new JSONArray();
      List<Tracking> trackingList = new ArrayList<Tracking>();

      // get the website list
      if (json.get("type").equals("websiteslist")) {
        trackingList = trackingDao.websiteList(pool);
        for (Tracking item : trackingList) {
          list.add(item.getWebsite());
        }
      }
      // render report
      else if (json.get("type").equals("submit")) {
        if (json.get("criteria").equals("date")) {
          // render repoty by date
          trackingList = trackingDao.getListByDate(pool, json.get("date").toString());
        } else if (json.get("criteria").equals("daterange")) {
          // render repoty by date range
          trackingList =
              trackingDao.getListByDateRange(
                  pool, json.get("fromdate").toString(), json.get("todate").toString());
        } else if (json.get("criteria").equals("website")) {
          // render repoty by website
          String website = (json.get("website") == null ? "" : json.get("website").toString());
          trackingList = trackingDao.getListByWebsite(pool, website);
        }

        for (Tracking item : trackingList) {
          JSONObject trackingObj = new JSONObject();
          trackingObj.put("date", item.getDate());
          trackingObj.put("website", item.getWebsite());
          trackingObj.put("visit", item.getVisit());
          list.add(trackingObj);
        }
      }
      resultObj.put("result", list);
      resultObj.writeJSONString(result);
      // finally output the json string
      out.print(result.toString());
    } catch (ParseException | SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 30
0
  public static void loadAuthoritiesFromVIAF() {
    if (!connectToDatabase()) {
      return;
    }
    try {
      PreparedStatement addPreferredAuthorStmt =
          authoritiesConn.prepareStatement(
              "INSERT INTO preferred_authors (viafId, originalName, normalizedName, wikipediaLink) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE originalName = VALUES(originalName), normalizedName = VALUES(normalizedName), wikipediaLink = VALUES(wikipediaLink)");
      PreparedStatement addAlternateAuthorStmt =
          authoritiesConn.prepareStatement(
              "INSERT IGNORE alternate_authors (viafId, alternateName) VALUES (?, ?)");

      File viafFile = new File("d:/data/vufind-plus/viaf/viaf-20150115-clusters-rdf.xml");

      // Read data from the file one line at a time since the whole thing is HUGE
      try {
        BufferedReader reader = new BufferedReader(new FileReader(viafFile));

        // Setup the XML processor
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression viafIdExpression = xpath.compile("RDF/Description");
        XPathExpression conceptsExpression = xpath.compile("RDF/Concept");

        String curLine = reader.readLine();
        while (curLine != null) {
          if (!curLine.startsWith("<")) {
            curLine = curLine.substring(curLine.indexOf('<'));
          }
          // Get XMl for the line
          Document doc = dBuilder.parse(new InputSource(new StringReader(curLine)));

          // Load VIAF ID, Preferred authority, and alternate labels, also wikipedia article?
          Element viafIdNode = (Element) viafIdExpression.evaluate(doc, XPathConstants.NODE);
          String viafIdStr = viafIdNode.getAttribute("rdf:about");
          viafIdStr = viafIdStr.replace("http://viaf.org/viaf/", "");
          Long viafId = Long.parseLong(viafIdStr);
          NodeList concepts = (NodeList) conceptsExpression.evaluate(doc, XPathConstants.NODESET);
          HashSet<String> altLabels = new HashSet<String>();
          String preferredLabel = null;
          String wikipediaLink = null;
          // Scan through the concepts to get the Library of Congress Concept
          for (int i = 0; i < concepts.getLength(); i++) {
            Node curConcept = concepts.item(i);

            boolean isPreferredConcept = false;
            String preferredConceptLabel = null;
            HashSet<String> altLabelsForConcept = new HashSet<String>();
            // Get the scheme for the concept
            NodeList conceptInfoNodes = curConcept.getChildNodes();
            for (int j = 0; j < conceptInfoNodes.getLength(); j++) {
              Element conceptInfoNode = (Element) conceptInfoNodes.item(j);
              if (conceptInfoNode.getTagName().equals("skos:inScheme")) {
                String schemeName = conceptInfoNode.getAttribute("rdf:resource");
                if (schemeName.equals("http://viaf.org/authorityScheme/LC")) {
                  isPreferredConcept = true;
                }
              } else if (conceptInfoNode.getTagName().equals("skos:prefLabel")) {
                preferredConceptLabel = conceptInfoNode.getTextContent();
              } else if (conceptInfoNode.getTagName().equals("skos:altLabel")) {
                altLabelsForConcept.add(conceptInfoNode.getTextContent());
              } else if (conceptInfoNode.getTagName().equals("foaf:isPrimaryTopicOf")) {
                if (conceptInfoNode.hasAttribute("rdf:resource")
                    && conceptInfoNode
                        .getAttribute("rdf:resource")
                        .startsWith("http://en.wikipedia.org")) {
                  wikipediaLink = conceptInfoNode.getAttribute("rdf:resource");
                }
              }
            }

            if (isPreferredConcept) {
              preferredLabel = preferredConceptLabel;
              altLabels = altLabelsForConcept;
              break;
            }
          }

          if (preferredLabel != null) {
            String normalizedName = AuthorNormalizer.getNormalizedName(preferredLabel);
            if (normalizedName.length() > 50) {
              logger.warn("Normalized author longer than 50 characters " + normalizedName);
              normalizedName = normalizedName.substring(0, 50);
            }
            if (preferredLabel.length() > 200) {
              logger.warn("Author longer than 200 characters " + preferredLabel);
              preferredLabel = preferredLabel.substring(0, 200);
            }

            addPreferredAuthorStmt.setLong(1, viafId);
            addPreferredAuthorStmt.setString(2, preferredLabel);
            addPreferredAuthorStmt.setString(3, normalizedName);
            addPreferredAuthorStmt.setString(4, wikipediaLink);
            addPreferredAuthorStmt.executeUpdate();

            // To make lookups faster, we will want to put alternate labels as first name last name
            // in addition to
            // last name, first name
            for (String curAltName : altLabels) {
              // Add the normalized author name for improved performance doing lookups
              String normalizedAltAuthor = AuthorNormalizer.getNormalizedName(curAltName);
              if (normalizedAltAuthor.length() > 200) {
                logger.warn(
                    "Normalized alternate author longer than 200 characters " + preferredLabel);
                normalizedAltAuthor = normalizedAltAuthor.substring(0, 200);
              }
              addAlternateAuthorStmt.setLong(1, viafId);
              addAlternateAuthorStmt.setString(2, normalizedAltAuthor);
              addAlternateAuthorStmt.executeUpdate();

              // See if we need to reverse the author name to first name / last name
              String reversedName = AuthorNormalizer.getDisplayName(curAltName);
              if (reversedName != null) {
                String normalizedReversedName = AuthorNormalizer.getNormalizedName(reversedName);
                if (normalizedReversedName.length() > 200) {
                  logger.warn(
                      "Normalized reversed alternate author longer than 200 characters "
                          + preferredLabel);
                  normalizedReversedName = normalizedReversedName.substring(0, 200);
                }
                addAlternateAuthorStmt.setLong(1, viafId);
                addAlternateAuthorStmt.setString(2, normalizedReversedName);
                addAlternateAuthorStmt.executeUpdate();
              }
            }

            // TODO: optionally load related works from see also?
          } else {
            // logger.warn("No preferred Label found for cluster " + viafIdStr);
          }

          // Get the next line
          curLine = reader.readLine();
        }
      } catch (Exception e) {
        logger.error("Error loading authorities from VIAF", e);
      }
    } catch (SQLException e) {
      logger.error("Unable to connect to database", e);
    }
    if (authoritiesConn != null) {
      return;
    }
  }