/**
   * 使用 ResultSet 中的第 i 行给 Schema 赋值
   *
   * @param: rs ResultSet
   * @param: i int
   * @return: boolean
   */
  public boolean setSchema(ResultSet rs, int i) {
    try {
      // rs.absolute(i);		// 非滚动游标
      if (rs.getString("CalCode") == null) this.calCode = null;
      else this.calCode = rs.getString("CalCode").trim();

      if (rs.getString("RiskCode") == null) this.riskCode = null;
      else this.riskCode = rs.getString("RiskCode").trim();

      if (rs.getString("Type") == null) this.type = null;
      else this.type = rs.getString("Type").trim();

      if (rs.getString("CalSQL") == null) this.calSQL = null;
      else this.calSQL = rs.getString("CalSQL").trim();

      if (rs.getString("Remark") == null) this.remark = null;
      else this.remark = rs.getString("Remark").trim();

    } catch (SQLException sqle) {
      System.out.println(
          "数据库中的LEPCalMode表字段个数和Schema中的字段个数不一致,或者执行db.executeQuery查询时没有使用select * from tables");
      // @@错误处理
      CError tError = new CError();
      tError.moduleName = "LEPCalModeSchema";
      tError.functionName = "setSchema";
      tError.errorMessage = sqle.toString();
      this.mErrors.addOneError(tError);
      return false;
    }
    return true;
  }
Ejemplo n.º 2
0
    public MetadataBlob[] select(String selectString) {
      PreparedStatement stmt = null;
      try {
        stmt =
            conn.prepareStatement(
                "select writingKey, mapkey, blobdata from metadatablobs " + selectString + ";");
        ResultSet rs = stmt.executeQuery();
        List<MetadataBlob> list = new ArrayList<MetadataBlob>();
        while (rs.next()) {
          MetadataBlob f =
              new MetadataBlob(
                  rs.getString("writingkey"), rs.getString("mapkey"), rs.getString("blobdata"));
          list.add(f);
        }

        return list.toArray(new MetadataBlob[0]);
      } catch (SQLException sqe) {
        System.err.println("Error selecting: " + selectString);
        sqe.printStackTrace();
        return null;
      } finally {
        if (stmt != null)
          try {
            stmt.close();
          } catch (SQLException sqe2) {
            sqe2.printStackTrace();
          }
      }
    }
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    PrintWriter writer = response.getWriter();
    String noteName = request.getParameter("noteName");
    String note = request.getParameter("note");

    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/evernoteDB");

      Statement st = con.createStatement();

      st.executeUpdate(
          "INSERT INTO note (noteName, note) VALUES ('" + noteName + "','" + note + "')");

      response.sendRedirect("/userNotes.jsp");
    } catch (ClassNotFoundException e) {
      writer.println("Couldn't load database driver: " + e.getMessage());
    } catch (SQLException e) {
      writer.println("SQLException caught: " + e.getMessage());
    } catch (Exception e) {
      writer.println(e);
    }
  }
Ejemplo n.º 5
0
  public static String getVersion(Connection conn) throws SQLException {
    String method = "getVersion";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL =
          "SELECT CASE "
              + "WHEN POSITION ('HAWQ 2.0.1' in version) > 0 THEN 'HAWQ_2_0_1' "
              + "WHEN POSITION ('HAWQ 2.0.0' in version) > 0 THEN 'HAWQ_2_0_0' "
              + "WHEN POSITION ('HAWQ 1' in version) > 0 THEN 'HAWQ_1' "
              + "WHEN POSITION ('HAWQ' in version) = 0 AND POSITION ('Greenplum Database' IN version) > 0 THEN 'GPDB' "
              + "ELSE 'OTHER' END "
              + "FROM version()";
      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Ejemplo n.º 6
0
  private boolean login(String[] part) {
    ResultSet rs = null;

    try {
      rs = beanOracle.selection("PASSWORD", "UTILISATEURS", "LOGIN = '******'");
    } catch (SQLException e) {
      System.err.println(e.getStackTrace());
    }

    String pwd = null;

    try {
      if (!rs.next()) {
        SendMsg("ERR#Login invalide");
      } else pwd = rs.getString("PASSWORD");
    } catch (SQLException ex) {
      System.err.println(ex.getStackTrace());
    }

    if (pwd.equals(part[2])) {
      SendMsg("ACK");
      return true;
    } else SendMsg("ERR#Mot de passe incorrecte");

    return false;
  }
Ejemplo n.º 7
0
  /**
   * Deletes an instructor from the database. Deletes the instructor's courses by invoking the
   * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or
   * other database connection problems.
   *
   * @see deleteCourse
   * @param instructor instructor's user name
   * @throws InvalidDBRequestException
   */
  public void deleteInstructor(String instructor) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete the instructor's courses
      ResultSet rs =
          stmt.executeQuery(
              "select course_num from course where instructor = '" + instructor + "'");
      while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor);

      // delete the instructor's record
      count = stmt.executeUpdate("delete from instructor where login ='******'");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 8
