public Connection getConnection() throws SQLException {
    synchronized (pool) {
      if (!pool.isEmpty()) {
        int last = pool.size() - 1;
        Connection pooled = (Connection) pool.remove(last);

        boolean conn_ok = true;
        String test_table = prop.getProperty("test_table");
        if (test_table != null) {
          Statement stmt = null;
          try {
            stmt = pooled.createStatement();
            stmt.executeQuery("select * from " + prop.getProperty("test_table"));
          } catch (SQLException ex) {
            conn_ok = false; // 连接不可用
          } finally {
            if (stmt != null) {
              stmt.close();
            }
          }
        }
        if (conn_ok == true) {
          return pooled;
        } else {
          pooled.close();
        }
      }
    }
    Connection conn =
        DriverManager.getConnection(
            prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
    return conn;
  }
示例#2
0
  public void t1estDataSource() {
    Connection con = null;
    Statement st = null;
    try {
      P6TestUtil.unloadDrivers();

      // try to do a simple test using the datasourcey stuff
      Properties props = P6TestUtil.loadProperties("P6Test.properties");
      String user = props.getProperty("user");
      String password = props.getProperty("password");
      String url = props.getProperty("url");

      P6DriverManagerDataSource ds = new P6DriverManagerDataSource();

      ds.setUrl(url);

      con = ds.getConnection(user, password);
      st = con.createStatement();
      st.execute("create table foo (col1 varchar2(255))");
      st.execute("insert into table foo values ('1')");

      ResultSet rs = st.executeQuery("select count(*) from foo");
      // assertTrue(rs.

    } catch (Exception e) {
      e.printStackTrace(System.out);
      fail("unexpected exception: " + e);
    } finally {

    }
  }
  private LogisticRegressionModel instantiateSparkModel() {
    Configuration conf = new Configuration();
    conf.set("fs.defaultFS", topologyConfig.getProperty("hdfs.url"));

    double[] sparkModelInfo = null;

    try {
      sparkModelInfo =
          getSparkModelInfoFromHDFS(
              new Path(topologyConfig.getProperty("hdfs.url") + "/tmp/sparkML_weights"), conf);
    } catch (Exception e) {
      LOG.error("Couldn't instantiate Spark model in prediction bolt: " + e.getMessage());
      e.printStackTrace();

      throw new RuntimeException(e);
    }

    // all numbers besides the last value are the weights
    double[] weights = Arrays.copyOfRange(sparkModelInfo, 0, sparkModelInfo.length - 1);

    // the last number in the array is the intercept
    double intercept = sparkModelInfo[sparkModelInfo.length - 1];

    org.apache.spark.mllib.linalg.Vector weightsV = (Vectors.dense(weights));
    return new LogisticRegressionModel(weightsV, intercept);
  }
示例#4
0
 private Properties decryptPwd(Properties initProps) {
   String encryptionKey = initProps.getProperty("encryptKeyFile");
   if (initProps.getProperty("password") != null && encryptionKey != null) {
     // this means the password is encrypted and use the file to decode it
     try {
       try (Reader fr = new InputStreamReader(new FileInputStream(encryptionKey), UTF_8)) {
         char[] chars = new char[100]; // max 100 char password
         int len = fr.read(chars);
         if (len < 6)
           throw new DataImportHandlerException(
               SEVERE, "There should be a password of length 6 atleast " + encryptionKey);
         Properties props = new Properties();
         props.putAll(initProps);
         String password = null;
         try {
           password =
               CryptoKeys.decodeAES(initProps.getProperty("password"), new String(chars, 0, len))
                   .trim();
         } catch (SolrException se) {
           throw new DataImportHandlerException(SEVERE, "Error decoding password", se.getCause());
         }
         props.put("password", password);
         initProps = props;
       }
     } catch (IOException e) {
       throw new DataImportHandlerException(
           SEVERE, "Could not load encryptKeyFile  " + encryptionKey);
     }
   }
   return initProps;
 }
示例#5
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
示例#6
0
 public void initParam(String paramFile) throws Exception {
   // 使用Properties类来加载属性文件
   Properties props = new Properties();
   props.load(new FileInputStream(paramFile));
   driver = props.getProperty("driver");
   url = props.getProperty("url");
   user = props.getProperty("user");
   pass = props.getProperty("pass");
 }
  private static void truncateSeleniumTables(List<String> tables) {
    Properties props = getSeleniumProperties();

    clearDatabaseAndSkipBaseData(
        tables,
        props.getProperty(DB_URL_KEY),
        props.getProperty(DB_USER_KEY),
        props.getProperty(DB_PASS_KEY),
        props.getProperty(DB_DRIVER_CLASS_KEY));
  }
示例#8
0
  Competition getDataFromDatabase(String arg, Properties properties) {
    Competition competition = new Competition();

    String getAthleteDataQuery =
        "SELECT athletes.name, athletes.dob, athletes.country_code, "
            + "results.race_100m, results.long_jump, results.shot_put, results.high_jump, results.race_400m, "
            + "results.hurdles_110m, results.discus_throw, results.pole_vault, results.javelin_throw, results.race_1500m "
            + "FROM athletes, results, competitions "
            + "WHERE athletes.id = results.athlete_id "
            + "AND results.competition_id = competitions.id "
            + "AND (competitions.id = ? OR competitions.name = ?)";

    Connection conn = null;

    try {
      String url = properties.getProperty("db.url");
      String username = properties.getProperty("db.username");
      String password = properties.getProperty("db.password");

      conn = DriverManager.getConnection(url, username, password);
      PreparedStatement athleteDataQuery = conn.prepareStatement(getAthleteDataQuery);
      athleteDataQuery.setString(1, arg);
      athleteDataQuery.setString(2, arg);
      ResultSet resultSet = athleteDataQuery.executeQuery();

      while (resultSet.next()) {
        Athlete athlete = parseAthlete(resultSet);
        if (athlete == null) {
          System.out.println(Error.ERROR_DB_ATHLETE_PARSING_FAILED.getErrorText());
          continue;
        }

        DecathlonEvents decathlonEvents = parseDecathlonEvents(resultSet);
        if (decathlonEvents == null) {
          System.out.println(Error.ERROR_DB_ATHLETE_RESULTS_PARSING_FAILED.getErrorText());
          continue;
        }
        athlete.setDecathlonEvent(decathlonEvents);

        competition.addAthlete(athlete);
      }
    } catch (SQLException e) {
      System.out.println(Error.ERROR_DB_CONNECTION.getErrorText());
    } finally {
      if (conn != null)
        try {
          conn.close();
        } catch (SQLException e) {
          System.out.println(Error.ERROR_DB_CLOSE.getErrorText());
        }
    }
    return competition;
  }
示例#9
0
  /** 利用属性文件中的信息连接数据库 * */
  public static Connection getConnection() throws SQLException, IOException {
    Properties props = new Properties();
    String fileName = "QueryDB.properties";
    FileInputStream in = new FileInputStream(fileName);
    props.load(in);

    String drivers = props.getProperty("jdbc.drivers");
    if (drivers != null) System.setProperty("jdbc.drivers", drivers);
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    return DriverManager.getConnection(url, username, password);
  }
示例#10
0
 public static Connection ConnectionProvider() {
   try {
     Class.forName(prop.getProperty("driverClass"));
     Connection connection =
         DriverManager.getConnection(
             prop.getProperty("url"), prop.getProperty("userName"), prop.getProperty("password"));
     return connection;
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   return null;
 }
示例#11
0
  /**
   * Gets a connection from the properties specified in the file database.properties
   *
   * @return the database connection
   */
  public static Connection getConnection() throws SQLException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("database.properties"))) {
      props.load(in);
    }

    String drivers = props.getProperty("jdbc.drivers");
    if (drivers != null) System.setProperty("jdbc.drivers", drivers);

    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    return DriverManager.getConnection(url, username, password);
  }
