/**
   * PDI-11363. when using getLookup calls there is no need to make attempt to retrieve row set
   * metadata for every call. That may bring performance penalty depends on jdbc driver
   * implementation. For some drivers that penalty can be huge (postgres).
   *
   * <p>During the execution calling getLookup() method we changing usually only lookup where clause
   * which will not impact return row structure.
   *
   * @throws KettleDatabaseException
   * @throws SQLException
   */
  @Test
  public void testGetLookupMetaCalls() throws KettleDatabaseException, SQLException {
    DatabaseMeta meta = Mockito.mock(DatabaseMeta.class);
    Mockito.when(meta.getQuotedSchemaTableCombination(Mockito.anyString(), Mockito.anyString()))
        .thenReturn("a");
    Mockito.when(meta.quoteField(Mockito.anyString())).thenReturn("a");

    PreparedStatement ps = Mockito.mock(PreparedStatement.class);
    ResultSet rs = Mockito.mock(ResultSet.class);
    Mockito.when(ps.executeQuery()).thenReturn(rs);

    ResultSetMetaData rmeta = Mockito.mock(ResultSetMetaData.class);
    Mockito.when(rs.getMetaData()).thenReturn(rmeta);

    Mockito.when(rmeta.getColumnCount()).thenReturn(0);
    Mockito.when(ps.getMetaData()).thenReturn(rmeta);

    Database db = new Database(log, meta);

    Connection conn = Mockito.mock(Connection.class);
    Mockito.when(conn.prepareStatement(Mockito.anyString())).thenReturn(ps);

    db.setConnection(conn);
    String[] name = new String[] {"a"};
    db.setLookup("a", name, name, name, name, "a");

    for (int i = 0; i < 10; i++) {
      db.getLookup();
    }
    Mockito.verify(rmeta, Mockito.times(1)).getColumnCount();
  }
