//
  // Find all the java.sql interfaces implemented by a class and find
  // the methods in those interfaces which raise
  // SQLFeatureNotSupportedException when called on the passed-in candidate object.
  //
  private void vetInterfaces(
      Object candidate,
      Class myClass,
      HashSet<String> unsupportedList,
      HashSet<String> notUnderstoodList)
      throws Exception {
    Class superClass = myClass.getSuperclass();

    if (superClass != null) {
      vetInterfaces(candidate, superClass, unsupportedList, notUnderstoodList);
    }

    //
    // The contract for Class.getInterfaces() states that the interfaces
    // come back in a deterministic order, namely, in the order that
    // they were declared in the "extends" clause.
    //
    Class<?>[] interfaces = myClass.getInterfaces();
    int interfaceCount = interfaces.length;

    for (int i = 0; i < interfaceCount; i++) {
      Class<?> iface = interfaces[i];

      if (iface.getPackage().getName().equals(SQL_PACKAGE_NAME)) {
        vetInterfaceMethods(candidate, iface, unsupportedList, notUnderstoodList);
      }

      vetInterfaces(candidate, iface, unsupportedList, notUnderstoodList);
    }
  }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Ejemplo n.º 3
0
  public static void main(String[] args)
      throws SQLException, ClassNotFoundException, JSONException {
    PostgresDb db = new PostgresDb();
    // db.setUrl("jdbc:postgresql://localhost:5432/powaaim");

    try {
      Class.forName("org.postgresql.Driver");
      c = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPass());
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    st = c.createStatement();
    rs = st.executeQuery("SELECT id, name, externalshopid from shop where name='David_3'");
    System.out.println("id" + " " + "name" + " " + "externalshopid");
    c.close();
    obj = new JSONObject();

    while (rs.next()) {
      int id = rs.getInt("id");
      String externaId = rs.getString("externalshopid");
      String name = rs.getString("name");
      // System.out.println(id+ " " + " "+ name + " " +" "+ externaId);
      System.out.println();
      obj.put("id", id);
      obj.put("name", name);
      obj.put("externalshopid", externaId);
      System.out.print(obj);
    }
  }
 /**
  * Returns a null value compatible with the class. For instance, return <code>Boolean.FALSE</code>
  * for primitive booleans, 0 for primitive integers and <code>null</code> for non-primitive types.
  *
  * @param type a <code>Class</code> value
  * @return a null value
  */
 private Object getNullValueForType(Class type) {
   if (!type.isPrimitive()) {
     return null;
   }
   if (type == Boolean.TYPE) {
     return Boolean.FALSE;
   }
   if (type == Character.TYPE) {
     return new Character((char) 0);
   }
   if (type == Byte.TYPE) {
     return new Byte((byte) 0);
   }
   if (type == Short.TYPE) {
     return new Short((short) 0);
   }
   if (type == Integer.TYPE) {
     return new Integer(0);
   }
   if (type == Long.TYPE) {
     return new Long(0L);
   }
   if (type == Float.TYPE) {
     return new Float(0f);
   }
   if (type == Double.TYPE) {
     return new Double(0d);
   }
   fail("Don't know how to handle type " + type);
   return null; // unreachable statement
 }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
  //
  // Initialize the hashtable of methods which are allowed to raise
  // SQLFeatureNotSupportedException.
  //
  private void initializeExcludableMap(HashSet<String> vanishedMethodList) throws Exception {
    excludableMap = new Hashtable<Class, HashSet<Method>>();

    int count = rawExcludables.length;

    for (int i = 0; i < count; i++) {
      Exclusions exclusions = rawExcludables[i];
      Class<?> iface = exclusions.getInterface();
      MD[] mds = exclusions.getExcludedMethods();
      int exclusionCount = mds.length;
      HashSet<Method> excludedMethodSet = new HashSet<Method>();

      for (int j = 0; j < exclusionCount; j++) {
        MD md = mds[j];

        if (!md.requiredAtThisLevel()) {
          continue;
        }

        //
        // If we are strictly enforcing the JDBC standard,
        // then expose the mandatory methods which we know Derby
        // doesn't implement.
        //
        if (STRICT_ENFORCEMENT && !md.isOptional()) {
          continue;
        }

        Method method = null;

        try {
          method = iface.getMethod(md.getMethodName(), md.getArgTypes());
        } catch (NoSuchMethodException e) {
        }

        if (method == null) {
          vanishedMethodList.add(
              "Method has vanished from SQL interface: " + iface.getName() + "." + md);
        }

        excludedMethodSet.add(method);
      }

      excludableMap.put(iface, excludedMethodSet);
    }
  }
 public Connection createConnection() throws Exception {
   Connection con;
   try {
     Class.forName(dbClass);
     con = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
   } catch (Exception e) {
     e.printStackTrace();
     throw e;
   }
   return con;
 }