示例#12
0
  @Override
  public void init(Context context, Properties initProps) {
    initProps = decryptPwd(initProps);
    Object o = initProps.get(CONVERT_TYPE);
    if (o != null) convertType = Boolean.parseBoolean(o.toString());

    factory = createConnectionFactory(context, initProps);

    String bsz = initProps.getProperty("batchSize");
    if (bsz != null) {
      bsz = context.replaceTokens(bsz);
      try {
        batchSize = Integer.parseInt(bsz);
        if (batchSize == -1) batchSize = Integer.MIN_VALUE;
      } catch (NumberFormatException e) {
        LOG.warn("Invalid batch size: " + bsz);
      }
    }

    for (Map<String, String> map : context.getAllEntityFields()) {
      String n = map.get(DataImporter.COLUMN);
      String t = map.get(DataImporter.TYPE);
      if ("sint".equals(t) || "integer".equals(t)) fieldNameVsType.put(n, Types.INTEGER);
      else if ("slong".equals(t) || "long".equals(t)) fieldNameVsType.put(n, Types.BIGINT);
      else if ("float".equals(t) || "sfloat".equals(t)) fieldNameVsType.put(n, Types.FLOAT);
      else if ("double".equals(t) || "sdouble".equals(t)) fieldNameVsType.put(n, Types.DOUBLE);
      else if ("date".equals(t)) fieldNameVsType.put(n, Types.DATE);
      else if ("boolean".equals(t)) fieldNameVsType.put(n, Types.BOOLEAN);
      else if ("binary".equals(t)) fieldNameVsType.put(n, Types.BLOB);
      else fieldNameVsType.put(n, Types.VARCHAR);
    }
  }