Esempio n. 2
0
  public static void test01() throws Exception {
    Page p = new Page();
    p.setTmsp("2011-03-04 10:30:00");
    p.setUrl("http://www.google.com");
    p.setBody("my body");
    p.insert();

    Page e = new Page("2011-03-04 10:31:00", "http://www.usp.br", "o corpo");
    e.insert();
    e.setBody("usp usp usp");
    e.update();

    Database db = new Database();
    db.connect();
    ResultSet rs = Page.findAll(db);

    /*
    while (rs.next()) {
    	System.out.println(rs.getString("tmsp")
    		+", "+ rs.getString("url")
    		+", "+ rs.getString("body"));
    }*/

    Page p0 = null;
    while ((p0 = Page.next(rs)) != null) {
      System.out.println(p0.getTmsp());
      System.out.println(p0.getUrl());
      System.out.println(p0.getBody());
    }

    db.close();

    p.remove();
    e.remove();
  }
 public static Response editFeature(
     int fid,
     String spatialcontext,
     String viewpoint,
     InputXML input,
     String img,
     int width,
     int height) {
   try (Database db = new Database()) {
     Point[] points = anglesToFeature(spatialcontext, viewpoint, input.getAngles(), db);
     GeoFeature feature =
         Util.pointsToFeature(points, input.getAngles(), input.getType(), false, 0);
     db.setFeature(fid, spatialcontext, feature.toWkt(), "wkt", 0);
     db.addMeasurement(fid, spatialcontext, viewpoint, input);
     /*HashMap<String, Double> visibility = checkVisibility(spatialcontext, feature, db);
     for (String vp : visibility.keySet()) {
     db.setVisibility(spatialcontext, fid, vp, visibility.get(vp) > VISIBILITY_TOLERANCE);
     }*/
     db.setVisibility(spatialcontext, fid, viewpoint, true);
     db.close();
     // insertImage(img, fid, width, height);
     return FeatureXML.getFeature(spatialcontext, fid);
   } catch (ClientException e) {
     return Config.getResult(e);
   } catch (Exception e) {
     return Config.getResult(e);
   }
 }
  public Database getDatabase(final boolean evictCache) {
    if (!evictCache && cachedIntrospections.contains(lastDatabase)) {
      for (final Database database : cachedIntrospections) {
        if (database.equals(lastDatabase)) {
          return lastDatabase;
        }
      }
    }
    if (evictCache && cachedIntrospections.contains(lastDatabase)) {
      cachedIntrospections.remove(lastDatabase);
    }

    final String dbreXmlPath = getDbreXmlPath();
    if (StringUtils.isBlank(dbreXmlPath) || !fileManager.exists(dbreXmlPath)) {
      return null;
    }

    Database database = null;
    InputStream inputStream = null;
    try {
      inputStream = fileManager.getInputStream(dbreXmlPath);
      database = DatabaseXmlUtils.readDatabase(inputStream);
      cacheDatabase(database);
      return database;
    } catch (final Exception e) {
      throw new IllegalStateException(e);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }
  private static void computeBeliefBoundaries(
      Double hFFPos, Double hFFSpeed, Double hfFFTargetPos, Double hFFCreationTime) {

    double currentTime = System.nanoTime() / SEC_NANOSEC_FACTOR;
    double[] minBoundaries = new double[1];
    double[] maxBoundaries = new double[1];
    double startTime = 0.0;

    if (hfFFTargetPos != 0.0) {
      if (hFFCreationTime > hInit) {
        startTime = hFFCreationTime;
        hFFPosMin = hFFPos;
        hFFPosMax = hFFPos;
        hFFSpeedMin = hFFSpeed;
        hFFSpeedMax = hFFSpeed;
      } else {
        if (hFFCreationTime <= hLastTime) {
          startTime = hLastTime;
        } else if (hFFCreationTime > hLastTime) {
          startTime = hFFCreationTime;
          hFFPosMin = hFFPos;
          hFFPosMax = hFFPos;
          hFFSpeedMin = hFFSpeed;
          hFFSpeedMax = hFFSpeed;
        }
      }

      // ---------------------- knowledge evaluation --------------------------------

      double accMin =
          Database.getAcceleration(
              hFFSpeedMin, hFFPosMin, Database.lTorques, 0.0, 1.0, Database.lMass);
      double accMax =
          Database.getAcceleration(
              hFFSpeedMax, hFFPosMax, Database.lTorques, 1.0, 0.0, Database.lMass);

      FirstOrderIntegrator integrator = new MidpointIntegrator(1);
      integrator.setMaxEvaluations((int) TIMEPERIOD);
      FirstOrderDifferentialEquations f = new Derivation();
      // ------------- min ----------------------

      minBoundaries[0] = accMin;
      integrator.integrate(f, startTime, minBoundaries, currentTime, minBoundaries);
      hFFSpeedMin += minBoundaries[0];
      integrator.integrate(f, startTime, minBoundaries, currentTime, minBoundaries);
      hFFPosMin += minBoundaries[0];
      // ------------- max ----------------------

      maxBoundaries[0] = accMax;
      integrator.integrate(f, startTime, maxBoundaries, currentTime, maxBoundaries);
      hFFSpeedMax += maxBoundaries[0];
      integrator.integrate(f, startTime, maxBoundaries, currentTime, maxBoundaries);
      hFFPosMax += maxBoundaries[0];
    }
    if (hFFSpeedMax > 200) hFFSpeedMax = 200.0;
    if (hFFSpeedMin < 0.0) hFFSpeedMin = 0.0;
    if (hFFPosMin < 0.0) hFFPosMin = 0.0;
    hLastTime = currentTime;
    hInit = hFFCreationTime;
  }
Esempio n. 6
0
  @Override
  public void onClick(DialogInterface dialog, int which) {
    Context context = v.getContext();
    CharSequence text;
    if (!d) {
      text = "You accepted the offer";
    } else {
      text = "You declined the offer";
    }

    if (offer != null) {
      if (!d) {
        offer.accept(this.context, offer);
        Database.addOffer(context, offer);
      } else {
        offer.reject();
        Database.addOffer(context, offer);
      }
    }

    int duration = Toast.LENGTH_LONG;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
    h.setVisibility(LinearLayout.VISIBLE);
  }
Esempio n. 7
0
  public void EMpar(Database db, double prior) {
    int j, np;
    double x, y, tmp, tmpx, tmpy, tmpsx, tmpsy, tmpsxy;

    np = db.nPoints();
    tmpsx = tmpsy = tmpsxy = kmx = kmy = 0;
    for (j = 0; j < np; j++) {
      x = db.xVal(j);
      y = db.yVal(j);
      kmx += probs[j] * x;
      kmy += probs[j] * y;
      tmpsx += probs[j] * x * x;
      tmpsy += probs[j] * y * y;
      tmpsxy += probs[j] * x * y;
    }
    tmp = np * weight;
    kmx /= tmp;
    kmy /= tmp;
    ksx = Math.sqrt(tmpsx / tmp - kmx * kmx);
    ksy = Math.sqrt(tmpsy / tmp - kmy * kmy);
    ksxy = tmpsxy / tmp - kmx * kmy;
    if (ksx < mins) ksx = mins;
    if (ksy < mins) ksy = mins;
    weight = 0.9 * weight + 0.1 * prior;
  }
Esempio n. 8
0
  /**
   * oppretter en kø dersom det ikke finnes fra før.
   *
   * @param subjectcode
   * @return
   */
  public static boolean startQueue(String subjectcode) {

    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
      return false;
    }

    PreparedStatement ps = null;

    try {
      ps = db.connection.prepareStatement("UPDATE queue SET status = true WHERE subject_code = ?");
      ps.setString(1, subjectcode);
      ps.executeUpdate();
    } catch (Exception e) {
      System.out.println(e);
      return false;
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeConnection(db.connection);
    }

    return true;
  }
