Пример #1
1
 public String getONT() {
   Connection con;
   String ontid = null;
   String JsonStr = "{\"ont\": [";
   try {
     con = DataSource.getConnection();
     PreparedStatement pst = con.prepareStatement("select ont_id from ont");
     ResultSet rs = pst.executeQuery();
     int flag = 1;
     while (rs.next()) {
       flag = 0;
       ontid = rs.getString("ont_id");
       JsonStr += "{\"ont_id\":\"" + ontid + "\"},";
     }
     if (flag == 1) {
       JsonStr += ",";
     }
     int len = JsonStr.length();
     JsonStr = JsonStr.substring(0, len - 1);
     JsonStr += "],";
   } catch (SQLException | ClassNotFoundException e) {
     System.out.println("error connection to the database getponids" + e.getMessage());
     return "";
   }
   System.out.println(JsonStr);
   DataSource.returnConnection(con);
   return JsonStr;
 }
Пример #2
0
 public ArrayList<String> getFreguesiasByConcelho(String c, String el) {
   ArrayList<String> toRet = new ArrayList<>();
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps =
         conn.prepareStatement(
             "SELECT  freguesia FROM `assembleia de voto` where concelho = '"
                 + c
                 + "' and eleicao = '"
                 + el
                 + "';");
     ResultSet rs = ps.executeQuery();
     for (; rs.next(); ) {
       toRet.add(rs.getString("freguesia"));
     }
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
       return null;
     }
   }
   return toRet;
 }
 public QueryManager() {
   try {
     connector = new PostgisConnector();
     statement = connector.getStatement();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   }
 }
Пример #4
0
 public DBWorker() {
   try {
     Class.forName("com.mysql.jdbc.Driver");
     connection = DriverManager.getConnection(HOST, USERNAME, PASSWORD);
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   }
 }
