示例#1
1
 // ----This function gets as a parameter a list of terms----
 // ---------the function returns a list of tweet ids from collection search_results-----------
 // ----------------------------------------------------------------------------------------
 public LinkedList<String> get_tweets(LinkedList<String> search_terms) {
   log4j.info("starting function get_tweets");
   LinkedList<String> result = new LinkedList<String>();
   Iterator<String> terms = search_terms.iterator();
   long curr_time = System.currentTimeMillis();
   long min_time = curr_time - this.frame_time; // time below min_time will be ignored
   int count_all = 0; // tweets counter
   while (terms.hasNext()) {
     int count = 0;
     String term = terms.next();
     DBObject st = new BasicDBObject();
     try {
       st.put("searchword", term);
       DBObject obj = this.collsr.findOne(st); // look for the relevant document
       String[] tweets_plus_time =
           obj.get("tweets")
               .toString()
               .split(","); // make an array, even indexes are tweet_id's and odd indexes are their
       // time
       String new_string =
           ""; // the string to replace eventually the current field 'tweets' in the document
       for (int i = 0;
           i < tweets_plus_time.length - 1;
           i += 2) // go over the tweet ids from the document
       {
         if (Long.parseLong(tweets_plus_time[i + 1])
             >= min_time) // tweet time is within the time frame
         {
           result.add(tweets_plus_time[i]); // add tweet id to result
           count++;
           if (new_string == "") // add tweet information without leading comma
           {
             new_string += tweets_plus_time[i] + "," + tweets_plus_time[i + 1];
             // count++;
           } else // add tweet information with leading comma
           {
             new_string += "," + tweets_plus_time[i] + "," + tweets_plus_time[i + 1];
           }
         }
       }
       count_all += count;
       log4j.info(count + " tweets for term: " + term);
       obj.put("tweets", new_string); // replace 'tweets' field
       obj.put("last_update", System.currentTimeMillis()); // update time of update
       collsr.save(obj);
     } catch (NullPointerException e) {
       log4j.info("search_term: " + term + ", is not in collection search_results");
     }
   }
   log4j.info("over_all there are " + count_all + " tweets to compare!!!");
   log4j.info("ending function get_tweets");
   return result;
 }
示例#2
1
  // ----This function getting search term and tweet id ----
  // ----the function adding the tweet id and the time of search to the collection search_results--
  public void SearchResultId(String searchword, String tweet_id) {
    log4j.info(
        "starting function SearchResultId with parameters: searchword = "
            + searchword
            + ", tweet_id"
            + tweet_id);
    try {
      DBObject searchobj = new BasicDBObject();
      searchobj.put("searchword", searchword);
      DBObject obj = this.collsr.findOne(searchobj); // get document if exists
      long min_time =
          System.currentTimeMillis() - this.frame_time; // minimum time to keep in document

      if (Long.parseLong(obj.get("last_update").toString()) < min_time) {
        // last updated before minimum time - checking each tweet
        String[] tweets = obj.get("tweets").toString().split(",");
        String new_string = "";
        for (int i = 1; i < tweets.length; i += 2) // going over all existing tweets in document
        {
          if (Long.parseLong(tweets[i]) >= min_time) {
            // tweet stays in document
            if (new_string == "") {
              // no leading comma
              new_string += tweets[i - 1] + "," + tweets[i];
            } else {
              // leading comma
              new_string += "," + tweets[i - 1] + "," + tweets[i];
            }
          }
        }
        obj.put("tweets", new_string + "," + tweet_id);
        obj.put("last_update", System.currentTimeMillis());
        // obj.put("in_process", 0);
        this.collsr.save(obj);
      } else {
        // last updated after minimum time - just adding tweet
        obj.put("tweets", obj.get("tweets").toString() + "," + tweet_id);
        this.collsr.save(obj);
      }

    } catch (NullPointerException e) {
      // there is no document yet, creating one
      DBObject searchobj = new BasicDBObject();
      searchobj.put("searchword", searchword);
      searchobj.put("tweets", tweet_id);
      searchobj.put("last_update", System.currentTimeMillis());
      this.collsr.save(searchobj);
    }
    log4j.info("ending function SearchResultId");
  }