0
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 9
0
  /**
   * Deletes students who are older than a certain number of years and not registered to any course.
   *
   * @param year students older than year are candidates to be deleted
   * @throws InvalidDBRequestException
   */
  public void deleteOldStudent(int year) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();

      // query all student who have been in the database longer than a number of years and not
      // registered to any course
      ResultSet rs =
          stmt.executeQuery(
              "select login, count(course_id) "
                  + "from student s left join courseRoster r on login = user_login "
                  + "where date_entered < SUBDATE(now(), INTERVAL "
                  + new String().valueOf(year).trim()
                  + " YEAR) "
                  + "group by login, date_entered");
      // delete them
      while (rs.next()) if (rs.getInt(2) == 0) purgeStudent(rs.getString(1).trim());

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 10
0
  /**
   * Remove a student from a particular course. Also Deletes all the quiz vizualisation files in the
   * student's directory which relates to the course. Caution: vizualisation file will be deleted
   * eventhough it also relates to another course if the student is also registered to that course.
   * (FIX ME!) Throws InvalidDBRequestException if the student is not registered in the course,
   * error occured during deletion, or other exception occured.
   *
   * @param username student's user name
   * @param courseID course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void deleteStudent(String username, String courseID) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if student registered to the course
      rs =
          stmt.executeQuery(
              "select * from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (!rs.next())
        throw new InvalidDBRequestException("Student is not registered to the course");

      // remove student from the course
      count =
          stmt.executeUpdate(
              "delete from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (count != 1) throw new InvalidDBRequestException("Error occured during deletion!");

      // delete the quiz visualization files
      rs =
          stmt.executeQuery(
              "select distinct unique_id, s.test_name from scores s, courseTest t "
                  + "where s.test_name = t.test_name "
                  + "and course_id = '"
                  + courseID
                  + "' "
                  + "and user_login = '******'");
      while (rs.next()) {
        deleteVisualization(rs.getString(1), username, rs.getString(2));
        count =
            stmt.executeUpdate("delete from scores where unique_id = " + rs.getString(1).trim());
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addstudent: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 11
0
  /**
   * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any
   * error occured to the database connection.
   *
   * @param name the instructor's user name
   * @return a vector containing the list of courses
   * @throws InvalidDBRequestException
   */
  public Vector getCourseList(String name) throws InvalidDBRequestException {
    Vector courseList = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get the course list
      rs =
          stmt.executeQuery(
              "select course_num, course_name from course where instructor = '"
                  + name
                  + "' order by course_num");
      while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2));

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getCourseList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }

    return courseList;
  }