Esempio n. 9
0
  /**
   * Henter ut hvilken rolle en bruker har i ett bestemt f*g.
   *
   * @param subjectcode
   * @param username
   * @return
   */
  public static String getSubject_access(String subjectcode, String username) {

    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
    }

    PreparedStatement ps = null;
    ResultSet rs = null;
    String role = "student";

    /* Henter hvilken access brukeren har i faget */
    try {
      ps =
          db.connection.prepareStatement(
              "SELECT r.role_name FROM roles r INNER JOIN person_sub_role psr ON psr.role_id = r.id WHERE psr.username = ? AND psr.subjectcode = ? ");
      ps.setString(1, username);
      ps.setString(2, subjectcode);
      rs = ps.executeQuery();

      if (rs.next()) {
        role = rs.getString("role_name");
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeResSet(rs);
      Cleanup.closeConnection(db.connection);
    }
    return role;
  }
Esempio n. 10
0
 /**
  * Parse and prepare the given SQL statement. This method also checks if the connection has been
  * closed.
  *
  * @param sql the SQL statement
  * @return the prepared statement
  */
 public Command prepareLocal(String sql) {
   if (closed) {
     throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed");
   }
   Command command;
   if (queryCacheSize > 0) {
     if (queryCache == null) {
       queryCache = SmallLRUCache.newInstance(queryCacheSize);
       modificationMetaID = database.getModificationMetaId();
     } else {
       long newModificationMetaID = database.getModificationMetaId();
       if (newModificationMetaID != modificationMetaID) {
         queryCache.clear();
         modificationMetaID = newModificationMetaID;
       }
       command = queryCache.get(sql);
       if (command != null && command.canReuse()) {
         command.reuse();
         return command;
       }
     }
   }
   Parser parser = new Parser(this);
   command = parser.prepareCommand(sql);
   if (queryCache != null) {
     if (command.isCacheable()) {
       queryCache.put(sql, command);
     }
   }
   return command;
 }
Esempio n. 11
0
 private List<MapInfo> getMapInfo(Database database) {
   return complete(database.maps())
       .stream()
       .map(name -> new MapInfo(name, complete(database.mapSize(name))))
       .filter(info -> info.size() > 0)
       .collect(Collectors.toList());
 }