示例#13
0
 // 采用静态初始化块来初始化Connection、Statement对象
 static {
   try {
     Properties props = new Properties();
     props.load(new FileInputStream("mysql.ini"));
     String drivers = props.getProperty("driver");
     String url = props.getProperty("url");
     String username = props.getProperty("user");
     String password = props.getProperty("pass");
     // 加载数据库驱动
     Class.forName(drivers);
     // 取得数据库连接
     conn = DriverManager.getConnection(url, username, password);
     stmt = conn.createStatement();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public String[] getCleanSql() {
    if (cleanSql == null) {
      // loop over all foreign key constraints
      List dropForeignKeysSql = new ArrayList();
      List createForeignKeysSql = new ArrayList();
      Iterator iter = configuration.getTableMappings();
      while (iter.hasNext()) {
        Table table = (Table) iter.next();
        if (table.isPhysicalTable()) {
          Iterator subIter = table.getForeignKeyIterator();
          while (subIter.hasNext()) {
            ForeignKey fk = (ForeignKey) subIter.next();
            if (fk.isPhysicalConstraint()) {
              // collect the drop key constraint
              dropForeignKeysSql.add(
                  fk.sqlDropString(
                      dialect,
                      properties.getProperty(Environment.DEFAULT_CATALOG),
                      properties.getProperty(Environment.DEFAULT_SCHEMA)));
              createForeignKeysSql.add(
                  fk.sqlCreateString(
                      dialect,
                      mapping,
                      properties.getProperty(Environment.DEFAULT_CATALOG),
                      properties.getProperty(Environment.DEFAULT_SCHEMA)));
            }
          }
        }
      }

      List deleteSql = new ArrayList();
      iter = configuration.getTableMappings();
      while (iter.hasNext()) {
        Table table = (Table) iter.next();
        deleteSql.add("delete from " + table.getName());
      }

      List cleanSqlList = new ArrayList();
      cleanSqlList.addAll(dropForeignKeysSql);
      cleanSqlList.addAll(deleteSql);
      cleanSqlList.addAll(createForeignKeysSql);

      cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
    }
    return cleanSql;
  }
 @Override
 public void setProperties(Properties properties) {
   String dialect = properties.getProperty("dialect");
   if (Strings.isNullOrEmpty(dialect)) {
     dialect = DEFAULT_DIALECT;
   }
   setDialect(dialect);
 }
  public void writePredictionToHDFS(Tuple input, double[] params, double prediction)
      throws Exception {

    try {

      Configuration conf = new Configuration();
      conf.set("fs.defaultFS", topologyConfig.getProperty("hdfs.url"));
      FileSystem fs = FileSystem.get(conf);

      Path pt =
          new Path(
              topologyConfig.getProperty("hdfs.url")
                  + "/tmp/predictions/"
                  + System.currentTimeMillis());

      BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true)));

      br.write("Original Event: " + input + "\n");
      br.write("\n");
      br.write("Certification status (from HBase): " + (params[0] == 1 ? "Y" : "N") + "\n");
      br.write("Wage plan (from HBase): " + (params[1] == 1 ? "Miles" : "Hours" + "\n"));
      br.write("Hours logged (from HBase): " + params[2] * 100 + "\n");
      br.write("Miles logged (from HBase): " + params[3] * 1000 + "\n");
      br.write("\n");
      br.write("Is Foggy? (from weather API): " + (params[4] == 1 ? "Y" : "N" + "\n"));
      br.write("Is Rainy? (from weather API): " + (params[5] == 1 ? "Y" : "N" + "\n"));
      br.write("Is Windy? (from weather API): " + (params[6] == 1 ? "Y" : "N" + "\n"));
      br.write("\n");
      br.write("\n");
      br.write("Input to Spark ML model: " + Arrays.toString(params) + "\n");
      br.write("\n");
      br.write("Prediction from Spark ML model: " + prediction + "\n");
      br.flush();
      br.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#17
0
文件: DBManager.java 项目: kone/kin
  /**
   * 初始化连接池
   *
   * @param props
   * @param show_sql
   */
  private static final void initDataSource(Properties dbProperties) {
    try {
      if (dbProperties == null) {
        dbProperties = new Properties();
        dbProperties.load(DBManager.class.getResourceAsStream(CONFIG_PATH));
      }
      // Class.forName(dbProperties.getProperty("jdbc.driverClass"));
      for (Object key : dbProperties.keySet()) {
        String skey = (String) key;
        if (skey.startsWith("jdbc.")) {
          String name = skey.substring(5);
          cp_props.put(name, dbProperties.getProperty(skey));
          if ("show_sql".equalsIgnoreCase(name)) {
            show_sql = "true".equalsIgnoreCase(dbProperties.getProperty(skey));
          }
        }
      }
      dataSource = (DataSource) Class.forName(cp_props.getProperty("datasource")).newInstance();
      if (dataSource.getClass().getName().indexOf("c3p0") > 0) {
        // Disable JMX in C3P0
        System.setProperty(
            "com.mchange.v2.c3p0.management.ManagementCoordinator",
            "com.mchange.v2.c3p0.management.NullManagementCoordinator");
      }
      log.info("Using DataSource : " + dataSource.getClass().getName());
      BeanUtils.populate(dataSource, cp_props);

      Connection conn = getConnection();
      DatabaseMetaData mdm = conn.getMetaData();
      log.info(
          "Connected to " + mdm.getDatabaseProductName() + " " + mdm.getDatabaseProductVersion());
      closeConnection();
    } catch (Exception e) {
      e.printStackTrace();
      throw new DBException(e);
    }
  }
示例#18
0
  public void testMajorVersion() {
    try {
      Properties props = P6TestUtil.loadProperties("P6Test.properties");
      String url = props.getProperty("url");

      Driver driver = DriverManager.getDriver(url);

      // make sure you have a p6 driver
      if (!(driver instanceof P6SpyDriverCore)) {
        fail("Expected to get back a p6spy driver, got back a " + driver);
      }

      // but make sure it's bound to something
      // these numbers will likely change over time :)
      assertEquals(1, driver.getMajorVersion());
      assertEquals(0, driver.getMinorVersion());

    } catch (Exception e) {
      e.printStackTrace(System.out);
      fail("unexpected exception: " + e);
    } finally {
    }
  }
  public void execute(String[] sqls) {
    String sql = null;
    String showSqlText = properties.getProperty("hibernate.show_sql");
    boolean showSql = ("true".equalsIgnoreCase(showSqlText));

    try {
      createConnection();
      statement = connection.createStatement();

      for (int i = 0; i < sqls.length; i++) {
        sql = sqls[i];
        String delimitedSql = sql + getSqlDelimiter();

        if (showSql) log.debug(delimitedSql);
        statement.executeUpdate(delimitedSql);
      }

    } catch (SQLException e) {
      e.printStackTrace();
      throw new RuntimeException("couldn't execute sql '" + sql + "'", e);
    } finally {
      closeConnection();
    }
  }
示例#20
0
 public static String GetFaultDescription(long fault, Locale locale) {
   if (fault != 0L) {
     String fmt = "000";
     StringBuffer sb = new StringBuffer();
     if ((fault & TYPE_MASK) == TYPE_J1708) {
       int mid = DTOBDFault.DecodeSystem(fault); // MID
       boolean isSid = DTOBDFault.IsJ1708_SID(fault);
       int pidSid = DTOBDFault.DecodePidSid(fault); // PID|SID "128/[s]123/1"
       int fmi = DTOBDFault.DecodeFMI(fault); // FMI
       Properties p =
           (j1587DescProvider != null)
               ? j1587DescProvider.getJ1587Descriptions(fault)
               : new Properties();
       // MID
       sb.append(
           NAME_MID
               + "("
               + StringTools.format(mid, fmt)
               + ") "
               + p.getProperty(NAME_MID_DESC, "")
               + "\n");
       // PID/SID
       if (isSid) {
         sb.append(
             NAME_SID
                 + "("
                 + StringTools.format(pidSid, fmt)
                 + ") "
                 + p.getProperty(NAME_SID_DESC, "")
                 + "\n");
       } else {
         sb.append(
             NAME_PID
                 + "("
                 + StringTools.format(pidSid, fmt)
                 + ") "
                 + p.getProperty(NAME_PID_DESC, "")
                 + "\n");
       }
       // FMI
       sb.append(
           NAME_FMI
               + "("
               + StringTools.format(fmi, fmt)
               + ") "
               + p.getProperty(NAME_FMI_DESC, ""));
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_J1939) {
       int spn = DTOBDFault.DecodeSystem(fault); // SPN
       int fmi = DTOBDFault.DecodeFMI(fault); // FMI
       Properties p = new Properties();
       // SPN
       sb.append(
           NAME_SPN
               + "("
               + StringTools.format(spn, fmt)
               + ") "
               + p.getProperty(NAME_SPN, "")
               + "\n");
       // FMI
       sb.append(
           NAME_FMI + "(" + StringTools.format(fmi, fmt) + ") " + p.getProperty(NAME_FMI, ""));
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_OBDII) {
       String dtc = DTOBDFault.GetFaultString(fault); // DTC
       Properties p = new Properties();
       // DTC
       sb.append(NAME_DTC + "(" + dtc + ") " + p.getProperty(NAME_DTC, ""));
       return sb.toString();
     }
   }
   return "";
 }
  public double[] enrichEvent(Tuple input) {
    double driverID = input.getIntegerByField("driverId");
    // int week = input.get
    Connection conn = null;
    try {
      // conn = phoenixDriver.connect("jdbc:phoenix:localhost:2181:/hbase-unsecure",new
      // Properties());
      conn =
          DriverManager.getConnection(
              "jdbc:phoenix:"
                  + topologyConfig.getProperty("hbase.zookeeper.server")
                  + ":2181:/hbase-unsecure");
      // input features to spark model
      double certified = 0,
          wageplan = 0,
          hours_logged = 0,
          miles_logged = 0,
          foggy = 0,
          rainy = 0,
          windy = 0;
      // get driver certification status and wage plan from hbase
      ResultSet rst =
          conn.createStatement()
              .executeQuery("select certified, wage_plan from drivers where driverid=" + driverID);

      while (rst.next()) {
        certified = rst.getString(1).equals("Y") ? 1 : 0;
        wageplan = rst.getString(1).equals("miles") ? 1 : 0;
      }
      // get driver fatigue status from timesheet table in hbase
      rst =
          conn.createStatement()
              .executeQuery(
                  "select hours_logged, miles_logged from timesheet"
                      + " where driverid="
                      + driverID
                      + " and week="
                      + getWeek(input));

      while (rst.next()) {
        hours_logged = rst.getInt(1);
        miles_logged = rst.getInt(2);
      }

      System.out.println("HOURS LOGGED " + hours_logged);
      System.out.println("MILES LOGGED " + miles_logged);

      // scale the hours & miles features for spark model
      hours_logged = hours_logged / 100;
      miles_logged = miles_logged / 1000;

      // get weather conditions - currently these are being simulated randomly, with a bias
      // towards more fog for dangerous drivers
      if (driverID == 12) // jamie
      foggy = new Random().nextInt(100) < 50 ? 1 : 0;
      else if (driverID == 11) // george
      foggy = new Random().nextInt(100) < 35 ? 1 : 0;
      else foggy = new Random().nextInt(100) < 12 ? 1 : 0;

      rainy = new Random().nextInt(100) < 20 ? 1 : 0;
      windy = new Random().nextInt(100) < 30 ? 1 : 0;

      // return the enriched event
      return new double[] {certified, wageplan, hours_logged, miles_logged, foggy, rainy, windy};

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);

    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
示例#22
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

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

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

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

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

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

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

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

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

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

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

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

        // Close the statement
        stmt.close();

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

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

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

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

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

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

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
  private void initializeDatabaseConnectionConfigurationParameters() {
    String propertyValue;
    Properties systemProperties;

    systemProperties = GlobalProperties.instance().getProperties();

    userAccount = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUserAccountKey);
    if (userAccount == null) {
      userAccount = DatabaseGlobals.DatabaseConnectionUserAccountDefault;
    }
    logger.info(DatabaseGlobals.UserAccountValueMsg + userAccount);

    password = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionPasswordKey);
    if (password == null) {
      password = DatabaseGlobals.DatabaseConnectionPasswordDefault;
    }
    logger.info(DatabaseGlobals.PasswordValueMsg + password);

    databaseName = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionDatabaseNameKey);
    if (databaseName == null) {
      databaseName = DatabaseGlobals.DatabaseConnectionDatabaseNameDefault;
    }
    logger.info(DatabaseGlobals.DatabaseNameValueMsg + databaseName);

    databaseHost = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionDatabaseHostKey);
    if (databaseHost == null) {
      databaseHost = DatabaseGlobals.DatabaseConnectionDatabaseHostDefault;
    }
    logger.info(DatabaseGlobals.DatabaseHostValueMsg + databaseHost);

    clientAppName =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionClientAppNameKey);
    if (clientAppName == null) {
      clientAppName = DatabaseGlobals.DatabaseConnectionClientAppNameDefault;
    }
    logger.info(DatabaseGlobals.ClientAppNameValueMsg + clientAppName);

    userMetaData = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUserMetaDataKey);
    if (userMetaData == null) {
      userMetaData = DatabaseGlobals.DatabaseConnectionUserMetaDataDefault;
    }
    logger.info(DatabaseGlobals.UserMetaDataValueMsg + userMetaData);

    useRepeatRead =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUseRepeatReadKey);
    if (useRepeatRead == null) {
      useRepeatRead = DatabaseGlobals.DatabaseConnectionUseRepeatReadDefault;
    }
    logger.info(DatabaseGlobals.UseRepeatReadValueMsg + useRepeatRead);

    charsetConverter =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionCharsetConverterKey);
    if (charsetConverter == null) {
      charsetConverter = DatabaseGlobals.DatabaseConnectionCharsetConverterDefault;
    }
    logger.info(DatabaseGlobals.CharsetConverterValueMsg + charsetConverter);

    connectionPoolDescription =
        systemProperties.getProperty(
            DatabaseGlobals.DatabaseConnectionConnectionPoolDescriptionKey);
    if (connectionPoolDescription == null) {
      connectionPoolDescription =
          DatabaseGlobals.DatabaseConnectionConnectionPoolDescriptionDefault;
    }
    logger.info(DatabaseGlobals.ConnectionPoolDescriptionValueMsg + connectionPoolDescription);

    propertyValue =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionConnectionPortKey);
    if (propertyValue == null) {
      connectionPort = DatabaseGlobals.DatabaseConnectionConnectionPortDefault;
      logger.info("Using default connectionPort value: " + connectionPort);
    } else {
      try {
        connectionPort = Integer.parseInt(propertyValue);
        logger.info("Using connectionPort value: " + connectionPort);
      } catch (NumberFormatException e) {
        connectionPort = DatabaseGlobals.DatabaseConnectionConnectionPortDefault;
        logger.info(
            "Error converting property value.  Using default connectionPort value: "
                + connectionPort);
      }
    }

    propertyValue =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionConnectionPoolSizeKey);
    if (propertyValue == null) {
      connectionPoolSize = DatabaseGlobals.DatabaseConnectionConnectionPoolSizeDefault;
      logger.info("Using default connectionPoolSize value: " + connectionPoolSize);
    } else {
      try {
        connectionPoolSize = Integer.parseInt(propertyValue);
        logger.info("Using connectionPoolSize value: " + connectionPoolSize);
      } catch (NumberFormatException e) {
        connectionPoolSize = DatabaseGlobals.DatabaseConnectionConnectionPoolSizeDefault;
        logger.info(
            "Error converting property value.  Using default connectionPoolSize value: "
                + connectionPoolSize);
      }
    }
  }