Ejemplo n.º 8
0
  /**
   * Establece una conexión con la base de datos, usando el usuario y clave especificados. Si ya hay
   * una conexi�n, esta es cerrada.
   *
   * @param usuario Una cadena con el nombre de usuario
   * @param clave Una cadena con la clave
   * @return Regresa verdadero (true) si pudo establecer la conexión de lo contrario regresa falso
   *     (false).
   */
  protected boolean conectar(String usuario, String clave) throws Exception {

    // Registra el controlador de manera implicita
    Class.forName(controlador).newInstance();
    // Obtiene la conexión
    System.err.println(url + "," + usuario + "," + clave + ":OK!!!");
    this.conexión = DriverManager.getConnection(url, usuario, clave);
    // Actualiza usuario y clave del middler
    this.usuario = usuario;
    this.clave = clave;
    return this.conexión != null;
  } // Fin conectar
Ejemplo n.º 9
0
 /** Set up a pool with a given key. */
 public synchronized ConnectionPool addAlias(
     String poolKey,
     String driverClassName,
     String dbURL,
     String userName,
     String password,
     int maxSize,
     long expiration)
     throws ClassNotFoundException, InstantiationException, IllegalAccessException {
   Class.forName(driverClassName).newInstance();
   ConnectionPool cp = new ConnectionPool(dbURL, userName, password, maxSize, expiration, debug);
   poolMap.put(poolKey, cp);
   return cp;
 }
Ejemplo n.º 10
0
  //
  // Return the methods of an interface in a deterministic
  // order. Class.getMethods() does not do us this favor.
  //
  private Method[] sortMethods(Class iface) throws Exception {
    Method[] raw = iface.getMethods();
    int count = raw.length;
    Method[] cooked = new Method[count];
    MethodSortable[] sortables = new MethodSortable[count];

    for (int i = 0; i < count; i++) {
      sortables[i] = new MethodSortable(raw[i]);
    }

    Arrays.sort(sortables);

    for (int i = 0; i < count; i++) {
      cooked[i] = sortables[i].getMethod();
    }

    return cooked;
  }