Esempio n. 12
0
  protected int fetchNumRows(String clause, boolean forceQuotes) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    StringBuilder sql = new StringBuilder("select ");
    sql.append(clause);
    sql.append(" from ");
    if (getSchema() != null) {
      sql.append(getSchema());
      sql.append('.');
    }

    if (forceQuotes) {
      String quote = db.getMetaData().getIdentifierQuoteString().trim();
      sql.append(quote + getName() + quote);
    } else sql.append(db.getQuotedIdentifier(getName()));

    try {
      stmt = db.getConnection().prepareStatement(sql.toString());
      rs = stmt.executeQuery();
      while (rs.next()) {
        return rs.getInt(1);
      }
      return -1;
    } catch (SQLException exc) {
      if (forceQuotes) // we tried with and w/o quotes...fail this attempt
      throw exc;

      return fetchNumRows(clause, true);
    } finally {
      if (rs != null) rs.close();
      if (stmt != null) stmt.close();
    }
  }
Esempio n. 13
0
 public static BigInteger getBalance(String address, String asset) {
   Database db = Database.getInstance();
   Blocks blocks = Blocks.getInstance();
   if (asset.equals("BTC")) {
     /*
     BigInteger totalBalance = BigInteger.ZERO;
     LinkedList<TransactionOutput> unspentOutputs = blocks.wallet.calculateAllSpendCandidates(true);
     Set<Transaction> txs = blocks.wallet.getTransactions(true);
     for (TransactionOutput out : unspentOutputs) {
     	Script script = out.getScriptPubKey();
     	if (script.getToAddress(blocks.params).toString().equals(address) && out.isAvailableForSpending()) {
     		totalBalance = totalBalance.add(out.getValue());
     	}
     }
     return totalBalance;
      */
     return getBTCBalance(address);
   } else {
     ResultSet rs =
         db.executeQuery(
             "select sum(amount) as amount from balances where address='"
                 + address
                 + "' and asset='"
                 + asset
                 + "';");
     try {
       if (rs.next()) {
         return BigInteger.valueOf(rs.getLong("amount"));
       }
     } catch (SQLException e) {
     }
   }
   return BigInteger.ZERO;
 }
Esempio n. 14
0
 public static void updateLastParsedBlock(Integer block_index) {
   Database db = Database.getInstance();
   db.executeUpdate(
       "REPLACE INTO sys_parameters (para_name,para_value) values ('last_parsed_block','"
           + block_index.toString()
           + "');");
 }
Esempio n. 15
0
  private String getRangeCode(int item) throws SQLException {
    String result = "";

    Database db = new Database(conn);
    String name = db.getItemFullName(item, ITEM_TYPE.TYPE);

    PreparedStatement stmt = conn.prepareStatement(RANGE_SOURCE);
    stmt.setInt(1, item);

    ResultSet rs = stmt.executeQuery();

    if (rs.next()) {
      result = "CREATE TYPE " + name + " AS RANGE (\n";

      result = result + "\tSUBTYPE =" + rs.getString("subtype") + "\n";

      if (rs.getString("opc") != null)
        result = result + "\t, SUBTYPE_OPCLASS = " + rs.getString("opc") + "\n";

      if (rs.getString("collation") != null)
        result = result + "\t, COLLATION = " + rs.getString("collation") + "\n";

      if (rs.getString("canonical") != null)
        result = result + "\t, CANONICAL = " + rs.getString("canonical") + "\n";

      if (rs.getString("subdiff") != null)
        result = result + "\t, SUBTYPE_DIFF = " + rs.getString("subdiff") + "\n";

      result = result + ")";
    }

    return result;
  }
Esempio n. 16
0
  /**
   * Fjerner en entry
   *
   * @param username
   * @param subjectcode
   * @return
   */
  public static boolean removeQueueEntry(String username) {

    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
      return false;
    }

    PreparedStatement ps = null;

    /* sletter din entrys */
    try {
      ps = db.connection.prepareStatement("DELETE FROM queue_list WHERE person_username = ?");
      ps.setString(1, username);
      ps.executeUpdate();
    } catch (Exception e) {
      System.out.println(e);
      return false;
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeConnection(db.connection);
    }

    return true;
  }