示例#24
0
文件: Dots.java 项目: rcuvgd/tmlinux
  /**
   * Read command line input and load config file, set config value to the instance of DotsConfig.
   */
  public static void loadConfig(String[] args) {
    int i;
    String configFileName = "./config.ini";
    String tmpString;
    String value;
    File configFile = null;
    StringTokenizer stk = null;
    Properties props = new Properties();
    String propString;

    /* Read command line input */
    for (i = 0; i < args.length; ) {
      String option = args[i++];

      if (option.equals("-config")) {
        configFileName = args[i++];
      } else if (option.equals("-case")) {
        TESTCASENAME = args[i++];
      } else if (option.equals("-?") || option.equals("-help")) {
        System.out.println("Usage:Dots [-option]");
        System.out.println("\t\t-config				Config file name");
        System.out.println("\t\t-case				Test case name");
        System.out.println("\t\t-help				Print this message");
        System.exit(0);
      } else {
        System.out.println("Expected Option Is Not Found!");
        System.out.println("Usage:	Dots -config [config file] -case [case name]");
        System.exit(0);
      }
    }

    TESTCASENAME = TESTCASENAME.toUpperCase();

    /* Check test case name */
    if (TESTCASENAME.equals("")) {
      System.out.println("Testcase Name Must Be Specified!");
      System.out.println("Usage:	Dots -config [config file] -case [case name]");
      System.exit(0);
    }
    if (!(TESTCASENAME.equals("BTCJ1")
        || TESTCASENAME.equals("BTCJ2")
        || TESTCASENAME.equals("BTCJ3")
        || TESTCASENAME.equals("BTCJ4")
        || TESTCASENAME.equals("BTCJ5")
        || TESTCASENAME.equals("BTCJ6")
        || TESTCASENAME.equals("BTCJ7")
        || TESTCASENAME.equals("BTCJ8")
        || TESTCASENAME.equals("ATCJ1")
        || TESTCASENAME.equals("ATCJ2"))) {
      System.out.println("Testcase Name Is Not Correct!");
      System.exit(0);
    }

    /* Load config file and set DotsConfig value */
    try {
      props.load(new FileInputStream(configFileName));

      if ((propString = props.getProperty("DURATION")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option DURATION Is Not Found!");
          System.exit(1);
        }
        stk = new StringTokenizer(propString, ":");
        if (stk.countTokens() > 1) {
          value = stk.nextToken().trim();
          tmpString = stk.nextToken().trim();
          DotsConfig.DURATION = Integer.parseInt(value) * 60 + Integer.parseInt(tmpString);
        } else DotsConfig.DURATION = Integer.parseInt(propString.trim()) * 60;
        if (DotsConfig.DURATION <= 1) {
          System.out.println("DURATION value is too small(<=1)!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option DURATION Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("CONCURRENT_CONNECTIONS")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option CONCURRENT_CONNECTIONS Is Not Found!");
          System.exit(1);
        }
        DotsConfig.CONNECTIONS = Integer.parseInt(propString.trim());
        if (DotsConfig.CONNECTIONS < 1) {
          System.out.println("CONCURRENT_CONNECTIONS value is too small(<1)!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option CONCURRENT_CONNECTIONS Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("CPU_TARGET")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option CPU_TARGET Is Not Found!");
          System.exit(1);
        }
        DotsConfig.CPU_TARGET = Integer.parseInt(propString.trim());
        if (DotsConfig.CPU_TARGET <= 10) {
          System.out.println("CPU_TARGET value is too small(<10)!");
          System.exit(1);
        }
        if (DotsConfig.CPU_TARGET > 100) {
          System.out.println("CPU_TARGET value is too large(>100)!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option CPU_TARGET Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("LOG_DIR")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option LOG_DIR Is Not Found!");
          System.exit(1);
        }
        DotsConfig.LOG_DIR = propString.trim();
      } else {
        System.out.println("Expected Config File Option LOG_DIR Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("AUTO_MODE")) != null) {
        if (propString.trim().equalsIgnoreCase("yes")) DotsConfig.AUTO_MODE = true;
        else if (propString.trim().equalsIgnoreCase("no")) DotsConfig.AUTO_MODE = false;
        else {
          System.out.println("AUTO_MODE format is not correct!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option AUTO_MODE Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("SUMMARY_INTERVAL")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option SUMMARY_INTERVAL Is Not Found!");
          System.exit(1);
        }
        DotsConfig.SUMMARY_INTERVAL = Integer.parseInt(propString.trim());
        if (DotsConfig.SUMMARY_INTERVAL < 1) {
          System.out.println("SUMMARY_INTERVAL value is too small(<1)!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option SUMMARY_INTERVAL Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("UserID")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option UserID Is Not Found!");
          System.exit(1);
        }
        DotsConfig.DB_UID = propString.trim();
      } else {
        System.out.println("Expected Config File Option UserID Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("Password")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option Password Is Not Found!");
          System.exit(1);
        }
        DotsConfig.DB_PASSWD = propString.trim();
      } else {
        System.out.println("Expected Config File Option Password Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("DriverClass")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option DriverClass Is Not Found!");
          System.exit(1);
        }
        DotsConfig.DRIVER_CLASS_NAME = propString.trim();
      } else {
        System.out.println("Expected Config File Option DriverClass Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("URL")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option URL Is Not Found!");
          System.exit(1);
        }
        DotsConfig.URL = propString.trim();
      } else {
        System.out.println("Expected Config File Option URL Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("SERVER_IP")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option SERVER_IP Is Not Found!");
          System.exit(1);
        }
        DotsConfig.SERVER_IP = propString.trim();
      } else {
        System.out.println("Expected Config File Option SERVER_IP Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("SERVER_PORT")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option SERVER_PORT Is Not Found!");
          System.exit(1);
        }
        DotsConfig.PERF_SVR_PORT = propString.trim();
      } else {
        System.out.println("Expected Config File Option SERVER_PORT Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("MAX_ROWS")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Expected Config File Option MAX_ROWS Is Not Found!");
          System.exit(1);
        }
        DotsConfig.MAX_ROWS = Integer.parseInt(propString.trim());
        if (DotsConfig.MAX_ROWS <= 1) {
          System.out.println("MAX_ROWS value is too small(<=1)!");
          System.exit(1);
        }
      } else {
        System.out.println("Expected Config File Option MAX_ROWS Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("MAX_LOGFILESIZE")) != null) {
        if (propString.trim().length() <= 0) {
          System.out.println("Excepted Config File Option MAX_LOGFILESIZE Is Not Found!");
          System.exit(1);
        }
        DotsConfig.MAX_LOGFILESIZE = Integer.parseInt(propString.trim());
        if (DotsConfig.MAX_LOGFILESIZE <= 102400) {
          System.out.println("MAX_LOGFILESIZE value is too small(<=100K)");
          System.exit(1);
        }
        if (DotsConfig.MAX_LOGFILESIZE > 1073741824) { // 1G
          System.out.println("MAX_LOGFILESIZE value is too large(>1G)");
          System.exit(1);
        }
      } else {
        System.out.println("Excepted Config File Option MAX_LOGFILESIZE Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("CREATIONINTERVAL")) != null) {
        DotsConfig.INTERVAL = Integer.parseInt(propString.trim());
        if (DotsConfig.INTERVAL > 5) {
          System.out.println("CREATIONINTERVAL value is too large(>5min)");
          System.exit(1);
        }
        if (DotsConfig.INTERVAL < 1) {
          System.out.println("CREATIONPINTERVAL value is too small(<1min");
          System.exit(1);
        }
      } else {
        System.out.println("Excepted Config File Option CREATIONINTERVAL Is Not Found!");
        System.exit(1);
      }

      if ((propString = props.getProperty("RUN_AUTO")) != null) {
        if (propString.trim().equalsIgnoreCase("yes")) DotsConfig.RUN_AUTO = true;
        else if (propString.trim().equalsIgnoreCase("no")) DotsConfig.RUN_AUTO = false;
        else {
          System.out.println("RUN_AUTO format is not correct!");
          System.exit(1);
        }
      } else {
        DotsConfig.RUN_AUTO = false;
      }

      DotsConfig.THRDGRP = new ThreadGroup("DBAccess");
      DotsConfig.CPU_USAGE = 0;
      DotsConfig.QUERYCOUNT = 0;
      DotsConfig.INSERTCOUNT = 0;
      DotsConfig.DELETECOUNT = 0;
      DotsConfig.UPDATECOUNT = 0;
      DotsConfig.FAILEDCOUNT = 0;
    } catch (NumberFormatException e) {
      System.out.println("Config File Number Format Error!");
      e.printStackTrace();
      System.exit(1);
    } catch (IOException e) {
      System.out.println("Read Config File Error!");
      e.printStackTrace();
      System.exit(1);
    }
  }