Ejemplo n.º 11
0
 public CachedRowSet query(String sql, int pageSize, int page) throws Exception {
   // 加载驱动
   Class.forName(driver);
   try (
   // 获取数据库连接
   Connection conn = DriverManager.getConnection(url, user, pass);
       Statement stmt = conn.createStatement();
       ResultSet rs = stmt.executeQuery(sql)) {
     // 使用RowSetProvider创建RowSetFactory
     RowSetFactory factory = RowSetProvider.newFactory();
     // 创建默认的CachedRowSet实例
     CachedRowSet cachedRs = factory.createCachedRowSet();
     // 设置每页显示pageSize条记录
     cachedRs.setPageSize(pageSize);
     // 使用ResultSet装填RowSet,设置从第几条记录开始
     cachedRs.populate(rs, (page - 1) * pageSize + 1);
     return cachedRs;
   }
 }
 public static void createConnectionPool() {
   Context context;
   try {
     context = new InitialContext();
     Class.forName("org.firebirdsql.jdbc.FBDriver");
     ds = (DataSource) context.lookup("java:comp/env/jdbc/PanelTrackDB");
     Connection c = ds.getConnection();
   } catch (NamingException e) {
     // TODO Auto-generated catch block
     errorLogger.error("An Error Occured:", e);
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     errorLogger.error("An Error Occured:", e);
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (SQLException e) {
     errorLogger.error("An Error Occured:", e);
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    Connection con = null;
    Statement stat = null;
    String s;
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");

      //    con=DriverManager.getConnection("jdbc:oracle:oci8:@oracle9i","scott","tiger");

      //
      // con=DriverManager.getConnection("jdbc:oracle:thin:@saraswati:1521:oracle10g","scott","tiger");
      con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "scott", "tiger");

      /*Properties p=new Properties();
      p.put("user","scott");
      p.put("password","tiger");*/

      // Driver d=(Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

      // Connection con=d.connect("jdbc:odbc:oradsn",p);

      // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      // con=DriverManager.getConnection("jdbc:odbc:namadsn","scott","tiger");

      System.out.println("The connection is successful.");
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      stat = con.createStatement();
      s = "create table student(Rollno int,Name varchar2(50),serName varchar2(50))";
      stat.executeUpdate(s);
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      stat = con.createStatement();
      s = "insert into student values(1,'Namrata','Marathe')";
      stat.executeUpdate(s);
      s = "insert into student values(2,'Arjun','Marathe')";
      stat.executeUpdate(s);
      s = "insert into student values(3,'Rahul','Marathe')";
      stat.executeUpdate(s);

    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      stat.close();
    } catch (SQLException e) {
    }

    System.out.println("create is successful:");

    try {
      stat = con.createStatement();
      s = "select * from student";
      ResultSet rset = stat.executeQuery(s);

      while (rset.next())
        System.out.println(rset.getInt(1) + " " + rset.getString(2) + "    " + rset.getString(3));
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      stat.close();
    } catch (SQLException se) {

    }
  }
Ejemplo n.º 14
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    server svr = new server();
    response.setContentType("text/html");
    HttpSession session = request.getSession(true);
    PrintWriter out = response.getWriter();
    String email = request.getParameter("email");
    String pw1 = request.getParameter("pw1");
    String pw2 = request.getParameter("pw2");
    String error = null;
    String username = session.getAttribute("username").toString();
    if (pw1.compareTo(pw2) != 0) {
      error = "Passwords do not match";
      session.setAttribute("ErrorMessage", error);
      response.sendRedirect("home.jsp");
    }
    try {
      Statement st = null;
      String strQuery = null;
      if ((pw1.length() == 0) && (email.length() == 0)) {
        session.setAttribute("ErrorMessage", "Nothing to change!");
        response.sendRedirect("home.jsp");
      } else if ((pw1.length() != 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "', `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() == 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() != 0) && (email.length() == 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "' WHERE `username`='"
                + username
                + "'";
      }
      Connection dbcon = null;
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      dbcon = DriverManager.getConnection(svr.getURL(), svr.getUN(), svr.getPW());
      st = dbcon.createStatement();
      st.executeUpdate(strQuery);
      session.setAttribute("ErrorMessage", "Details Changed");
      dbcon.close();
      session.setAttribute("ErrorMessage", "Details Changed");
      response.sendRedirect("home.jsp");
    } catch (Exception ex) {
      out.println(ex);
    }
  }
Ejemplo n.º 15
0
 /** @deprecated use or rewrite in terms of ReflectUtils.findProxyConstructor() */
 private static Constructor createProxyConstructor(Class intfc) throws NoSuchMethodException {
   Class[] proxyInterfaces = new Class[] {intfc};
   Class proxyCl =
       Proxy.getProxyClass(C3P0PooledConnection.class.getClassLoader(), proxyInterfaces);
   return proxyCl.getConstructor(PROXY_CTOR_ARGS);
 }