Esempio n. 17
0
  private String getSequenceCode(int item) throws SQLException {
    String result = "";

    Database db = new Database(conn);
    String name = db.getItemFullName(item, ITEM_TYPE.TABLE);

    String fromClause = name;
    String sql = SEQUENCE_SOURCE + fromClause;

    PreparedStatement stmt = conn.prepareStatement(sql);

    ResultSet rs = stmt.executeQuery();

    if (rs.next()) {
      result = "CREATE SEQUENCE " + name + " AS\n";
      result = result + "\t INCREMENT " + Long.toString(rs.getLong(6)) + "\n";
      result = result + "\t MINVALUE " + Long.toString(rs.getLong(2)) + "\n";
      result = result + "\t MAXVALUE " + Long.toString(rs.getLong(3)) + "\n";
      result = result + "\t START " + Long.toString(rs.getLong(1)) + "\n";
      result = result + "\t CACHE " + Long.toString(rs.getLong(4)) + "\n";
      result = result + "\t ";

      if (!rs.getBoolean(5)) {
        result = result + "NO ";
      }
      result = result + "CYCLE\n";
    }

    return result;
  }
Esempio n. 18
0
  /**
   * Endrer kø info til ett bestemt f*g
   *
   * @param code
   * @param info
   * @param username
   * @return
   */
  public static boolean endreKoInfo(String code, String info, String username) {

    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
      return false;
    }

    PreparedStatement ps = null;

    try {
      ps =
          db.connection.prepareStatement(
              "UPDATE queue SET info = ?,info_username = ? WHERE subject_code = ?");
      ps.setString(1, info);
      ps.setString(2, username);
      ps.setString(3, code);
      ps.executeUpdate();
    } catch (Exception e) {
      System.out.println(e);
      return false;
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeConnection(db.connection);
    }
    return true;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.list_wisata_budaya);

    database = new Database(this);
    database.bukaKoneksi();
    Cursor cursor = database.bacaWisataBudaya();

    startManagingCursor(cursor);
    String[] awal = new String[] {database.FIELD_JUDUL, database.FIELD_GAMBAR};
    int[] tujuan = new int[] {R.id.nama2, R.id.gambar2};
    mCursorAdapter =
        new SimpleCursorAdapter(this, R.layout.item_wisata_budaya, cursor, awal, tujuan);

    mCursorAdapter.setViewBinder(
        new SimpleCursorAdapter.ViewBinder() {
          public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (columnIndex == database.POSISI_ID) {
              TextView textView = (TextView) view;
              textView.setText("");
              return true;
            }
            return false;
          }
        });

    setListAdapter(mCursorAdapter);
    registerForContextMenu(getListView());
  }
Esempio n. 20
0
  /**
   * Endrer en entry(kø-element) til aktiv tilstand(får hjelp av en lærer).
   *
   * @param teacher
   * @param user
   * @param active
   */
  public static void setActive(String teacher, String user, boolean active) {
    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
      return;
    }

    PreparedStatement ps = null;

    try {
      ps =
          db.connection.prepareStatement(
              "UPDATE queue_list SET status = ?,teacher_username = ? WHERE person_username = ?");
      ps.setBoolean(1, active);
      ps.setString(2, teacher);
      ps.setString(3, user);
      ps.executeUpdate();
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeConnection(db.connection);
    }
  }
Esempio n. 21
0
 public void restore() throws jsqlite.Exception {
   String line = null, sql = null;
   while (true) {
     try {
       line = is.readLine();
     } catch (EOFException e) {
       line = null;
     } catch (IOException e) {
       throw new jsqlite.Exception("I/O error: " + e);
     }
     if (line == null) {
       break;
     }
     if (sql == null) {
       sql = line;
     } else {
       sql = sql + " " + line;
     }
     if (Database.complete(sql)) {
       db.exec(sql, null);
       sql = null;
     }
   }
   if (sql != null) {
     throw new jsqlite.Exception("Incomplete SQL: " + sql);
   }
 }