示例#25
0
  static void initJDBC() {

    try {

      // load the ini file
      Properties ini = new Properties();
      ini.load(new FileInputStream(System.getProperty("prop")));

      // display the values we need
      System.out.println("driver=" + ini.getProperty("driver"));
      System.out.println("conn=" + ini.getProperty("conn"));
      System.out.println("user="******"user"));
      System.out.println("password=******");
      name = ini.getProperty("name");
      // Register jdbcDriver
      Class.forName(ini.getProperty("driver"));

      // make connection
      conn =
          DriverManager.getConnection(
              ini.getProperty("conn"), ini.getProperty("user"), ini.getProperty("password"));
      conn.setAutoCommit(false);

      // Create Statement
      stmt = conn.createStatement();

      distPrepStmt =
          conn.prepareStatement(
              "INSERT INTO district "
                  + " (d_id, d_w_id, d_ytd, d_tax, d_next_o_id, d_name, d_street_1, d_street_2, d_city, d_state, d_zip) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

      itemPrepStmt =
          conn.prepareStatement(
              "INSERT INTO item "
                  + " (i_id, i_name, i_price, i_data, i_im_id) "
                  + "VALUES (?, ?, ?, ?, ?)");

      custPrepStmt =
          conn.prepareStatement(
              "INSERT INTO customer "
                  + " (c_id, c_d_id, c_w_id, "
                  + "c_discount, c_credit, c_last, c_first, c_credit_lim, "
                  + "c_balance, c_ytd_payment, c_payment_cnt, c_delivery_cnt, "
                  + "c_street_1, c_street_2, c_city, c_state, c_zip, "
                  + "c_phone, c_since, c_middle, c_data) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

      histPrepStmt =
          conn.prepareStatement(
              "INSERT INTO history "
                  + " (h_c_id, h_c_d_id, h_c_w_id, "
                  + "h_d_id, h_w_id, "
                  + "h_date, h_amount, h_data) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

      ordrPrepStmt =
          conn.prepareStatement(
              "INSERT INTO oorder "
                  + " (o_id, o_w_id,  o_d_id, o_c_id, "
                  + "o_carrier_id, o_ol_cnt, o_all_local, o_entry_d) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

      orlnPrepStmt =
          conn.prepareStatement(
              "INSERT INTO order_line "
                  + " (ol_w_id, ol_d_id, ol_o_id, "
                  + "ol_number, ol_i_id, ol_delivery_d, "
                  + "ol_amount, ol_supply_w_id, ol_quantity, ol_dist_info) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

      nworPrepStmt =
          conn.prepareStatement(
              "INSERT INTO new_order " + " (no_w_id, no_d_id, no_o_id) " + "VALUES (?, ?, ?)");

      stckPrepStmt =
          conn.prepareStatement(
              "INSERT INTO stock "
                  + " (s_i_id, s_w_id, s_quantity, s_ytd, s_order_cnt, s_remote_cnt, s_data, "
                  + "s_dist_01, s_dist_02, s_dist_03, s_dist_04, s_dist_05, "
                  + "s_dist_06, s_dist_07, s_dist_08, s_dist_09, s_dist_10) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

      whsePrepStmt =
          conn.prepareStatement(
              "INSERT INTO warehouse "
                  + " (w_id, w_ytd, w_tax, w_name, w_street_1, w_street_2, w_city, w_state, w_zip) "
                  + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

    } catch (SQLException se) {
      System.out.println(se.getMessage());
      transRollback();

    } catch (Exception e) {
      e.printStackTrace();
      transRollback();
    } // end try
  } // end initJDBC()
示例#26
0
  protected Callable<Connection> createConnectionFactory(
      final Context context, final Properties initProps) {
    //    final VariableResolver resolver = context.getVariableResolver();
    resolveVariables(context, initProps);
    final String jndiName = initProps.getProperty(JNDI_NAME);
    final String url = initProps.getProperty(URL);
    final String driver = initProps.getProperty(DRIVER);

    if (url == null && jndiName == null)
      throw new DataImportHandlerException(SEVERE, "JDBC URL or JNDI name has to be specified");

    if (driver != null) {
      try {
        DocBuilder.loadClass(driver, context.getSolrCore());
      } catch (ClassNotFoundException e) {
        wrapAndThrow(SEVERE, e, "Could not load driver: " + driver);
      }
    } else {
      if (jndiName == null) {
        throw new DataImportHandlerException(
            SEVERE, "One of driver or jndiName must be specified in the data source");
      }
    }

    String s = initProps.getProperty("maxRows");
    if (s != null) {
      maxRows = Integer.parseInt(s);
    }

    return factory =
        new Callable<Connection>() {
          @Override
          public Connection call() throws Exception {
            LOG.info(
                "Creating a connection for entity "
                    + context.getEntityAttribute(DataImporter.NAME)
                    + " with URL: "
                    + url);
            long start = System.nanoTime();
            Connection c = null;

            if (jndiName != null) {
              c = getFromJndi(initProps, jndiName);
            } else if (url != null) {
              try {
                c = DriverManager.getConnection(url, initProps);
              } catch (SQLException e) {
                // DriverManager does not allow you to use a driver which is not loaded through
                // the class loader of the class which is trying to make the connection.
                // This is a workaround for cases where the user puts the driver jar in the
                // solr.home/lib or solr.home/core/lib directories.
                Driver d =
                    (Driver) DocBuilder.loadClass(driver, context.getSolrCore()).newInstance();
                c = d.connect(url, initProps);
              }
            }
            if (c != null) {
              try {
                initializeConnection(c, initProps);
              } catch (SQLException e) {
                try {
                  c.close();
                } catch (SQLException e2) {
                  LOG.warn("Exception closing connection during cleanup", e2);
                }

                throw new DataImportHandlerException(
                    SEVERE, "Exception initializing SQL connection", e);
              }
            }
            LOG.info(
                "Time taken for getConnection(): "
                    + TimeUnit.MILLISECONDS.convert(
                        System.nanoTime() - start, TimeUnit.NANOSECONDS));
            return c;
          }

          private void initializeConnection(Connection c, final Properties initProps)
              throws SQLException {
            if (Boolean.parseBoolean(initProps.getProperty("readOnly"))) {
              c.setReadOnly(true);
              // Add other sane defaults
              c.setAutoCommit(true);
              c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
              c.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
            }
            if (!Boolean.parseBoolean(initProps.getProperty("autoCommit"))) {
              c.setAutoCommit(false);
            }
            String transactionIsolation = initProps.getProperty("transactionIsolation");
            if ("TRANSACTION_READ_UNCOMMITTED".equals(transactionIsolation)) {
              c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            } else if ("TRANSACTION_READ_COMMITTED".equals(transactionIsolation)) {
              c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            } else if ("TRANSACTION_REPEATABLE_READ".equals(transactionIsolation)) {
              c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            } else if ("TRANSACTION_SERIALIZABLE".equals(transactionIsolation)) {
              c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            } else if ("TRANSACTION_NONE".equals(transactionIsolation)) {
              c.setTransactionIsolation(Connection.TRANSACTION_NONE);
            }
            String holdability = initProps.getProperty("holdability");
            if ("CLOSE_CURSORS_AT_COMMIT".equals(holdability)) {
              c.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
            } else if ("HOLD_CURSORS_OVER_COMMIT".equals(holdability)) {
              c.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
            }
          }

          private Connection getFromJndi(final Properties initProps, final String jndiName)
              throws NamingException, SQLException {

            Connection c = null;
            InitialContext ctx = new InitialContext();
            Object jndival = ctx.lookup(jndiName);
            if (jndival instanceof javax.sql.DataSource) {
              javax.sql.DataSource dataSource = (javax.sql.DataSource) jndival;
              String user = (String) initProps.get("user");
              String pass = (String) initProps.get("password");
              if (user == null || user.trim().equals("")) {
                c = dataSource.getConnection();
              } else {
                c = dataSource.getConnection(user, pass);
              }
            } else {
              throw new DataImportHandlerException(
                  SEVERE, "the jndi name : '" + jndiName + "' is not a valid javax.sql.DataSource");
            }
            return c;
          }
        };
  }
 private synchronized String getSqlDelimiter() {
   if (sqlDelimiter == null) {
     sqlDelimiter = properties.getProperty("jbpm.sql.delimiter", ";");
   }
   return sqlDelimiter;
 }
 public DriverManagerConnectionProvider(Properties prop) throws ClassNotFoundException {
   this.prop = prop;
   Class.forName(prop.getProperty("driver_class"));
   pool_size = Integer.parseInt(prop.getProperty("pool_size"));
 }
  /*
   * Builds sensors table from list of sensors currently loaded in the system
   * */
  public static boolean buildGeoIndex() {

    boolean success = true;

    sensors = new Vector<String>();
    coordinates = new Vector<Point>();

    getListOfSensors();

    Properties properties = loadProperties();

    if (properties != null) {
      try {
        dburl = properties.getProperty("dburl");
        dbuser = properties.getProperty("dbuser");
        dbpass = properties.getProperty("dbpass");

        Connection conn = connect(dburl, dbuser, dbpass);

        // ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
        // ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");

        String st_create_table =
            "DROP INDEX IF EXISTS gist_sensors;"
                + " DROP TABLE IF EXISTS sensors;"
                + " CREATE TABLE sensors ( \"name\" character(255) NOT NULL, \"location\" geometry NOT NULL );"
                + " CREATE INDEX gist_sensors ON sensors USING GIST ( location ); ";

        logger.warn("Running query: " + st_create_table);

        PreparedStatement prepareStatement = conn.prepareStatement(st_create_table);
        prepareStatement.execute();
        prepareStatement.close();

        for (int i = 0; i < coordinates.size(); i++) {
          String insert =
              "insert into sensors values ( '"
                  + sensors.get(i)
                  + "', ST_MakePoint("
                  + coordinates.get(i).getX()
                  + " , "
                  + coordinates.get(i).getY()
                  + " , "
                  + coordinates.get(i).getZ()
                  + ") );";
          PreparedStatement ps = conn.prepareStatement(insert);
          ps.execute();
          ps.close();
          logger.warn(insert);
        }

        Statement s = conn.createStatement();
        ResultSet r = s.executeQuery("select location, name from sensors");
        while (r.next()) {
          PGgeometry geom = (PGgeometry) r.getObject(1);
          String name = r.getString(2);
          logger.warn("Geometry " + geom.toString() + " : " + name);
        }
        s.close();
        conn.close();

      } catch (SQLException e) {
        logger.warn(e.getMessage(), e);
        success = false;
      } catch (ClassNotFoundException e) {
        logger.warn(e.getMessage(), e);
        success = false;
      }
    } else {
      logger.warn("Couldn't load properties files for PostGIS");
      success = false;
    }

    return success;
  }
  // implement FarragoMedDataServer
  public FarragoMedColumnSet newColumnSet(
      String[] localName,
      Properties tableProps,
      FarragoTypeFactory typeFactory,
      RelDataType rowType,
      Map<String, Properties> columnPropMap)
      throws SQLException {
    if (rowType == null) {
      rowType = createMockRowType(typeFactory);
    }

    assert (rowType.getFieldList().size() == 1);
    RelDataType type = rowType.getFields()[0].getType();
    assert (!type.isNullable());
    assert (typeFactory.getClassForPrimitive(type) != null);

    // TODO jvs 5-Aug-2005:  clean up usage of server properties
    // as defaults

    long nRows = -1;
    String rowCountSql = tableProps.getProperty(PROP_ROW_COUNT_SQL);
    if (rowCountSql != null) {
      // Attempt to issue a loopback query into Farrago to
      // get the number of rows to produce.
      DataSource loopbackDataSource = getLoopbackDataSource();
      Connection connection = null;
      if (loopbackDataSource != null) {
        try {
          connection = loopbackDataSource.getConnection();
          Statement stmt = connection.createStatement();
          ResultSet resultSet = stmt.executeQuery(rowCountSql);
          if (resultSet.next()) {
            nRows = resultSet.getLong(1);
          }
        } finally {
          // It's OK not to clean up stmt and resultSet;
          // connection.close() will do that for us.
          if (connection != null) {
            connection.close();
          }
        }
      }
    }

    if (nRows == -1) {
      nRows =
          getLongProperty(
              tableProps, PROP_ROW_COUNT, getLongProperty(getProperties(), PROP_ROW_COUNT, 10));
    }

    String executorImpl =
        tableProps.getProperty(
            PROP_EXECUTOR_IMPL, getProperties().getProperty(PROP_EXECUTOR_IMPL, PROPVAL_JAVA));
    assert (executorImpl.equals(PROPVAL_JAVA) || executorImpl.equals(PROPVAL_FENNEL));

    String udxSpecificName = tableProps.getProperty(PROP_UDX_SPECIFIC_NAME);

    if (udxSpecificName != null) {
      assert (executorImpl.equals(PROPVAL_JAVA));
    }

    checkNameMatch(getForeignSchemaName(), tableProps.getProperty(PROP_SCHEMA_NAME));

    checkNameMatch(getForeignTableName(), tableProps.getProperty(PROP_TABLE_NAME));

    return new MedMockColumnSet(this, localName, rowType, nRows, executorImpl, udxSpecificName);
  }