示例#3
0
  /**
   * Compare approximate and exact diameter computation. Approximate is very fast but provides only
   * a rough upper bound. For a discretized pairwise distance distribution, this is absolutely
   * sufficient.
   */
  public void testMaxPhaseSpaceDiameter() {

    int tsLen = 25000;
    TimeSeriesGenerator tsg = new TimeSeriesGenerator(1, tsLen, "lorenz");
    double[][][][] trajectories = tsg.getAllTrajectories();
    double[][] ts = trajectories[4][0];
    System.out.println("Computing max phase space diameter.");
    long tic = System.currentTimeMillis();
    double diam = PhaseSpaceDistribution.maxPhaseSpaceDiameter(ts, ts);
    System.out.println("diam = " + diam);
    long toc = System.currentTimeMillis();
    System.out.println(toc - tic);

    System.out.println("Computing max phase space diameter, approximate.");
    tic = System.currentTimeMillis();
    double diamApprox = PhaseSpaceDistribution.maxPhaseSpaceDiameterApproximate(ts);
    System.out.println("diamApprox = " + diamApprox);
    toc = System.currentTimeMillis();
    System.out.println(toc - tic);
    System.out.println("Relative error: " + (Math.abs(diamApprox - diam) / diam));

    //        GeometryFactory factory = new GeometryFactory(new
    // PrecisionModel(PrecisionModel.FIXED));
    //        Point[] points = new Point[tsLen];
    //        for (int i = 0; i < tsLen; i++) {
    //            Coordinate[] coordinates = new Coordinate[ts.length];
    //            for (int j = 0; j < ts.length; j++) {
    //                coordinates[j] = new Co
    //            }
    //            points[i] = new Point(new CoordinateArraySequence(coordinates), factory);
    //        }
    //        MultiPoint data = new MultiPoint(points, factory);
    //        MinimumDiameter minimumDiameter = new MinimumDiameter(geom);

  }
 public static void main(String[] args) throws Exception {
   long start = System.currentTimeMillis();
   //		analysis("Data_structure");
   facetAnalysis("Data_structure");
   long end = System.currentTimeMillis();
   System.out.println("总共用时: " + (end - start) / 1000 + " 秒...");
 }
示例#5
0
  @Override
  public void callInsert(String statementString) throws SQLException {
    /*        String sqlString = statementString;
    CallableStatement statement = sqlConn.prepareCall(sqlString);
    statement.execute();
    int iStatus = statement.getInt(1);
    sqlConn.commit();*/
    Statement statement = sqlConn.createStatement();
    //        statement.executeU(statementString);
    Statement s = null;
    try {
      s = sqlConn.createStatement();
    } catch (SQLException se) {
      System.out.println(
          "We got an exception while creating a statement:"
              + "that probably means we're no longer connected.");
      se.printStackTrace();
      System.exit(1);
    }

    int m = 0;

    try {
      m = s.executeUpdate(statementString);
    } catch (SQLException se) {
      System.out.println(
          "We got an exception while executing our query:"
              + "that probably means our SQL is invalid");
      se.printStackTrace();
      System.exit(1);
    }

    System.out.println("Successfully modified " + m + " rows.\n");
  }
示例#6
0
 public void saveAllSync() {
   long start = System.currentTimeMillis();
   save();
   closeConn();
   pl.getLogger()
       .log(Level.INFO, "Saved and closed in {0}ms", (System.currentTimeMillis() - start));
 }