Esempio n. 22
0
  /**
   * Oppdaterer den totale vente-tiden i ett f*g. Metoden legger til waitingtime til det som lå der
   * fra før.
   *
   * @param subjectcode
   * @param waitingtime
   * @return
   */
  public static boolean updateTotalWaitingTime(String subjectcode, int waitingtime) {

    Database db = new Database();
    try {
      db.openConnection();
    } catch (Exception ex) {
      System.out.println("(QueueDB.java) Error: Kunne ikke koble til database -> " + ex);
      return false;
    }

    PreparedStatement ps = null;

    try {
      ps =
          db.connection.prepareStatement(
              "UPDATE queue SET total_helped = total_helped + 1,total_waitingtime = total_waitingtime + ? WHERE subject_code = ?");
      ps.setInt(1, waitingtime);
      ps.setString(2, subjectcode);
      ps.executeUpdate();
    } catch (Exception e) {
      System.out.println(e);
      return false;
    } finally {
      Cleanup.closeSentence(ps);
      Cleanup.closeConnection(db.connection);
    }
    return true;
  }
Esempio n. 23
0
  public void bootFromServer(String clientName, Database db1)
      throws JSONException, ClassNotFoundException {

    Client client = Client.create();

    WebResource webResource =
        client.resource("http://localhost:8080/com.youtube.rest/api/bootstrap/get/" + clientName);
    ;

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() != 200 && response.getStatus() != 204) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);
    System.out.println("Server Bootstrap information: ");
    System.out.println(output);
    String query = db1.parseData(output);
    System.out.println("QUERY");
    System.out.println(query);
    db1.delete("client1");
    //	db1.insert(query);
    System.out.println("Information saved in Mysql!");
    System.out.println("Server boot done!");
  }
Esempio n. 24
0
  private String getCompositeCode(int item) throws SQLException {
    String result = "";

    Database db = new Database(conn);
    String name = db.getItemFullName(item, ITEM_TYPE.TABLE);

    PreparedStatement stmt = conn.prepareStatement(COMPOSITE_SOURCE);
    stmt.setInt(1, item);

    ResultSet rs = stmt.executeQuery();

    String atts = "";
    while (rs.next()) {
      atts = atts + "\t" + rs.getString(1) + "\t" + rs.getString(2) + ",\n";
    }

    if (!atts.equals("")) {
      // trim off the last ,\n
      atts = atts.substring(0, atts.length() - 2);

      result = "CREATE TYPE " + name + " AS ( \n";
      result = result + atts + "\n)";
    }

    return result;
  }
Esempio n. 25
0
  /** Immediately refreshes all globals using the backing database. */
  public synchronized void refreshGlobals() {
    bootstrapOnce.ensure();

    Database database = getDatabase();
    LOGGER.info("Loading globals from [{}]", database.getName());

    Query<Object> globalsQuery =
        Query.from(Object.class).where("_id = ?", GLOBALS_ID).using(database).noCache();

    State newGlobals = State.getInstance(globalsQuery.first());

    if (newGlobals == null) {
      newGlobals = State.getInstance(globalsQuery.master().first());
    }

    if (newGlobals == null) {
      newGlobals = new State();
      newGlobals.setDatabase(database);
      newGlobals.setId(GLOBALS_ID);
      newGlobals.save();
    }

    globals = newGlobals;
    lastGlobalsUpdate = new Date();
    fieldsCache.reset();
    metricFieldsCache.reset();
    indexesCache.reset();
  }