Ejemplo n.º 12
0
  public static void dropExternalReplTable(
      Connection conn,
      String sourceType,
      String targetSchema,
      String targetTable,
      String sourceTable)
      throws SQLException {
    String method = "dropExternalReplTable";
    int location = 1000;
    try {
      location = 2000;
      String replTargetSchema = externalSchema;

      location = 2100;
      String replTargetTable = getStageTableName(targetSchema, targetTable);

      location = 2200;
      String replSourceTable = getReplTableName(sourceType, sourceTable);

      location = 2315;
      dropExternalTable(conn, replTargetSchema, replTargetTable);
    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
  /** Returns true if this VM has acquired the right to run this TestTask */
  private static DUnitRun getDUnitRun() {
    if (dunitRun != null) {
      System.out.println("BBB dunitRun not null returning");
      return dunitRun;
    }

    try {
      SwarmBB.getBB().getSharedLock().lock();
      Integer runId = (Integer) SwarmBB.getBB().getSharedMap().get(SwarmBB.RUN_ID);
      System.out.println("BBB runID=" + runId);
      if (runId != null) {
        dunitRun = Swarm.getDUnitRun(runId);
        System.out.println("BBB lookedUp RUN:" + dunitRun);
      } else {
        dunitRun = Swarm.generateNewDUnitRun();
        System.out.println(
            "BBB GENNED UP A RUN:" + dunitRun + " mapping to id:" + dunitRun.getId());
        SwarmBB.getBB().getSharedMap().put(SwarmBB.RUN_ID, dunitRun.getId());
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      SwarmBB.getBB().getSharedLock().unlock();
    }
    return dunitRun;
  }
Ejemplo n.º 14
0
  /**
   * Maps attributes of an SQL structured type that are not serialized to a serialized form, using
   * the given type map for custom mapping when appropriate. The following types in the Java
   * programming language are mapped to their serialized forms: <code>Struct</code>, <code>SQLData
   * </code>, <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, and <code>Array</code>.
   *
   * <p>This method is called internally and is not used by an application programmer.
   *
   * @param map a <code>java.util.Map</code> object in which each entry consists of 1) a <code>
   *     String</code> object giving the fully qualified name of a UDT and 2) the <code>Class</code>
   *     object for the <code>SQLData</code> implementation that defines how the UDT is to be mapped
   * @throws SerialException if an error occurs
   */
  private void mapToSerial(Map map) throws SerialException {

    try {

      for (int i = 0; i < attribs.length; i++) {
        if (attribs[i] instanceof Struct) {
          attribs[i] = new SerialStruct((Struct) attribs[i], map);
        } else if (attribs[i] instanceof SQLData) {
          attribs[i] = new SerialStruct((SQLData) attribs[i], map);
        } else if (attribs[i] instanceof Blob) {
          attribs[i] = new SerialBlob((Blob) attribs[i]);
        } else if (attribs[i] instanceof Clob) {
          attribs[i] = new SerialClob((Clob) attribs[i]);
        } else if (attribs[i] instanceof Ref) {
          attribs[i] = new SerialRef((Ref) attribs[i]);
        } else if (attribs[i] instanceof java.sql.Array) {
          attribs[i] = new SerialArray((java.sql.Array) attribs[i], map);
        }
      }

    } catch (SQLException e) {
      throw new SerialException(e.getMessage());
    }
    return;
  }
Ejemplo n.º 15
0
 public void deleteOption(String modelName, String optionSetName, String option) {
   try {
     int autoid = 0;
     String sql = "select id from automobile where name ='" + modelName + "';";
     ResultSet rs;
     rs = statement.executeQuery(sql);
     while (rs.next()) {
       autoid = rs.getInt("id"); // get auto_id
     }
     int opsid = 0;
     sql =
         "select id from optionset where name ='"
             + optionSetName
             + "' and auto_id= "
             + autoid
             + ";";
     rs = statement.executeQuery(sql);
     while (rs.next()) {
       opsid = rs.getInt("id"); // get option_id
     }
     sql = "delete from options where name= '" + option + "' and option_id= " + opsid;
     statement.executeUpdate(sql); // delete it using name and option_id
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
  /** Creates a Pooled connection and adds it to the connection pool. */
  private void installConnection() throws EmanagerDatabaseException {
    logger.debug("enter");

    PooledConnection connection;

    try {
      connection = poolDataSource.getPooledConnection();
      connection.addConnectionEventListener(this);
      connection.getConnection().setAutoCommit(false);
      synchronized (connectionPool) {
        connectionPool.add(connection);
        logger.debug("Database connection added.");
      }
    } catch (SQLException ex) {
      logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex);
      SQLException ex1 = ex.getNextException();
      while (ex1 != null) {
        logger.fatal("chained sql exception ex1 = " + ex1);
        SQLException nextEx = ex1.getNextException();
        ex1 = nextEx;
      }
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString);
      throw ede;
    }
  }
Ejemplo n.º 17
0
  public void conectarBaseDeDatos() {
    try {
      final String CONTROLADOR = "org.postgresql.Driver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion =
          DriverManager.getConnection(
              "jdbc:postgresql://" + main.ipSeleccionada + "/" + objUtils.nameBD, user, pass);
      // conexion = DriverManager.getConnection("jdbc:postgresql://127.0.0.1/goliak_jg", "postgres",
      // "majcp071102kaiser");

      sentencia = conexion.createStatement();
      /*JOptionPane.showMessageDialog(null, "si conecta");*/
    } catch (ClassNotFoundException ex1) {
      // ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
      System.exit(1);
    } catch (SQLException ex) {
      // ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(
          null,
          "Error Creacion Statement."
              + ex.getMessage()
              + " / "
              + url
              + " / "
              + user
              + " / "
              + pass);
      System.exit(1);
    }
  }
Ejemplo n.º 18
0
  public void display(ResultSet rs) {
    try {
      boolean recordNumber = rs.next();
      if (recordNumber) {
        payNo = rs.getString(1);
        pasNo = rs.getString(2);
        pasName = rs.getString(3);
        mode = rs.getString(4);
        dt = rs.getString(5);
        amount = rs.getString(6);
        rev = rs.getString(7);

        text1.setText(payNo);
        combo1.setSelectedItem(pasNo);
        combo2.setSelectedItem(pasName);
        combo4.setSelectedItem(mode);
        p_date.setText(dt);
        combo8.setSelectedItem(amount);
        combo3.setSelectedItem(rev);

      } else {
        JOptionPane.showMessageDialog(
            null, "Record Not found", "ERROR", JOptionPane.DEFAULT_OPTION);
      }
    } catch (SQLException sqlex) {
      sqlex.printStackTrace();
    }
  }
Ejemplo n.º 19
0
 // AQUI VOYA  OBTENER EL SERVDUIOR QUEMADO EN UN ARCHIVO DE TEXTO
 public void conectarBaseDeDatos2() {
   try {
     final String CONTROLADOR = "org.postgresql.Driver";
     Class.forName(CONTROLADOR);
     // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
     conexion = DriverManager.getConnection(url2, user, pass);
     sentencia = conexion.createStatement();
     /*JOptionPane.showMessageDialog(null, "si conecta");*/
   } catch (ClassNotFoundException ex1) {
     // ex1.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
     System.exit(1);
   } catch (SQLException ex) {
     // ex.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(
         null,
         "Error Creacion Statement."
             + ex.getMessage()
             + " / "
             + url2
             + " / "
             + user
             + " / "
             + pass);
     System.exit(1);
   }
 }
  /**
   * 使用 ResultSet 中的第 i 行给 Schema 赋值
   *
   * @param: rs ResultSet
   * @param: i int
   * @return: boolean
   */
  public boolean setSchema(ResultSet rs, int i) {
    try {
      // rs.absolute(i);		// 非滚动游标
      if (rs.getString("RiskCode") == null) this.riskCode = null;
      else this.riskCode = rs.getString("RiskCode").trim();

      if (rs.getString("RiskVer") == null) this.riskVer = null;
      else this.riskVer = rs.getString("RiskVer").trim();

      if (rs.getString("DutyCode") == null) this.dutyCode = null;
      else this.dutyCode = rs.getString("DutyCode").trim();

      if (rs.getString("ChoFlag") == null) this.choFlag = null;
      else this.choFlag = rs.getString("ChoFlag").trim();

      if (rs.getString("SpecFlag") == null) this.specFlag = null;
      else this.specFlag = rs.getString("SpecFlag").trim();

    } catch (SQLException sqle) {
      System.out.println(
          "数据库中的LEPRiskDuty表字段个数和Schema中的字段个数不一致,或者执行db.executeQuery查询时没有使用select * from tables");
      // @@错误处理
      CError tError = new CError();
      tError.moduleName = "LEPRiskDutySchema";
      tError.functionName = "setSchema";
      tError.errorMessage = sqle.toString();
      this.mErrors.addOneError(tError);
      return false;
    }
    return true;
  }
Ejemplo n.º 21
0
  /**
   * Check the user's name and password and verify that the user is an instructor. Throws
   * InvalidDBRequestException if user is not an instructor, wrong password, or if any error occured
   * to the database connection.
   *
   * @param name user's user name
   * @param pass user's password
   * @throws InvalidDBRequestException
   */
  public void instructorLogin(String name, String pass) throws InvalidDBRequestException {
    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // check if instructor
      rs = stmt.executeQuery("select password from instructor where login = '******'");
      if (!rs.next()) {
        if (debug) System.out.println("User not found in the instructor table");
        throw new InvalidDBRequestException("Instructor not registered");
      }

      // check password
      if (!rs.getString(1).equals(pass)) {
        if (debug) System.out.println("Invalid password for user: "******"Invalid password for user: "******"Invalid SQL in instructor login: "******"???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }
  }
Ejemplo n.º 22
0
  public static void failJobs(Connection conn) throws SQLException {
    String method = "failJobs";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      String strSQL =
          "INSERT INTO os.ao_queue (queue_id, status, queue_date, start_date, end_date, "
              + "error_message, num_rows, id, refresh_type, target_schema_name, target_table_name, target_append_only, "
              + "target_compressed, target_row_orientation, source_type, source_server_name, source_instance_name, "
              + "source_port, source_database_name, source_schema_name, source_table_name, source_user_name, "
              + "source_pass, column_name, sql_text, snapshot) "
              + "SELECT queue_id, 'failed' as status, queue_date, start_date, now() as end_date, "
              + "'Outsourcer stop requested' as error_message, num_rows, id, refresh_type, target_schema_name, "
              + "target_table_name, target_append_only, target_compressed, target_row_orientation, source_type, "
              + "source_server_name, source_instance_name, source_port, source_database_name, source_schema_name, "
              + "source_table_name, source_user_name, source_pass, column_name, sql_text, snapshot "
              + "FROM os.queue WHERE status = 'queued'";

      stmt.executeUpdate(strSQL);

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Ejemplo n.º 23
0
  public static void customStartAll(Connection conn) throws SQLException {
    String method = "customStartAll";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      int id = 0;
      int gpfdistPort = 0;
      String strSQL = "SELECT id\n";
      strSQL += "FROM os.custom_sql";

      ResultSet rs = stmt.executeQuery(strSQL);
      while (rs.next()) {
        id = rs.getInt(1);
        gpfdistPort = GpfdistRunner.customStart(OSProperties.osHome);

        strSQL = "INSERT INTO os.ao_custom_sql\n";
        strSQL +=
            "(id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, gpfdist_port)\n";
        strSQL +=
            "SELECT id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, "
                + gpfdistPort
                + "\n";
        strSQL += "FROM os.custom_sql\n";
        strSQL += "WHERE id = " + id;

        stmt.executeUpdate(strSQL);
      }
    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Ejemplo n.º 24
0
  public static String getVariable(Connection conn, String name) throws SQLException {
    String method = "getVariable";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL = "SELECT os.fn_get_variable('" + name + "')";

      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Ejemplo n.º 25
0
  public void updateOptionPrice(
      String modelName, String optionSetName, String optionName, float newPrice) {
    try {
      int autoid = 0;
      String sql = "select id from automobile where name ='" + modelName + "';";
      ResultSet rs = statement.executeQuery(sql);
      while (rs.next()) {
        autoid = rs.getInt("id"); // get auto_id
      }
      int opsid = 0;
      sql =
          "select id from optionset where name ='"
              + optionSetName
              + "' and auto_id= "
              + autoid
              + ";";
      rs = statement.executeQuery(sql);
      while (rs.next()) {
        opsid = rs.getInt("id"); // get option_id
      }
      sql =
          "update options set price = "
              + newPrice
              + " where name= '"
              + optionName
              + "' and option_id= "
              + opsid
              + ";";
      statement.executeUpdate(sql); // update it with name and option_id

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
  public void conectarBDdinamic(String ip) {

    if (ip == null) {
      ip = "192.168.8.231";
    }
    url = "jdbc:postgresql://" + ip + "/ventasalm";
    // javax.swing.JOptionPane.showMessageDialog(null, url);
    String estado;
    try {

      final String CONTROLADOR = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion = DriverManager.getConnection(url, user, pass);
      sentencia = conexion.createStatement();
      // estado="Conectado Correctamente";
    } catch (ClassNotFoundException ex1) {
      ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    } catch (SQLException ex) {
      ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Creacion Statement");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    }
    // return estado;
  }
Ejemplo n.º 27
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
Ejemplo n.º 28
0
  /**
   * Obtains information on a quiz that a student has taken, which includes the student's answer to
   * the quiz, a unique id of the instance, number of questions in the quiz, number of questions
   * answered correctly, and vizualisation type of the quiz. Throws InvalidDBRequestException if
   * cannot find the record of the stuent taking the quiz, quiz is not registered in the database,
   * or if any error occured to the database connection.
   *
   * @param student student's user name
   * @param quiz quiz name
   * @param startTime the time the student started the quiz
   * @return a string tokenizer containing: answer,uniqueID, numQuestions, numCorrect, and
   *     visualType. It uses "@" as the delimiter.
   * @throws InvalidDBRequestException
   */
  public StringTokenizer getAnswerAndVisualType(String student, String quiz, String startTime)
      throws InvalidDBRequestException {
    String answer;
    String uniqueID;
    String numQuestions;
    String numCorrect;
    String visualType;
    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get student's answer, unique id, number of questions, and number of questions answered
      // correctly
      rs =
          stmt.executeQuery(
              "select transcript, unique_id, num_questions, num_correct from scores "
                  + "where test_name = '"
                  + quiz
                  + "' and user_login = '******' and start_time = '"
                  + startTime
                  + "'");
      if (!rs.next()) throw new InvalidDBRequestException("Student has not taken the quiz");
      else {
        answer = rs.getString(1).trim();
        uniqueID = rs.getString(2).trim();
        numQuestions = rs.getString(3).trim();
        numCorrect = rs.getString(4).trim();
      }

      // get quiz vizualisation type
      rs = stmt.executeQuery("select visual_type from test where name = '" + quiz + "' ");
      if (!rs.next())
        throw new InvalidDBRequestException(
            "Quiz was not found! Can't retrieve visualization type.");
      else {
        visualType = rs.getString(1);
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getAnswerAndVisualType: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
    return new StringTokenizer(
        answer + "@" + uniqueID + "@" + numQuestions + "@" + numCorrect + "@" + visualType, "@");
  }
Ejemplo n.º 29
0
  /**
   * Query a quiz list from the database. If there is no student user name specified, the list will
   * contain all quizzes that are used in the instructor's courses. Otherwise, the list will contain
   * all quizzes that the student has taken and from the instructor's courses which the student is
   * registered. Throws InvalidDBRequestException if any error occured to the database connection.
   *
   * @param instructor instructor's user name
   * @param student student's user name. Can be empty to get a list of all quizzes in the
   *     instructor's courses.
   * @return a vector containing the list of quizzes
   * @throws InvalidDBRequestException
   */
  public Vector getQuizList(String instructor, String student) throws InvalidDBRequestException {
    Vector list = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      if (!student.equals("")) {
        // get the list that contains all quizzes that the student has taken and from the
        // instructor's courses which the student is registered
        rs =
            stmt.executeQuery(
                "select courseTest.test_name, scores.start_time from scores, courseTest, course "
                    + "where courseTest.test_name = scores.test_name "
                    + "and courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' and user_login = '******' "
                    + "order by scores.start_time");

        while (rs.next()) {
          list.add(rs.getString(1) + " <" + rs.getString(2) + ">");
        }
      } else {
        // get the list that contains all quizzes that are used in the instructor's courses
        rs =
            stmt.executeQuery(
                "select test_name from courseTest, course "
                    + "where courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' ");

        while (rs.next()) {
          list.add(rs.getString(1));
        }
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getQuizList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }

    return list;
  }
Ejemplo n.º 30
0
 /**
  * Sets the SQL structured type that this <code>SerialRef</code> object references to the given
  * <code>Object</code> object.
  *
  * @param obj an <code>Object</code> representing the SQL structured type to be referenced
  * @throws SerialException if an error is encountered generating the the structured type
  *     referenced by this <code>SerialRef</code> object
  */
 public void setObject(Object obj) throws SerialException {
   try {
     reference.setObject(obj);
   } catch (SQLException e) {
     throw new SerialException("SQLException: " + e.getMessage());
   }
   object = obj;
 }