示例#7
0
文件: Query.java 项目: kptran/sql2o
  public Table executeAndFetchTable() {
    ResultSet rs;
    long start = System.currentTimeMillis();
    try {
      rs = statement.executeQuery();
      long afterExecute = System.currentTimeMillis();
      Table table = TableFactory.createTable(rs, this.isCaseSensitive());
      long afterClose = System.currentTimeMillis();

      logger.info(
          "total: {} ms, execution: {} ms, reading and parsing: {} ms; executed fetch table [{}]",
          new Object[] {
            afterClose - start,
            afterExecute - start,
            afterClose - afterExecute,
            this.getName() == null ? "No name" : this.getName()
          });

      return table;
    } catch (SQLException e) {
      throw new Sql2oException("Error while executing query", e);
    } finally {
      closeConnectionIfNecessary();
    }
  }
示例#8
0
 private boolean AidedIn(SaoWorker w)
 {
   BatSQL bSQL = new BatSQL();
   boolean success = false;
   String id    = w.getUserID();
   String q = "select * from aidedin where USERID='" + id + "'";
   ResultSet rs = bSQL.query(q);
       
   try
   {
     boolean more = rs.next();
     if (more) { success = true; }
   } //end of try
   catch (SQLException ex)
   {
     System.out.println("!*******SQLException caught*******!");
     while (ex != null)
     {
       System.out.println ("SQLState: " + ex.getSQLState ());
       System.out.println ("Message:  " + ex.getMessage ());
       System.out.println ("Vendor:   " + ex.getErrorCode ());
       ex = ex.getNextException ();
       System.out.println ("");
     }
     System.exit(0);
   } //end catching SQLExceptions
   catch (java.lang.Exception ex)
   {
     System.out.println("!*******Exception caught*******!");
     System.exit(0);
   } //end catching other Exceptions
   bSQL.disconnect();
   return success;
 } //end of AidedIn?
  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);
    }
  }
示例#10
0
  @Test
  public void testUpsertDateValues() throws Exception {
    long ts = nextTimestamp();
    Date now = new Date(System.currentTimeMillis());
    ensureTableCreated(getUrl(), TestUtil.PTSDB_NAME, null, ts - 2);
    Properties props = new Properties();
    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String dateString = "1999-01-01 02:00:00";
    PreparedStatement upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('aaa','bbb',to_date('" + dateString + "'))");
    int rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('ccc','ddd',current_date())");
    rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    conn.commit();

    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1
    conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String select = "SELECT date,current_date() FROM ptsdb";
    ResultSet rs = conn.createStatement().executeQuery(select);
    Date then = new Date(System.currentTimeMillis());
    assertTrue(rs.next());
    Date date = DateUtil.parseDate(dateString);
    assertEquals(date, rs.getDate(1));
    assertTrue(rs.next());
    assertTrue(rs.getDate(1).after(now) && rs.getDate(1).before(then));
    assertFalse(rs.next());
  }
  private void putUpdateStoredBlock(StoredBlock storedBlock, boolean wasUndoable)
      throws SQLException {
    try {
      PreparedStatement s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO headers(hash, chainWork, height, header, wasUndoable)"
                      + " VALUES(?, ?, ?, ?, ?)");
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(1, hashBytes);
      s.setBytes(2, storedBlock.getChainWork().toByteArray());
      s.setInt(3, storedBlock.getHeight());
      s.setBytes(4, storedBlock.getHeader().unsafeRimbitSerialize());
      s.setBoolean(5, wasUndoable);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      // It is possible we try to add a duplicate StoredBlock if we upgraded
      // In that case, we just update the entry to mark it wasUndoable
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)) || !wasUndoable) throw e;

      PreparedStatement s =
          conn.get().prepareStatement("UPDATE headers SET wasUndoable=? WHERE hash=?");
      s.setBoolean(1, true);
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(2, hashBytes);
      s.executeUpdate();
      s.close();
    }
  }
 // 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);
   }
 }
示例#13
0
文件: Query.java 项目: aaberg/sql2o
  public Connection executeBatch() throws Sql2oException {
    long start = System.currentTimeMillis();
    try {
      logExecution();
      PreparedStatement statement = buildPreparedStatement();
      connection.setBatchResult(statement.executeBatch());
      this.currentBatchRecords = 0;
      try {
        connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null);
        connection.setCanGetKeys(this.returnGeneratedKeys);
      } catch (SQLException sqlex) {
        throw new Sql2oException(
            "Error while trying to fetch generated keys from database. If you are not expecting any generated keys, fix this error by setting the fetchGeneratedKeys parameter in the createQuery() method to 'false'",
            sqlex);
      }
    } catch (Throwable e) {
      this.connection.onException();
      throw new Sql2oException("Error while executing batch operation: " + e.getMessage(), e);
    } finally {
      closeConnectionIfNecessary();
    }

    long end = System.currentTimeMillis();
    logger.debug(
        "total: {} ms; executed batch [{}]",
        new Object[] {end - start, this.getName() == null ? "No name" : this.getName()});

    return this.connection;
  }
示例#14
0
  @Override
  public void run() {

    nextTickTime = System.currentTimeMillis() + tickTime;
    // final String oldThreadName=Thread.currentThread().getName();
    try {
      currentThread = Thread.currentThread();
      lastStart = System.currentTimeMillis();
      lastClient = null;
      final boolean allSuspended = CMLib.threads().isAllSuspended();
      if ((CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) && (!allSuspended)) {
        for (final Iterator<TickClient> i = tickers(); i.hasNext(); ) {
          final TickClient client = i.next();
          lastClient = client;
          // if(client.getCurrentTickDown()<=1)
          // currentThread.setName(oldThreadName+":"+getName()+":"+client.getName());
          if (client.tickTicker(false)) {
            delTicker(client); // cant do i.remove, its an streeset
          }
        }
      }
    } finally {
      lastStop = System.currentTimeMillis();
      milliTotal += (lastStop - lastStart);
      tickTotal++;
      currentThread = null;
      // Thread.currentThread().setName(oldThreadName);
    }
    if (tickers.size() == 0) {
      if (CMLib.threads() instanceof ServiceEngine)
        ((ServiceEngine) CMLib.threads()).delTickGroup(this);
    }
  }
示例#15
0
 /** low-level test for critical performance issue described in bug [3078236] */
 public void testExceptionChaining() throws SQLException {
   for (boolean warn : new boolean[] {false, true}) {
     long base = 0;
     for (int size : new int[] {10, 25, 50, 100, 500}) {
       SQLDiagnostic diag = new SQLDiagnostic(0);
       System.gc();
       long start = System.nanoTime();
       for (int c = 0; c < size * 1000; c++) {
         if (warn) {
           diag.addWarning(new SQLWarning());
         } else {
           diag.addException(new SQLException());
         }
       }
       long avg = (System.nanoTime() - start) / size; // nanoseconds per 1000 exceptions
       // ensure time grows linear (allows factor 2 deviation, but not exponential effects)
       assertTrue(
           "chaining "
               + size * 1000
               + (warn ? " warnings" : " exceptions")
               + " slowed down too much ("
               + base / 1000000
               + " ms -> "
               + avg / 1000000
               + " ms per 1000)",
           base == 0 || avg < base * 2);
       base = base == 0 ? avg : base;
     }
   }
 }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
示例#17
0
文件: Query.java 项目: aaberg/sql2o
 public ResultSetIterableBase() {
   try {
     start = System.currentTimeMillis();
     logExecution();
     rs = buildPreparedStatement().executeQuery();
     afterExecQuery = System.currentTimeMillis();
   } catch (SQLException ex) {
     throw new Sql2oException("Database error: " + ex.getMessage(), ex);
   }
 }
示例#18
0
 protected void check() {
   if (map == null) {
     Connection connection = null;
     Statement statement = null;
     ResultSet results = null;
     try {
       connection = dataSource.getConnection();
       statement = connection.createStatement();
       long start = System.currentTimeMillis();
       String s = getFindSql(identifier);
       if (log.isTraceEnabled()) {
         log.trace("About to execute " + s + " because ", new Exception());
       }
       results = statement.executeQuery(s);
       ResultSetMetaData meta = results.getMetaData();
       map = new HashMap<String, String>();
       if (results.next()) {
         for (int i = 1; i <= meta.getColumnCount(); i++) {
           String value = org.mmbase.util.Casting.toString(results.getString(i));
           map.put(meta.getColumnName(i).toLowerCase(), value);
         }
       }
       long duration = (System.currentTimeMillis() - start);
       if (duration > 500) {
         log.warn("Executed " + s + " in " + duration + " ms");
       } else if (duration > 100) {
         log.debug("Executed " + s + " in " + duration + " ms");
       } else {
         log.trace("Executed " + s + " in " + duration + " ms");
       }
     } catch (Exception e) {
       throw new RuntimeException(e.getMessage(), e);
     } finally {
       if (results != null)
         try {
           results.close();
         } catch (Exception e) {
         }
       if (statement != null)
         try {
           statement.close();
         } catch (Exception e) {
         }
       if (connection != null)
         try {
           connection.close();
         } catch (Exception e) {
         }
     }
   }
 }
示例#19
0
  public static void main(String[] args) throws Exception {

    long time = System.currentTimeMillis();

    // setLocations
    int numberlocations = 2;
    lonlats = new double[numberlocations * 2];
    lonlats = functions.setLocations(numberlocations);

    // create FileWriter
    FileWriter output = functions.createFileWriter();
    functions.createFileWriterLocs(numberlocations, lonlats);

    // initialize variables
    double[] criteria = new double[numberlocations];
    for (int i = 0; i < numberlocations; i++) {
      criteria[i] = 0;
    }

    polys = (ArrayList<Double>[]) new ArrayList[numberlocations + 1];
    for (int i = 0; i < polys.length; i++) polys[i] = new ArrayList<Double>();

    polysGeometry = (ArrayList<String>[]) new ArrayList[3];
    for (int i = 0; i < polysGeometry.length; i++) polysGeometry[i] = new ArrayList<String>();

    allocPolys = (ArrayList<Integer>[]) new ArrayList[numberlocations];
    for (int i = 0; i < allocPolys.length; i++) allocPolys[i] = new ArrayList<Integer>();

    geomAllocPolys = (ArrayList<String>[]) new ArrayList[numberlocations];
    for (int i = 0; i < geomAllocPolys.length; i++) geomAllocPolys[i] = new ArrayList<String>();

    //		//calculate number of Polygons in that region
    int numberpolygons = functions.getNrOrSum(true);
    int sumcriteria = functions.getNrOrSum(false);

    //		//alocate Polygons to locations
    allocatePolygons(numberlocations, numberpolygons, criteria, sumcriteria);

    //		//Create Shapefile with allocated poylgons
    for (int i = 0; i < numberlocations; i++) {
      functions.writePolygon(output, allocPolys[i], geomAllocPolys[i], i + 1);
    }
    //		System.out.println("1:"+criteria[0]+",2:"+criteria[1]+"3:"+criteria[2]+"4:"+criteria[3]);
    System.out.println("1:" + criteria[0] + ",2:" + criteria[1]);
    System.out.println("Time for whole algorithm:" + (System.currentTimeMillis() - time) + " ms");
    //
    output.flush();
    output.close();

    System.out.println("successfully ended");
  }
示例#20
0
 private static Connection getConnection() throws SQLException {
   try {
     Class.forName("com.mysql.jdbc.Driver");
   } catch (ClassNotFoundException ex) {
     Logger.getLogger(DBSample1.class.getName()).log(Level.SEVERE, null, ex);
   }
   String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
   String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
   String username = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
   String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
   String name = "dbsample1";
   String url = "jdbc:mysql://" + host + ":" + port + "/" + name;
   return DriverManager.getConnection(url, username, password);
 }
示例#21
0
 /**
  * _more_
  *
  * @param range _more_
  * @param var _more_
  * @return _more_
  * @throws Exception _more_
  */
 protected float[] getFloatData(Range range, String var) throws Exception {
   long t1 = System.currentTimeMillis();
   float[] f =
       SqlUtil.readFloat(
           SqlUtil.getIterator(select("(" + var + ")", TABLE_DATA, "order by " + varTime)),
           1,
           (float) getMissingValue(var));
   long t2 = System.currentTimeMillis();
   //            System.err.println("length:" + f.length + " time:" + (t2-t1));
   if (f.length == 0) {
     throw new BadDataException("No observations found in data base");
   }
   return f;
 }
  /**
   * INTERNAL: Execute the query. Get the rows and build the object from the rows.
   *
   * @exception DatabaseException - an error has occurred on the database
   * @return java.lang.Object collection of objects resulting from execution of query.
   */
  protected Object executeObjectLevelReadQuery() throws DatabaseException {
    Object result = null;

    if (getContainerPolicy().overridesRead()) {
      return getContainerPolicy().execute();
    }

    if (this.descriptor.isDescriptorForInterface()) {
      Object returnValue =
          this.descriptor.getInterfacePolicy().selectAllObjectsUsingMultipleTableSubclassRead(this);
      setExecutionTime(System.currentTimeMillis());
      return returnValue;
    }

    List rows = getQueryMechanism().selectAllRows();
    setExecutionTime(System.currentTimeMillis());

    // If using 1-m joins, must set all rows.
    if (hasJoining() && this.joinedAttributeManager.isToManyJoin()) {
      this.joinedAttributeManager.setDataResults(rows, this.session);
    }

    if (this.session.isUnitOfWork()) {
      result =
          registerResultInUnitOfWork(
              rows, (UnitOfWorkImpl) this.session, this.translationRow, true); //
    } else {
      result = getContainerPolicy().containerInstance(rows.size());
      this.descriptor.getObjectBuilder().buildObjectsInto(this, rows, result);
    }

    if (this.shouldIncludeData) {
      ComplexQueryResult complexResult = new ComplexQueryResult();
      complexResult.setResult(result);
      complexResult.setData(rows);
      return complexResult;
    }

    // Add the other (already registered) results and return them.
    if (getDescriptor().hasTablePerClassPolicy()) {
      result =
          containerPolicy.concatenateContainers(
              result,
              getDescriptor()
                  .getTablePerClassPolicy()
                  .selectAllObjectsUsingMultipleTableSubclassRead(this));
    }

    return result;
  }
 protected void init() {
   try {
     _con = WebAppConnection.getWebAppConnection().getConnection();
   } catch (OptInCustomerException ex) {
     AppLog.writeAuditLog(
         "OptIN Driver OptInCustomerException: no connection to dB " + ex.getMessage());
     System.out.println(
         "OptIN Driver OptInCustomerException: no connection to dB " + ex.getMessage());
     System.exit(1);
   } catch (Exception exe) {
     AppLog.writeAuditLog("OptIN Driver Exception: " + exe.getMessage());
     System.out.println("OptIn Driver Exception : " + exe.getMessage());
     System.exit(1);
   }
 }
示例#24
0
  protected Connection getConnection() throws Exception {
    long currTime = System.nanoTime();
    if (currTime - connLastUsed > CONN_TIME_OUT) {
      synchronized (this) {
        Connection tmpConn = factory.call();
        closeConnection();
        connLastUsed = System.nanoTime();
        return conn = tmpConn;
      }

    } else {
      connLastUsed = currTime;
      return conn;
    }
  }
示例#25
0
 /**
  * Set Measure Actual
  *
  * @param MeasureActual actual
  */
 @Override
 public void setMeasureActual(BigDecimal MeasureActual) {
   if (MeasureActual == null) return;
   super.setMeasureActual(MeasureActual);
   setDateLastRun(new Timestamp(System.currentTimeMillis()));
   setGoalPerformance();
 } //	setMeasureActual
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;

    /* get system property user.home */
    /* POTENTIAL FLAW: Read data from a system property */
    data = System.getProperty("user.home");

    Connection dbConnection = null;

    try {
      dbConnection = IO.getDBConnection();

      /* POTENTIAL FLAW: Set the catalog name with the value of data
       * allowing a nonexistent catalog name or unauthorized access to a portion of the DB */
      dbConnection.setCatalog(data);
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
示例#27
0
  public Boolean insertarEquipo(String name, String form, int h1, int h2, int h3, int h4)
      throws ClassNotFoundException, SQLException {

    Connection c = null;
    Statement stmt = null;
    Boolean boo = true;
    try {
      // for (int d = 2; d < 20; d++) {
      ///    asd();
      //  }

      System.out.println(cont);
      Class.forName("com.mysql.jdbc.Driver");
      c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Equipos", "root", "camilo");
      c.setAutoCommit(false);
      stmt = c.createStatement();
      String sql =
          "INSERT INTO Equipos (Nombre,Formacion,Arquero,Defensor,Mediocampo,Ataque) "
              + String.format("VALUES ('%s','%s',%2d,%2d,%2d,%2d);", name, form, h1, h2, h3, h4);
      stmt.executeUpdate(sql);
      cont++;
      System.out.println("Equipo insertado ");
      stmt.close();
      c.commit();
      c.close();
    } catch (Exception e) {
      System.out.println("Error en insertarEquipo");
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
      System.exit(0);
    }
    return boo;
  }
示例#28
0
  public EquiposDB() {
    c = null;
    stmt = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Equipos", "root", "camilo");
      System.out.println("Conectado a Equipo.db");

      stmt = c.createStatement();
      String sql =
          "CREATE TABLE IF NOT EXISTS Equipos"
              + "(ID INT NOT NULL AUTO_INCREMENT,"
              + " Nombre TEXT NOT NULL, "
              + " Formacion TEXT,"
              + " Arquero INT, "
              + " Defensor INT, "
              + " Mediocampo INT, "
              + " Ataque INT, "
              + " PRIMARY KEY(ID))";
      stmt.executeUpdate(sql);
      stmt.close();
      c.close();
    } catch (ClassNotFoundException | SQLException e) {
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
      System.exit(0);
    }
    System.out.println("Tabla " + nteam + " creada");
  }
  /** erstellt die nötigen Tabellen in der Datenbank, falls sie noch nicht exisiteren */
  private void erstelleTabellen() {
    try {
      // erstellt die Benutzer-Tabelle
      String dbQuery =
          "CREATE TABLE IF NOT EXISTS benutzer ("
              + "bNr INTEGER PRIMARY KEY AUTOINCREMENT,"
              + "benutzername VARCHAR(45) NOT NULL,"
              + "statusnachricht text,"
              + "statussymbol VARCHAR(4),"
              + "status_aktuell_seit INTEGER,"
              + "passwort VARCHAR(50) NOT NULL,"
              + "online TINYINT(1));";

      con.createStatement().executeUpdate(dbQuery);

      // erstellt die Kontaklisten-Tabelle
      dbQuery =
          "CREATE TABLE IF NOT EXISTS kontaktliste ("
              + "kId INTEGER PRIMARY KEY AUTOINCREMENT,"
              + "besitzer INTEGER,"
              + "kontakt INTEGER,"
              + "foreign key (besitzer) references benutzer(bNr),"
              + "foreign key (kontakt) references benutzer(bNr))";

      con.createStatement().executeUpdate(dbQuery);

    } catch (SQLException e) {
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
      System.exit(1);
    }
  }
示例#30
0
 public void mouseClicked(MouseEvent e) {
   requestFocus();
   if (!focussed) starttime = System.currentTimeMillis();
   //	System.out.println("mouse click");
   requestFocus();
   focussed = true;
 }