Esempio n. 26
0
  private String getEnumCode(int item) throws SQLException {
    String result = "";

    Database db = new Database(conn);
    String name = db.getItemFullName(item, ITEM_TYPE.TYPE);

    PreparedStatement stmt = conn.prepareStatement(ENUM_SOURCE);
    stmt.setInt(1, item);

    ResultSet rs = stmt.executeQuery();

    String enums = "";
    while (rs.next()) {
      enums = enums + "'" + rs.getString(1) + "',";
    }

    if (!enums.equals("")) {
      // trim off the last ,
      enums = enums.substring(0, enums.length() - 1);

      result = "CREATE TYPE " + name + " AS ENUM \n";
      result = result + "\t(" + enums + ")";
    }

    return result;
  }
Esempio n. 27
0
  // Chamando Robot
  public static void robot() throws Exception {
    Database db = new Database();
    db.connect();
    ResultSet rs = Page.findAll(db);

    Page p = null;
    while ((p = Page.next(rs)) != null) {
      String body = Robot.get(p.getUrl());

      // procurar por urls dentro do body
      // buscar por essas paginas

      // String expr = "href=\"([^\"]*)";
      String ereg = "href=\"https{0,1}:\\/\\/([^\"]*)\"";
      Pattern pt = Pattern.compile(ereg);
      Matcher m = pt.matcher(body);

      while (m.find()) {
        System.out.println(m.group());
        String[] _url = m.group().split("\"");
        Page.newUrl(_url[1]);
      }

      p.setBody(body);
      p.update();
    }

    db.close();
  }
Esempio n. 28
0
  private String getFunctionCode(int item) throws SQLException {
    String result = "";

    Database db = new Database(conn);
    String name = db.getItemFullName(item, ITEM_TYPE.FUNCTION);

    PreparedStatement stmt = conn.prepareStatement(FUNC_SOURCE);
    stmt.setInt(1, item);

    ResultSet rs = stmt.executeQuery();

    if (rs.next()) {
      String src = rs.getString(1);
      String lang = rs.getString(2);
      String ret = rs.getString(3);

      result = "CREATE FUNCTION " + name;
      result = result + " RETURNS " + ret;
      result = result + " AS $$ ";
      result = result + src;
      result = result + "$$ LANGUAGE " + lang + ";";
    }

    return result;
  }
Esempio n. 29
0
 /**
  * Add an undo log entry to this session.
  *
  * @param table the table
  * @param operation the operation type (see {@link UndoLogRecord})
  * @param row the row
  */
 public void log(Table table, short operation, Row row) {
   if (undoLogEnabled) {
     UndoLogRecord log = new UndoLogRecord(table, operation, row);
     // called _after_ the row was inserted successfully into the table,
     // otherwise rollback will try to rollback a not-inserted row
     if (SysProperties.CHECK) {
       int lockMode = database.getLockMode();
       if (lockMode != Constants.LOCK_MODE_OFF && !database.isMultiVersion()) {
         String tableType = log.getTable().getTableType();
         if (locks.indexOf(log.getTable()) < 0
             && !Table.TABLE_LINK.equals(tableType)
             && !Table.EXTERNAL_TABLE_ENGINE.equals(tableType)) {
           DbException.throwInternalError();
         }
       }
     }
     undoLog.add(log);
   } else {
     if (database.isMultiVersion()) {
       // see also UndoLogRecord.commit
       ArrayList<Index> indexes = table.getIndexes();
       for (int i = 0, size = indexes.size(); i < size; i++) {
         Index index = indexes.get(i);
         index.commit(operation, row);
       }
       row.commit();
     }
   }
 }
  // Fees update method
  private void updateFeesData(long id) {
    String columns[] = {"Course", "Fees Payed", "Total fees", "Installments"};
    try {
      Database db = new Database();

      panel_7.removeAll();

      feestablemodel = new MyTableModel(db.getFeeData(id), columns);

      feestable = new JTable(feestablemodel);
      feestable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      feestable.getSelectionModel().addListSelectionListener(this);

      feesscrollpane = new JScrollPane(feestable);
      panel_7.add(feesscrollpane);

      // change fees payed label
      feespayedlabel.setText("Fees Payed");
      feesduelabel.setText("Fees Due");
      totalfeeslabel.setText("Total Fees");

      panel_7.revalidate();
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
    }
  }