Пример #5
0
 public void putTemplate(
     String codigo,
     String eleicao,
     String concelho,
     String freguesia,
     String habertura,
     String hencerramento,
     String local) {
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps =
         conn.prepareStatement(
             "DELETE FROM `assembleia de voto` WHERE codigo='"
                 + codigo
                 + "' AND eleicao ='"
                 + eleicao
                 + "'");
     ps.executeUpdate();
     String q =
         "INSERT INTO `assembleia de voto` VALUES ('"
             + codigo
             + "','"
             + eleicao
             + "','"
             + concelho
             + "','"
             + freguesia
             + "','"
             + habertura
             + "','"
             + hencerramento
             + "','"
             + local
             + "','"
             + 0
             + "','"
             + 0
             + "','"
             + 0
             + "','"
             + 0
             + "','"
             + 0
             + "');";
     PreparedStatement sql = conn.prepareStatement(q);
     sql.executeUpdate();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  public JSONObject getManufacturers() {

    JSONObject result = new JSONObject();

    Connection dbConnection = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");

      dbConnection =
          DriverManager.getConnection(PathNames.DB_URL, PathNames.USERNAME, PathNames.PASSWORD);

      String query =
          "SELECT * FROM "
              + PathNames.DB_MANUFACTURER_CATEGORIES
              + " cats, "
              + PathNames.DB_MANUFACTURERS
              + " mans WHERE cats.category_key='"
              + catkey
              + "' AND mans.manufacturer_id=cats.manufacturer_id";

      System.out.println(query);
      // Execute a query
      Statement statement = dbConnection.createStatement();

      ResultSet rs = statement.executeQuery(query);

      JSONArray typeList = new JSONArray();

      while (rs.next()) {
        JSONObject curr = new JSONObject();
        curr.put("catkey", rs.getString("category_key"));
        curr.put("manufacturer_id", rs.getString("manufacturer_id"));
        curr.put("manufacturer", rs.getString("manufacturer"));
        curr.put("image", rs.getString("image_name"));
        typeList.add(curr);
      }

      result.put("manufacturers", typeList);
      manufacturers = result;

    } catch (SQLException | ClassNotFoundException ex) {
      ex.printStackTrace();
    } finally {
      try {
        dbConnection.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return result;
  }
Пример #7
0
 private void connect() {
   try {
     Class.forName("com.mysql.jdbc.Driver");
     conn = DriverManager.getConnection(databaseURL, username, password.toString());
     // conn = DriverManager.getConnection(tempURL);
     conn.setAutoCommit(false);
   } catch (SQLException | ClassNotFoundException e) {
     System.out.println("error connecting to SQL Database");
     e.printStackTrace();
   }
 }
Пример #8
0
  public static void getTable(PrintWriter out) {

    out.println("<!DOCTYPE html>");
    out.println("<html lang=\"en\">");
    out.println("<head>");
    out.println(
        "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" integrity=\"sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==\"crossorigin=\"anonymous\">");
    out.println("</head><body>");
    out.println(
        "<table class=\"table table-hover\"><thead style = \"color:#4C1818\"><tr><th>Assignment</th><th>Grade</th></tr></thead><tbody>");
    try {
      // URL of Oracle database server
      String url = "jdbc:oracle:thin:system/password@localhost";
      Class.forName("oracle.jdbc.driver.OracleDriver");

      // properties for creating connection to Oracle database
      Properties props = new Properties();
      props.setProperty("user", "testuserdb");
      props.setProperty("password", "password");

      // creating connection to Oracle database using JDBC
      Connection conn = DriverManager.getConnection(url, props);

      String sql = "Select * from Gradebook";

      // creating PreparedStatement object to execute query
      PreparedStatement preStatement = conn.prepareStatement(sql);

      ResultSet result = preStatement.executeQuery();
      // System.out.printf("%15s %15s", "First Name", "Last Name");
      // System.out.println();
      while (result.next()) {

        assignmentname = result.getString("ASSIGNMENT");
        assignmentgrade = result.getString("GRADE");

        out.println("<tr><td>" + assignmentname + "</td>");
        out.println("<td>" + assignmentgrade + "</td></tr>");
      }
      conn.close();
    } catch (SQLException | ClassNotFoundException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }

    out.println(
        "<br><br><form action = \"ShowAverage\" method \"POST\"><button type=\"Show Average\" class=\"btn btn-primary btn-sm\">Show Average</button></form>");
    out.println(
        "<script> src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>");
    out.println(
        "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\" integrity=\"sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==\" crossorigin=\"anonymous\"></script>");
    out.println("</body></html>");
  }
Пример #9
0
 public void updateOntStatus(String ontid, String status) {
   Connection con = null;
   try {
     con = DataSource.getConnection();
     PreparedStatement pst = con.prepareStatement("update ont set status=? where ont_id=?");
     pst.setString(1, status);
     pst.setString(2, ontid);
     pst.executeUpdate();
     pst.close();
   } catch (SQLException | ClassNotFoundException e) {
     System.out.println("in update ONT status" + e.getMessage());
   }
   DataSource.returnConnection(con);
 }
Пример #10
0
  /** hace la conexion */
  public static void performConnection() {
    String host = "localhost";
    String user = "******";
    String pass = "******";
    String dtbs = "polla2";

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String newConnectionURL =
          "jdbc:mysql://" + host + "/" + dtbs + "?" + "user="******"&password=" + pass;
      con = DriverManager.getConnection(newConnectionURL);
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #11
0
  /**
   * Retorna um objeto Connection relacionado ao database selecionado.
   *
   * @return Um objeto Connection se conseguiu criar a conexão
   * @throws RuntimeException caso ocorra algum erro
   */
  public static Connection getConnetion() {
    try {
      if (!setted) {
        Class.forName("org.postgresql.Driver");
        stdConnection =
            DriverManager.getConnection("jdbc:postgresql://localhost/testejee", "baby", "123456");
        setted = true;
      }
      return stdConnection;
    } catch (SQLException | ClassNotFoundException e) {
      log.error("Erro ao criar conexão com o banco de dados! MSG: " + e.getMessage());

      throw new RuntimeException(e);
    }
  }
Пример #12
0
 public void clear() {
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps = conn.prepareStatement("DELETE FROM `Assembleia de Voto`");
     ps.executeUpdate();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
       conn = null;
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
 }
Пример #13
0
  public static void updateTable() {
    try {
      // URL of Oracle database server
      String url = "jdbc:oracle:thin:system/password@localhost";
      Class.forName("oracle.jdbc.driver.OracleDriver");

      // properties for creating connection to Oracle database
      Properties props = new Properties();
      props.setProperty("user", "testuserdb");
      props.setProperty("password", "password");

      // creating connection to Oracle database using JDBC
      Connection conn = DriverManager.getConnection(url, props);

      String sql =
          "Insert into GRADEBOOK (ENTRY,ASSIGNMENT,GRADE) values (seq_entry.nextval"
              + ",'"
              + assign
              + "',"
              + grade
              + ")";

      // creating PreparedStatement object to execute query
      PreparedStatement preStatement = conn.prepareStatement(sql);

      ResultSet result = preStatement.executeQuery();
      // System.out.printf("%15s %15s", "First Name", "Last Name");
      // System.out.println();
      //	        while(result.next()){
      //
      //	        	CustId = result.getString("CUSTOMER_ID");
      //	        	name = result.getString("CUST_FIRST_NAME");
      //	            Lname=result.getString("CUST_LAST_NAME");
      ////	            out.println(name);
      ////	            out.println(Lname);
      //	            name = name + " " + Lname;
      //	            out.println("<tr><td><a href=\"Details?CustId=" + CustId + "\">" + name +
      // "</a></td></tr>");
      //
      //	        }
      conn.close();
    } catch (SQLException | ClassNotFoundException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
Пример #14
0
 public boolean isEmpty() {
   boolean b = false;
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps = conn.prepareStatement("SELECT * FROM `assembleia de voto`");
     ResultSet rs = ps.executeQuery();
     b = !rs.next();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return b;
 }
Пример #15
0
 public Boolean identify() throws IOException, SQLException {
   Boolean result = false;
   try {
     resultSet =
         hBaseSQLManager.executeSqlGetString(
             "SELECT MD5_ID FROM VISITOR WHERE MD5_ID ='" + getMd5Id() + "'");
     if (resultSet.next()) result = true;
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     if (hBaseSQLManager.statement != null)
       try {
         hBaseSQLManager.statement.close();
       } catch (SQLException e) {
         e.printStackTrace();
       }
   }
   return result;
 }
Пример #16
0
 public boolean containsKey(Object key) throws NullPointerException {
   boolean c = false;
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps =
         conn.prepareStatement(
             "Select codigo from `equipas` where codigo = '" + (String) key + "'");
     ResultSet rs = ps.executeQuery();
     c = rs.next();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return c;
 }
Пример #17
0
 public int size() {
   int i = -1;
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps = conn.prepareStatement("Select count(AV_id) from `assembleia de voto`");
     ResultSet rs = ps.executeQuery();
     if (rs.next()) {
       i = rs.getInt(1);
     }
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return i;
 }
Пример #18
0
 /** controls behaver for save button */
 public void onSave() {
   try {
     dbCon = DBController.getInstance();
     dbCon.insertInto(
         "Survey_Template",
         DBController.appendApo(createSurvey.getSurveyName()),
         DBController.appendApo(this.getTemplateName()));
     createSurvey
         .getSurveyPrevModel()
         .getData(
             "Survey_Template",
             "Survey = " + DBController.appendApo(createSurvey.getSurveyName()),
             1,
             "Survey",
             "Template");
     createSurvey.getSurveyTemplateListModel().getData();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   }
 }
Пример #19
0
  public Set<String> keySet() {
    Set<String> res = new HashSet<String>();

    try {
      conn = SqlConnect.connect();
      PreparedStatement ps = conn.prepareStatement("SELECT codigo FROM `assembleia de voto`");
      ResultSet rs = ps.executeQuery();
      for (; rs.next(); ) {
        res.add(rs.getString("Codigo"));
      }
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return res;
  }
Пример #20
0
 public void remove(String cod, String el) {
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps =
         conn.prepareStatement(
             "DELETE FROM `assembleia de voto` WHERE codigo =' "
                 + cod
                 + "' AND eleicao='"
                 + el
                 + "'");
     ps.executeUpdate();
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Пример #21
0
  public static void main(String[] args) {

    Connection connection = null;
    try {
      // Register the driver
      Class.forName("org.postgresql.Driver");
      // Make the connection
      connection =
          DriverManager.getConnection(
              "jdbc:postgresql://cmps180-db.lt.ucsc.edu/ssmcgrat", "ssmcgrat", "calculated33XML");

      StoreApplication app = new StoreApplication();
      List<String> phoneNumbers =
          app.getCustomerPhoneFromFirstLastName(connection, "John", "Smith");

      /** ********** Print the phone numbers here: *************** */
      List<String> filmTitles = app.getFilmTitlesBasedOnLengthRange(connection, 60, 120);

      /** *********** Print the film titles here: **************** */
      int count = app.countCustomersInDistrict(connection, "Buenos Aires", false);

      /** ********** Print the customer count here: ************* */

      // add a film to the database
      app.insertFilmIntoInventory(connection, "Sequel to the Prequel", "Memorable", 98, "PG-13");
    } catch (SQLException | ClassNotFoundException e) {
      System.out.println("Error while connecting to database: " + e);
      e.printStackTrace();
    } finally {
      if (connection != null) {
        // Closing Connection
        try {
          connection.close();
        } catch (SQLException e) {
          System.out.println("Failed to close connection: " + e);
          e.printStackTrace();
        }
      }
    }
  }
Пример #22
0
 public ArrayList<String> getAssembleiasDeVoto(String eleicao) throws SQLException {
   ArrayList<String> res = new ArrayList<String>();
   try {
     conn = SqlConnect.connect();
     PreparedStatement ps =
         conn.prepareStatement(
             "Select codigo from `assembleia de voto` where eleicao ='" + eleicao + "'");
     ResultSet rs = ps.executeQuery();
     for (; rs.next(); ) {
       res.add(rs.getString("codigo"));
     }
   } catch (SQLException | ClassNotFoundException e) {
     e.printStackTrace();
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return res;
 }
Пример #23
0
  @Override
  public synchronized Account newAccount(String name) throws RemoteException, RejectedException {
    AccountImpl account = (AccountImpl) accounts.get(name);
    if (account != null) {
      System.out.println("Account [" + name + "] exists!!!");
      throw new RejectedException(
          "Rejected: Bank:  Account for: " + name + " already exists: " + account);
    }
    ResultSet result = null;
    try {
      findAccountStatement.setString(1, name);
      result = findAccountStatement.executeQuery();

      if (result.next()) {
        // account exists, instantiate, put in cache and throw exception.
        account = new AccountImpl(name, result.getFloat("balance"), getConnection());
        accounts.put(name, account);
        throw new RejectedException("Rejected: Account for: " + name + " already exists");
      }
      result.close();

      // create account.
      createAccountStatement.setString(1, name);
      int rows = createAccountStatement.executeUpdate();
      if (rows == 1) {
        account = new AccountImpl(name, getConnection());
        accounts.put(name, account);
        System.out.println("Bank: Account: " + account + " has been created for " + name);
        return account;
      } else {
        throw new RejectedException("Cannot create an account for " + name);
      }
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
      throw new RejectedException("Cannot create an account for " + name, e);
    }
  }
Пример #24
0
  public static void main(String[] args) {
    try {
      Connection connection = BddConnection.getConnection();
      String sql = "INSERT INTO Producto VALUES (?,?,?,?,?,?)";
      PreparedStatement statement = connection.prepareStatement(sql);
      File img = new File("imgPrueba.jpg");
      FileInputStream in = new FileInputStream(img);
      // ID
      statement.setString(1, "1");
      // Stock
      statement.setInt(2, 111);
      // Web clob
      statement.setString(3, "www.clob.com");
      // Image blob
      statement.setBinaryStream(4, in, img.length());
      statement.execute();
      System.out.println("Insercion realizada");

    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #25
0
  /*
   * (non-Javadoc)
   * @see de.zbit.Launcher#commandLineMode(de.zbit.AppConf)
   */
  @Override
  public void commandLineMode(AppConf appConf) {
    SBProperties args = appConf.getCmdArgs();
    if (args.containsKey(LogOptions.LOG_FILE)) {
      LogUtil.addHandler(
          new ConsoleHandler() {

            /** Formatter */
            OneLineFormatter formatter = new OneLineFormatter(false, false, false);

            /*
             * (non-Javadoc)
             * @see java.util.logging.StreamHandler#flush()
             */
            @Override
            public synchronized void flush() {
              System.out.flush();
            }

            /*
             * (non-Javadoc)
             * @see
             * java.util.logging.ConsoleHandler#publish(java.util.logging.LogRecord)
             */
            @Override
            public void publish(LogRecord record) {
              if (record.getLevel().intValue() == Level.INFO.intValue()) {
                try {
                  String message = formatter.format(record);
                  System.out.write(message.getBytes());
                } catch (IOException exc) {
                  reportError(null, exc, ErrorManager.FORMAT_FAILURE);
                  return;
                }
              }
            }
          },
          getLogPackages());
    }
    BiGGDB bigg = null;
    Parameters parameters = new Parameters();
    parameters.annotateWithBiGG = args.getBooleanProperty(ModelPolisherOptions.ANNOTATE_WITH_BIGG);
    if (parameters.annotateWithBiGG) {
      try {
        // Connect to database and launch application:
        String passwd = args.getProperty(DBOptions.PASSWD);
        bigg =
            new BiGGDB(
                new PostgreSQLConnector(
                    args.getProperty(DBOptions.HOST),
                    args.getIntProperty(DBOptions.PORT),
                    args.getProperty(DBOptions.USER),
                    passwd != null ? passwd : "",
                    args.getProperty(DBOptions.DBNAME)));
      } catch (SQLException | ClassNotFoundException exc) {
        exc.printStackTrace();
      }
    }
    // Gives users the choice to pass an alternative model notes XHTML file to
    // the program.
    File modelNotesFile = parseFileOption(args, ModelPolisherOptions.MODEL_NOTES_FILE);
    File documentNotesFile = parseFileOption(args, ModelPolisherOptions.DOCUMENT_NOTES_FILE);
    String documentTitlePattern = null;
    if (args.containsKey(ModelPolisherOptions.DOCUMENT_TITLE_PATTERN)) {
      documentTitlePattern = args.getProperty(ModelPolisherOptions.DOCUMENT_TITLE_PATTERN);
    }
    double[] coefficients = null;
    if (args.containsKey(ModelPolisherOptions.FLUX_COEFFICIENTS)) {
      String c = args.getProperty(ModelPolisherOptions.FLUX_COEFFICIENTS);
      String coeff[] = c.substring(1, c.length() - 1).split(",");
      coefficients = new double[coeff.length];
      for (int i = 0; i < coeff.length; i++) {
        coefficients[i] = Double.parseDouble(coeff[i].trim());
      }
    }
    String fObj[] = null;
    if (args.containsKey(ModelPolisherOptions.FLUX_OBJECTIVES)) {
      String fObjectives = args.getProperty(ModelPolisherOptions.FLUX_OBJECTIVES);
      fObj = fObjectives.substring(1, fObjectives.length() - 1).split(":");
    }
    parameters.includeAnyURI = args.getBooleanProperty(ModelPolisherOptions.INCLUDE_ANY_URI);
    parameters.checkMassBalance = args.getBooleanProperty(ModelPolisherOptions.CHECK_MASS_BALANCE);
    parameters.compression =
        ModelPolisherOptions.Compression.valueOf(
            args.getProperty(ModelPolisherOptions.COMPRESSION_TYPE));
    parameters.documentNotesFile = documentNotesFile;
    parameters.documentTitlePattern = documentTitlePattern;
    parameters.fluxCoefficients = coefficients;
    parameters.fluxObjectives = fObj;
    parameters.modelNotesFile = modelNotesFile;
    parameters.omitGenericTerms = args.getBooleanProperty(ModelPolisherOptions.OMIT_GENERIC_TERMS);
    parameters.sbmlValidation = args.getBooleanProperty(ModelPolisherOptions.SBML_VALIDATION);
    // run polishing operations in background and parallel.
    try {
      batchProcess(
          bigg,
          new File(args.getProperty(IOOptions.INPUT)),
          new File(args.getProperty(IOOptions.OUTPUT)),
          parameters);
    } catch (SBMLException | XMLStreamException | IOException exc) {
      exc.printStackTrace();
    }
  }
Пример #26
0
  /**
   * Method which saves visitor. There are listed 4 cases: 1. Visitor's cookiesId & cookiesData are
   * equal to visitor's MD5_ID & MD5_DATA into HBase. 2. Visitor's cookiesId are equal to MD5_ID
   * from HBase, but DATA is not equal. The we update visitor. 3. Visitor's cookies does not have
   * cookiesId or cookiesData. If visitor's md5Data is found into HBase, then we assign visitor to
   * existing one. 4. Visitor's cookies does not have cookiesId or cookiesData. Create new visitor
   * if nothing similar found into Hbase.
   */
  @Override
  public void save() {
    // JSONObject response = new JSONObject();
    String cookiesId = getMd5Id();
    String cookiesData = getMd5Data();
    String md5IdSearch = "";
    String md5DataSearch = "";
    int visitorId = 0;

    // CASE: WHEN THERE ARE COOKIES BUT THERE ARE NO USER IN DB!!!

    /** This if checks if visitor has cookies. */
    if (!cookiesId.equals("")) {
      try {
        resultSet =
            hBaseSQLManager.executeSqlGetString(
                "SELECT * FROM VISITOR WHERE MD5_ID ='" + cookiesId + "'");
        if (resultSet.next()) {
          md5IdSearch = resultSet.getString("MD5_ID");
          md5DataSearch = resultSet.getString("MD5_DATA");
          visitorId = resultSet.getInt("ID");
        }
      } catch (SQLException | ClassNotFoundException e) {
        e.printStackTrace();
      } finally {
        if (hBaseSQLManager.statement != null)
          try {
            hBaseSQLManager.statement.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
      }
      if (cookiesId.equals(md5IdSearch)) {
        if (cookiesData.equals(md5DataSearch)) {
        } else {
          /* Seems user changed something. We'll update visitor. OK */
          try {
            hBaseSQLManager.executeSqlGetIdOnUpdate(
                "UPSERT INTO VISITOR(ID, USER_AGENT, HEADERS, "
                    + "TIMEZONE, SCREEN, ENABLED_COOKIES, PLUGINS, FONTS, MD5_ID, MD5_DATA) "
                    + "VALUES("
                    + visitorId
                    + ", '"
                    + getUserAgent()
                    + "', '"
                    + getHeaders()
                    + "', "
                    + getTimezone()
                    + ", '"
                    + getScreen()
                    + "', '"
                    + isEnabledCookies()
                    + "'"
                    + ", '"
                    + getPlugins()
                    + "', '"
                    + getFonts()
                    + "', '"
                    + getMd5Id()
                    + "', '"
                    + getMd5Data()
                    + "')");
          } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
          } finally {
            if (hBaseSQLManager.statement != null)
              try {
                hBaseSQLManager.statement.close();
              } catch (SQLException e) {
                e.printStackTrace();
              }
          }
        }
      }
    }

    /** This if checks if visitor does not have cookies. */
    if (cookiesId.equals("")) {
      String md5id = "";
      try {
        resultSet =
            hBaseSQLManager.executeSqlGetString(
                "SELECT MD5_DATA FROM VISITOR WHERE MD5_DATA = '" + getMd5Data() + "'");
        if (resultSet.next()) md5DataSearch = resultSet.getString("MD5_DATA");
      } catch (SQLException | ClassNotFoundException e) {
        e.printStackTrace();
      } finally {
        if (hBaseSQLManager.statement != null)
          try {
            hBaseSQLManager.statement.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
      }
      if (md5DataSearch.equals(getMd5Data())) {
        try {
          resultSet =
              hBaseSQLManager.executeSqlGetString(
                  "SELECT MD5_ID FROM VISITOR WHERE MD5_DATA = '" + md5DataSearch + "'");
          if (resultSet.next()) md5id = resultSet.getString("MD5_ID");
        } catch (SQLException | ClassNotFoundException e) {
          e.printStackTrace();
        } finally {
          if (hBaseSQLManager.statement != null)
            try {
              hBaseSQLManager.statement.close();
            } catch (SQLException e) {
              e.printStackTrace();
            }
        }
        setMd5Id(md5id);

      } else {
        try {
          hBaseSQLManager.executeSqlGetIdOnUpdate(
              "UPSERT INTO VISITOR(ID, USER_AGENT, TIMEZONE, HEADERS, SCREEN, ENABLED_COOKIES, PLUGINS,"
                  + " FONTS, MD5_DATA) "
                  + "VALUES(NEXT VALUE FOR VISITOR.VISITOR_SEQUENCE, '"
                  + getUserAgent()
                  + "', "
                  + getTimezone()
                  + ", '"
                  + getHeaders()
                  + "', '"
                  + getScreen()
                  + "', '"
                  + isEnabledCookies()
                  + "'"
                  + ", '"
                  + getPlugins()
                  + "', '"
                  + getFonts()
                  + "', '"
                  + getMd5Data()
                  + "')");
          try {
            resultSet =
                hBaseSQLManager.executeSqlGetString(
                    "SELECT ID FROM VISITOR WHERE MD5_DATA = '" + getMd5Data() + "'");
            if (resultSet.next()) visitorId = resultSet.getInt("ID");
          } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
          } finally {
            if (hBaseSQLManager.statement != null) hBaseSQLManager.statement.close();
          }
          md5id = createMD5(Integer.toString(visitorId));
          setMd5Id(md5id);
          hBaseSQLManager.executeSqlGetIdOnUpdate(
              "UPSERT INTO VISITOR(ID, MD5_ID) VALUES(" + visitorId + ", '" + getMd5Id() + "')");
        } catch (SQLException | ClassNotFoundException e) {
          e.printStackTrace();
        } finally {
          if (hBaseSQLManager.statement != null)
            try {
              hBaseSQLManager.statement.close();
            } catch (SQLException e) {
              e.printStackTrace();
            }
        }
      }
    }

    try {
      try {
        hBaseSQLManager.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #27
0
  public AssembleiaDeVoto put(String key, AssembleiaDeVoto value) {
    try {
      conn = SqlConnect.connect();
      String s =
          "Replace INTO `assembleia de voto` VALUES ('"
              + key
              + "','"
              + value.getEleicao()
              + "','"
              + value.getConcelho()
              + "','"
              + value.getFreguesia()
              + "','"
              + value.getHabertura()
              + "','"
              + value.getHencerramento()
              + "','"
              + value.getLocal()
              + "','"
              + value.getNrEleitores()
              + "','"
              + value.getNrVotantes()
              + "','"
              + value.getVotosBrancos()
              + "','"
              + value.getVotosNulos()
              + "','"
              + value.getNrReclamacoes()
              + "')";
      PreparedStatement sql = conn.prepareStatement(s);

      for (Eleitor e : value.getResponsaveis()) {
        if (e.getCargoVP() == Eleitor.vPresidenteType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,true,false,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.presidenteType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',true,false,false,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.secType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,false,true,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.escType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,false,false,true)");
          sql2.executeUpdate();
        }
      }
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    return value;
  }
Пример #28
0
  public AssembleiaDeVoto get(Object key) {
    ArrayList<Eleitor> el = new ArrayList<Eleitor>();
    AssembleiaDeVoto av = null;
    try {
      conn = SqlConnect.connect();
      PreparedStatement ps =
          conn.prepareStatement(
              "Select * from `assembleia de voto` where codigo = '" + (String) key + "'");
      ResultSet rs = ps.executeQuery();
      if (rs.next()) {
        String c = rs.getString("Codigo");
        PreparedStatement ps1 =
            conn.prepareStatement("Select * from `Eleitor` where assembleia de voto = '" + c + "'");
        ResultSet rs2 = ps1.executeQuery();
        for (; rs2.next(); ) {
          int type = -1;
          if (rs.getBoolean("presidente")) type = Eleitor.presidenteType;
          if (rs.getBoolean("vice-presidente")) type = Eleitor.vPresidenteType;
          if (rs.getBoolean("secretario")) type = Eleitor.secType;
          if (rs.getBoolean("escrutinadores")) type = Eleitor.escType;

          int typeL = -1;
          if (rs.getBoolean("Deputado")) typeL = Eleitor.deputado;
          if (rs.getBoolean("delegado")) typeL = Eleitor.delegado;

          Eleitor e =
              new Eleitor(
                  rs2.getString("Nr de Eleitor"),
                  rs2.getString("Nome"),
                  rs2.getInt("Idade"),
                  rs2.getDate("Data Recensiamento"),
                  rs2.getString("Distrito"),
                  rs2.getString("Concelho"),
                  rs2.getString("Freguesia"),
                  type,
                  typeL);
          el.add(e);
        }
        av =
            new AssembleiaDeVoto(
                rs.getString("Codigo"),
                rs.getString("Eleicao"),
                rs.getString("concelho"),
                rs.getString("freguesia"),
                rs.getString("Hora de Abertura"),
                rs.getString("Hora de Encerramento"),
                rs.getString("Local"),
                rs.getInt("Eleitores Inscritos"),
                rs.getInt("Nr de votantes"),
                rs.getInt("Votos em Branco"),
                rs.getInt("Votos Nulos"),
                rs.getInt("Nr de Reclamacoes"),
                el);
      }
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return av;
  }
Пример #29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String userAgent = request.getHeader("user-agent");
    if (userAgent.matches(".*Android.*")) {
      int flag = 0;
      try {
        Connection con = DBConnectionAdmin.getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT email,password FROM admin");

        String emailmember = request.getParameter("mail");
        String passwordmember = request.getParameter("pass");
        while (rs.next()) {
          String email = rs.getString("email");
          String password = rs.getString("password");
          if (email.equals(emailmember) && password.equals(passwordmember)) {
            flag = 1; // success in login
            break;
          }
        }

        /*if(request.getParameter("remember")!=null ){
        	if( request.getParameter("remember").equals("yes") ){
        					Cookie c1 = new Cookie("email", emailmember);
        					c1.setMaxAge(60*60*24*365);
        					response.addCookie(c1);
        					Cookie c2 = new Cookie("password", passwordmember);
        					c2.setMaxAge(60*60*24*365);
        					response.addCookie(c2);

        	}
        }
        else{
        	Cookie[] cookies = request.getCookies();
        	if (cookies != null) {
        		for(Cookie cookie: cookies) {
        			if(cookie.getName().equals("email")){
        				cookie.setMaxAge(0);
        				response.addCookie(cookie);
        			}
        			else if(cookie.getName().equals("password")){
        				cookie.setMaxAge(0);
        				response.addCookie(cookie);
        			}
        		}
        	}

        }*/

      } catch (SQLException | ClassNotFoundException e1) {
        e1.printStackTrace();
      }
      if (flag == 1) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
        String title = "You Signed In Successfully";
        out.println(
            docType
                + "<HTML>\n"
                + "<HEAD>"
                + "<script type='text/javascript'>"
                + "function changeweb() {"
                + "   AndroidFunction.Second();"
                + "}"
                + "</script>"
                + "<TITLE>"
                + title
                + "</TITLE></HEAD>\n"
                + "<BODY BGCOLOR=\"#FDF5E6\" ><H1 ALIGN=CENTER>"
                + title
                + "</H1>\n"
                + "<button type='button' onclick=\"changeweb()\">Click Me!</button>"
                + "</BODY></HTML>");
        HttpSession session = request.getSession(true);
        String email = request.getParameter("mail");
        session.setAttribute("email", email);

      } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
        String title = "Wrong password or E-mail.Please try again.";
        out.println(
            docType
                + "<HTML>\n"
                + "<HEAD><TITLE>"
                + title
                + "</TITLE></HEAD>\n"
                + "<BODY BGCOLOR=\"#FDF5E6\" ><H1 ALIGN=CENTER>"
                + title
                + "</H1>\n</BODY></HTML>");
      }
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
      String title = "Main";
      out.println(
          docType
              + "<HTML>\n"
              + "<HEAD><TITLE>"
              + title
              + "</TITLE>"
              + "<style>"
              + "ul"
              + "{"
              + "list-style-type:none;"
              + "margin:0;"
              + "padding:0;"
              + "overflow:hidden;"
              + "}"
              + "li"
              + "{"
              + "float:left;"
              + "}"
              + "a:link,a:visited"
              + "{"
              + "display:block;"
              + "font-weight:bold;"
              + "font-size:200%;"
              + "color:#FFFFFF;"
              + "background-color:#98bf21;"
              + "text-align:center;"
              + "padding:4px;"
              + "text-decoration:none;"
              + "text-transform:uppercase;"
              + "border: 1px solid black;"
              + "padding:25px"
              + "}"
              + "a:hover,a:active"
              + "{"
              + "background-color:#7A991A;"
              + "}"
              + "</style>"
              + "</HEAD>\n"
              + "<body style='background-color:black' >\n");

      out.println("<ul>");
      out.println("<li><a href='http://localhost:8083/TestProject/main.html'>New Event!!</a></li>");
      out.println("<li><a href='post.Eventlist'>Events</a></li>");
      out.println("<li><a href='post.Myeventlist'>My Events</a></li>");
      out.println("<li><a href='post.Memberslist'>Members</a></li>");
      out.println("<li><a href='post.Profile'>Profile</a></li>");
      out.println("<li><a href='post.Help'>Help</a></li>");
      out.println("</ul>");
      out.println("</BODY></HTML>");
    }
  }
Пример #30
0
  public void registarAssembleia(String key, AssembleiaDeVoto value) {

    try {
      conn = SqlConnect.connect();
      for (Eleitor e : value.getResponsaveis()) {
        if (e.getCargoVP() == Eleitor.vPresidenteType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,true,false,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.presidenteType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',true,false,false,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.secType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,false,true,false)");
          sql2.executeUpdate();
        }
        if (e.getCargoVP() == Eleitor.escType) {
          PreparedStatement sql2 =
              conn.prepareStatement(
                  "INSERT INTO `AVConstituintes` VALUES ('"
                      + e.getNrEleitor()
                      + "','"
                      + key
                      + "','"
                      + value.getEleicao()
                      + "',false,false,false,true)");
          sql2.executeUpdate();
        }
      }
    } catch (SQLException | ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }