Пример #1
0
 /**
  * Get Restriction Lines
  *
  * @param reload reload data
  * @return array of lines
  */
 public MGoalRestriction[] getRestrictions(boolean reload) {
   if (m_restrictions != null && !reload) return m_restrictions;
   ArrayList<MGoalRestriction> list = new ArrayList<MGoalRestriction>();
   //
   String sql =
       "SELECT * FROM PA_GoalRestriction "
           + "WHERE PA_Goal_ID=? AND IsActive='Y' "
           + "ORDER BY Org_ID, C_BPartner_ID, M_Product_ID";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, get_Trx());
     pstmt.setInt(1, getPA_Goal_ID());
     rs = pstmt.executeQuery();
     while (rs.next()) list.add(new MGoalRestriction(getCtx(), rs, get_Trx()));
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   //
   m_restrictions = new MGoalRestriction[list.size()];
   list.toArray(m_restrictions);
   return m_restrictions;
 } //	getRestrictions
Пример #2
0
 public void put(String name, String value, String readPerm, String writePerm) {
   SysConfig cfg;
   if (prefix != null) name = prefix + name;
   try {
     boolean autoCommit = false;
     Transaction tx = db.session().getTransaction();
     if (tx == null || tx.getStatus().isNotOneOf(TransactionStatus.ACTIVE)) {
       tx = db.session().beginTransaction();
       autoCommit = true;
     }
     cfg = (SysConfig) db.session().get(SysConfig.class, name);
     boolean saveIt = false;
     if (cfg == null) {
       cfg = new SysConfig();
       cfg.setId(name);
       saveIt = true;
     }
     cfg.setReadPerm(readPerm);
     cfg.setWritePerm(writePerm);
     cfg.setValue(value);
     if (saveIt) db.session().save(cfg);
     if (autoCommit) tx.commit();
   } catch (HibernateException e) {
     db.getLog().warn(e);
   }
 }
Пример #3
0
  /**
   * Find all the year records in a Calendar, it need not be a standard period (used in MRP)
   *
   * @param C_Calendar_ID calendar
   * @param ctx context
   * @param trx trx
   * @return MYear[]
   */
  public static MYear[] getAllYearsInCalendar(int C_Calendar_ID, Ctx ctx, Trx trx) {

    List<MYear> years = new ArrayList<MYear>();
    String sql = "SELECT * FROM C_Year WHERE " + "IsActive='Y' AND C_Calendar_ID = ? ";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Calendar_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) years.add(new MYear(ctx, rs, trx));

    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {

      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }

    MYear[] retValue = new MYear[years.size()];
    years.toArray(retValue);
    return retValue;
  }
Пример #4
0
 /**
  * Get Accessible Goals
  *
  * @param ctx context
  * @return array of goals
  */
 public static MGoal[] getGoals(Ctx ctx) {
   ArrayList<MGoal> list = new ArrayList<MGoal>();
   String sql = "SELECT * FROM PA_Goal WHERE IsActive='Y' " + "ORDER BY SeqNo";
   sql =
       MRole.getDefault(ctx, false)
           .addAccessSQL(sql, "PA_Goal", false, true); // 	RW to restrict Access
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       MGoal goal = new MGoal(ctx, rs, null);
       goal.updateGoal(false);
       list.add(goal);
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   MGoal[] retValue = new MGoal[list.size()];
   list.toArray(retValue);
   return retValue;
 } //	getGoals
Пример #5
0
  /**
   * Returns the previous period
   *
   * @param period MPeriod
   * @param periodCount Count
   * @param trx trx
   * @param ctx Ctx
   * @return MPeriod
   */
  public static MPeriod getPreviousPeriod(MPeriod period, Ctx ctx, Trx trx) {

    MPeriod newPeriod = null;
    String sql =
        "SELECT * FROM C_Period WHERE "
            + "C_Period.IsActive='Y' AND PeriodType='S' "
            + "AND C_Period.C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Year.C_Calendar_ID = ? ) "
            + "AND ((C_Period.C_Year_ID * 1000) + C_Period.PeriodNo) "
            + " < ((? * 1000) + ?) ORDER BY C_Period.C_Year_ID DESC, C_Period.PeriodNo DESC";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, period.getC_Calendar_ID());
      pstmt.setInt(2, period.getC_Year_ID());
      pstmt.setInt(3, period.getPeriodNo());
      rs = pstmt.executeQuery();
      if (rs.next()) newPeriod = new MPeriod(ctx, rs, trx);
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    return newPeriod;
  }
Пример #6
0
  /**
   * Find the periods in a calendar year it need not be a standard period (used in MRP)
   *
   * @param C_Year_ID Year
   * @param periodType Period Type
   * @param ctx context
   * @param trx trx
   * @return MPeriod[]
   */
  public static MPeriod[] getAllPeriodsInYear(int C_Year_ID, String periodType, Ctx ctx, Trx trx) {

    List<MPeriod> periods = new ArrayList<MPeriod>();
    String sql = "SELECT * FROM C_Period WHERE IsActive='Y'";

    sql = sql + " AND C_Year_ID = ?";

    if (periodType != null) sql = sql + " AND PeriodType = ? ";

    sql = sql + " order by StartDate ";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Year_ID);

      if (periodType != null) pstmt.setString(2, periodType);

      rs = pstmt.executeQuery();
      while (rs.next()) periods.add(new MPeriod(ctx, rs, trx));
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    MPeriod[] retValue = new MPeriod[periods.size()];
    periods.toArray(retValue);
    return retValue;
  }
Пример #7
0
  /**
   * Very specifically get other siblings of the parent that have other xpaths, not the same as this
   *
   * @param tree
   * @return
   */
  public List<XMLNode> quickOtherSiblings(XMLNode tree) {
    List<XMLNode> l = Collections.emptyList();
    try {
      l =
          DB.getStatelessSession()
              .createSQLQuery(
                  "select * from xml_node_"
                      + tree.getXmlObject().getDbID()
                      + " where parent_node_id = :parent"
                      + " and (xpath_summary_id != :path "
                      + " or xml_node_id = :id ) "
                      + "order by xml_node_id")
              .addEntity(XMLNode.class)
              .setLong("parent", tree.getParentNode().getNodeId())
              .setLong("path", tree.getXpathHolder().getDbID())
              .setEntity("id", tree)
              .list();
    } catch (Exception e) {
      log.error("Query failed with ", e);
    }
    for (XMLNode node : l) {
      node.setXpathHolder(DB.getXpathHolderDAO().findById(node.getXpathHolder().getDbID(), false));
    }

    return l;
  }
Пример #8
0
 /**
  * Find first Year Period of DateAcct based on Client Calendar
  *
  * @param ctx context
  * @param C_Calendar_ID calendar
  * @param DateAcct date
  * @return active first Period
  */
 public static MPeriod getFirstInYear(Ctx ctx, int C_Calendar_ID, Timestamp DateAcct) {
   MPeriod retValue = null;
   String sql =
       "SELECT * "
           + "FROM C_Period "
           + "WHERE C_Year_ID IN "
           + "(SELECT p.C_Year_ID "
           + "FROM C_Year y"
           + " INNER JOIN C_Period p ON (y.C_Year_ID=p.C_Year_ID) "
           + "WHERE y.C_Calendar_ID=?"
           + "	AND ? BETWEEN StartDate AND EndDate)"
           + " AND IsActive='Y' AND PeriodType='S' "
           + "ORDER BY StartDate";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     pstmt.setInt(1, C_Calendar_ID);
     pstmt.setTimestamp(2, DateAcct);
     rs = pstmt.executeQuery();
     if (rs.next()) // 	first only
     retValue = new MPeriod(ctx, rs, null);
   } catch (SQLException e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   return retValue;
 } //	getFirstInYear
Пример #9
0
    public static void main(String[] args) throws UnknownHostException {
        MongoClient client = new MongoClient();
        DB db = client.getDB("hw31");
        DBCollection collection = db.getCollection("students");

        // create our pipeline operations, first with the $match
        DBObject match = new BasicDBObject("$match", new BasicDBObject("scores.type", "homework") );

        // $unwind op
        //DBObject unwind = new BasicDBObject("$unwind", "$scores");

        // Now the $group operation
        DBObject groupFields = new BasicDBObject( "_id", "$student_id");
        //groupFields.put("score", new BasicDBObject( "$min", "scores.$score"));
        DBObject group = new BasicDBObject("$group", groupFields);
//
//        // $sort operation
//        DBObject sortFields = new BasicDBObject("_id", 1).append("score", 1);
//        DBObject sort = new BasicDBObject("$sort", sortFields);

        // run aggregation
        AggregationOutput output = collection.aggregate(match, group);

        for(Iterator<DBObject> i = output.results().iterator(); i.hasNext();) {
            DBObject result = i.next();
            System.out.println(result);
//            collection.remove(QueryBuilder.start("student_id").is(result.get("_id"))
//                    .and("score").is(result.get("score")).and("type").is("homework").get());
        }

        System.out.println(collection.count());
    }
Пример #10
0
 /**
  * ************************************************************************ Create Missing
  * Document Types
  *
  * @param ctx context
  * @param AD_Client_ID client
  * @param sp server process
  * @param trx transaction
  */
 public static void createDocumentTypes(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trx) {
   s_log.info("AD_Client_ID=" + AD_Client_ID);
   String sql =
       "SELECT rl.Value, rl.Name "
           + "FROM AD_Ref_List rl "
           + "WHERE rl.AD_Reference_ID=183"
           + " AND rl.IsActive='Y' AND NOT EXISTS "
           + " (SELECT * FROM C_DocType dt WHERE dt.AD_Client_ID=? AND rl.Value=dt.DocBaseType)";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, trx);
     pstmt.setInt(1, AD_Client_ID);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       String name = rs.getString(2);
       String value = rs.getString(1);
       s_log.config(name + "=" + value);
       MDocType dt = new MDocType(ctx, value, name, trx);
       if (dt.save()) {
         if (sp != null) sp.addLog(0, null, null, name);
         else s_log.fine(name);
       } else {
         if (sp != null) sp.addLog(0, null, null, "Not created: " + name);
         else s_log.warning("Not created: " + name);
       }
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeResultSet(rs);
     DB.closeStatement(pstmt);
   }
 } //	createDocumentTypes
Пример #11
0
  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return success
   */
  @Override
  protected boolean afterSave(boolean newRecord, boolean success) {
    //	also used for afterDelete
    String sql =
        "UPDATE M_AttributeSet mas"
            + " SET IsInstanceAttribute='Y' "
            + "WHERE M_AttributeSet_ID= ? "
            + " AND IsInstanceAttribute='N'"
            + " AND (IsSerNo='Y' OR IsLot='Y' OR IsGuaranteeDate='Y'"
            + " OR EXISTS (SELECT * FROM M_AttributeUse mau"
            + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
            + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
            + " AND mau.IsActive='Y' AND ma.IsActive='Y'"
            + " AND ma.IsInstanceAttribute='Y')"
            + ")";
    int no = DB.executeUpdate(get_Trx(), sql, getM_AttributeSet_ID());
    if (no != 0) log.fine("afterSave - Set Instance Attribute");
    //
    sql =
        "UPDATE M_AttributeSet mas"
            + " SET IsInstanceAttribute='N' "
            + "WHERE M_AttributeSet_ID=? "
            + " AND IsInstanceAttribute='Y'"
            + "	AND IsSerNo='N' AND IsLot='N' AND IsGuaranteeDate='N'"
            + " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau"
            + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
            + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
            + " AND mau.IsActive='Y' AND ma.IsActive='Y'"
            + " AND ma.IsInstanceAttribute='Y')";
    no = DB.executeUpdate(get_Trx(), sql, getM_AttributeSet_ID());
    if (no != 0) log.fine("afterSave - Reset Instance Attribute");

    return success;
  } //	afterSave
  /**
   * Creates an {@link AttachedDevice} resource in the DataBase and validates the transaction
   *
   * @param resource - The {@link AttachedDevice} resource to create
   */
  public void create(AttachedDevice resource) {
    // Store the created resource
    DB.store(resource);
    // MgmtObjs
    MgmtObjs mgmtObjs = new MgmtObjs();
    mgmtObjs.setUri(resource.getMgmtObjsReference());
    mgmtObjs.setCreationTime(resource.getCreationTime());
    mgmtObjs.setLastModifiedTime(resource.getLastModifiedTime());
    mgmtObjs.setAccessRightID(resource.getAccessRightID());
    DAOFactory.getMgmtObjsDAO().create(mgmtObjs);
    // Subscriptions
    Subscriptions subscriptions = new Subscriptions();
    subscriptions.setUri(resource.getSubscriptionsReference());
    DAOFactory.getSubscriptionsDAO().create(subscriptions);
    // Create the query based on the uri constraint
    Query query = DB.query();
    query.constrain(AttachedDevices.class);
    query.descend("uri").constrain(resource.getUri().split("/" + resource.getId())[0]);
    // Store all the founded resources
    ObjectSet<AttachedDevices> result = query.execute();

    // Update the lastModifiedTime attribute of the parent
    AttachedDevices attachedDevices = result.get(0);
    // Update the lastModifiedTime attribute of the parent
    attachedDevices.setLastModifiedTime(
        DateConverter.toXMLGregorianCalendar(new Date()).toString());
    DB.store(attachedDevices);
    // Validate the current transaction
    commit();
  }
  public ArticleBean queryArticleSingle(int id) {
    String sql = "select * from tb_article where id ='" + id + "'";
    ResultSet rs = connection.executeQuery(sql);
    try {
      while (rs.next()) {
        articleBean = new ArticleBean();
        articleBean.setId(rs.getInt(1));
        articleBean.setTypeId(rs.getInt(2));
        articleBean.setTitle(rs.getString(3));
        articleBean.setContent(rs.getString(4));
        articleBean.setSdTime(rs.getString(5));
        articleBean.setCreate(rs.getString(6));
        articleBean.setInfo(rs.getString(7));
        articleBean.setCount(rs.getInt(8));

        /* 查询tb_review数据表统计当前文章的评论数 */
        sql =
            "select count(id) from tb_review where review_article_articleId=" + articleBean.getId();
        ResultSet rsr = connection.executeQuery(sql);
        if (rsr != null) {
          rsr.next();
          articleBean.setReview(rsr.getInt(1));
          rsr.close();
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return articleBean;
  }
Пример #14
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html;charset=UTF-8");
   response.setCharacterEncoding("utf-8");
   request.setCharacterEncoding("utf-8");
   String Sno = request.getParameter("Sno");
   String Pno = request.getParameter("Pno");
   String sql = null;
   String[] Qnum = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
   DB db = new DB();
   for (int i = 0; i < Qnum.length; i++) {
     sql =
         "insert into testsystem.answer values ('"
             + Sno
             + "','"
             + Pno
             + "','"
             + Qnum[i]
             + "','"
             + request.getParameter(Qnum[i])
             + "',null);";
     db.update(sql);
     System.out.println(sql);
   }
   response.sendRedirect("student.jsp");
 }
Пример #15
0
  public static String getSumExhibitQty(String track_no) throws Exception {
    String ret = "";
    DB db = new DB();
    try {
      AppArrestProveExhibit aae = new AppArrestProveExhibit(db);

      String sql = "";
      sql +=
          "select sum(aae.qty) qty, nvl(aae.qty_unit_name,u.thname) unit_name, count(aae.id) count_qty";
      sql += " from application_arrest_exhibit aae ";
      sql += " left join unit u on u.unit_code = aae.qty_unit_code";
      sql += " where aae.track_no = '" + track_no + "' ";
      sql += " group by nvl(aae.qty_unit_name,u.thname) ";
      sql += " order by nvl(aae.qty_unit_name,u.thname) ";

      // System.out.println(sql);
      // Test track_no = TN4900000042400
      List<Map<String, Object>> list = aae.findBySql(sql);

      if (list.size() > 1) {
        int qty = 0;
        for (int i = 0; i < list.size(); i++) {
          qty +=
              (list.get(i).get("count_qty") != null
                  ? new Integer(list.get(i).get("count_qty").toString())
                  : null);
        }
        ret = Integer.toString(qty) + " รายการ";
      } else {
        for (int i = 0; i < list.size(); i++) {
          String qty =
              NumberUtil.getNumberFormat(new Double(list.get(i).get("qty").toString()), 0, "");
          if (!ret.equals("")) {
            ret +=
                "\n"
                    + qty
                    + " "
                    + (list.get(i).get("unit_name") != null
                        ? list.get(i).get("unit_name").toString()
                        : "");
          } else {
            ret =
                qty
                    + " "
                    + (list.get(i).get("unit_name") != null
                        ? list.get(i).get("unit_name").toString()
                        : "");
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      db.closedb();
    }

    return ret;
  }
  /**
   * Process
   *
   * @return message
   * @throws Exception
   */
  @Override
  protected String doIt() throws Exception {
    log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID);
    if (p_C_AcctSchema_ID == 0) throw new CompiereSystemException("C_AcctSchema_ID=0");
    MAcctSchema as = MAcctSchema.get(getCtx(), p_C_AcctSchema_ID);
    if (as.get_ID() == 0)
      throw new CompiereSystemException("Not Found - C_AcctSchema_ID=" + p_C_AcctSchema_ID);

    //	Update
    String sql =
        "UPDATE M_Product_Acct pa "
            + "SET (P_Revenue_Acct,P_Expense_Acct,P_CostAdjustment_Acct,P_InventoryClearing_Acct,P_Asset_Acct,P_COGS_Acct,"
            + " P_PurchasePriceVariance_Acct,P_InvoicePriceVariance_Acct,"
            + " P_TradeDiscountRec_Acct,P_TradeDiscountGrant_Acct,"
            + " P_Resource_Absorption_Acct, P_MaterialOverhd_Acct)="
            + " (SELECT P_Revenue_Acct,P_Expense_Acct,P_CostAdjustment_Acct,P_InventoryClearing_Acct,P_Asset_Acct,P_COGS_Acct,"
            + " P_PurchasePriceVariance_Acct,P_InvoicePriceVariance_Acct,"
            + " P_TradeDiscountRec_Acct,P_TradeDiscountGrant_Acct,"
            + " P_Resource_Absorption_Acct, P_MaterialOverhd_Acct"
            + " FROM M_Product_Category_Acct pca"
            + " WHERE pca.M_Product_Category_ID="
            + p_M_Product_Category_ID
            + " AND pca.C_AcctSchema_ID= pa.C_AcctSchema_ID "
            + "), Updated=SysDate, UpdatedBy=0 "
            + "WHERE pa.C_AcctSchema_ID= ? "
            + " AND EXISTS (SELECT * FROM M_Product p "
            + "WHERE p.M_Product_ID=pa.M_Product_ID"
            + " AND p.M_Product_Category_ID= ? )";
    int updated = DB.executeUpdate(get_TrxName(), sql, p_C_AcctSchema_ID, p_M_Product_Category_ID);
    addLog(0, null, new BigDecimal(updated), "@Updated@");

    //	Insert new Products
    sql =
        "INSERT INTO M_Product_Acct "
            + "(M_Product_ID, C_AcctSchema_ID,"
            + " AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy,"
            + " P_Revenue_Acct, P_Expense_Acct, P_CostAdjustment_Acct, P_InventoryClearing_Acct, P_Asset_Acct, P_CoGs_Acct,"
            + " P_PurchasePriceVariance_Acct, P_InvoicePriceVariance_Acct,"
            + " P_TradeDiscountRec_Acct, P_TradeDiscountGrant_Acct,"
            + " P_Resource_Absorption_Acct, P_MaterialOverhd_Acct) "
            + "SELECT p.M_Product_ID, acct.C_AcctSchema_ID,"
            + " p.AD_Client_ID, p.AD_Org_ID, 'Y', SysDate, 0, SysDate, 0,"
            + " acct.P_Revenue_Acct, acct.P_Expense_Acct, acct.P_CostAdjustment_Acct, acct.P_InventoryClearing_Acct, acct.P_Asset_Acct, acct.P_CoGs_Acct,"
            + " acct.P_PurchasePriceVariance_Acct, acct.P_InvoicePriceVariance_Acct,"
            + " acct.P_TradeDiscountRec_Acct, acct.P_TradeDiscountGrant_Acct,"
            + " acct.P_Resource_Absorption_Acct, acct.P_MaterialOverhd_Acct "
            + "FROM M_Product p"
            + " INNER JOIN M_Product_Category_Acct acct ON (acct.M_Product_Category_ID=p.M_Product_Category_ID)"
            + "WHERE acct.C_AcctSchema_ID= ? " //	#
            + " AND p.M_Product_Category_ID= ? " //	#
            + " AND NOT EXISTS (SELECT * FROM M_Product_Acct pa "
            + "WHERE pa.M_Product_ID=p.M_Product_ID"
            + " AND pa.C_AcctSchema_ID=acct.C_AcctSchema_ID)";
    int created = DB.executeUpdate(get_TrxName(), sql, p_C_AcctSchema_ID, p_M_Product_Category_ID);
    addLog(0, null, new BigDecimal(created), "@Created@");

    return "@Created@=" + created + ", @Updated@=" + updated;
  } //	doIt
Пример #17
0
 private synchronized Response findOne(DB db, String coll, DBObject q) throws IOException {
   OutMessage msg =
       OutMessage.query(db.getCollection(coll), 0, 0, -1, q, null, Bytes.MAX_OBJECT_SIZE);
   try {
     return call(msg, db.getCollection(coll), null);
   } finally {
     msg.doneWithMessage();
   }
 }
 public ProductorComponentePdf getProductorComponentePdf(final Seccion seccion) {
   ConfiguracionProductorPdf configuracionPdfSeccion = null;
   if (seccion.isGenerica()) {
     configuracionPdfSeccion = DB.recuperarSeccionGenerica();
   } else {
     configuracionPdfSeccion = DB.recuperarConfiguracionPdfSeccion(seccion);
   }
   return getFromContext(configuracionPdfSeccion.getClaveProductor());
 }
Пример #19
0
  private void ReadFull() throws SQLException {
    db.Start();
    String res = db.ReadFull();
    db.Close();
    System.out.println(res);

    // go to the beginning
    Menu();
  }
Пример #20
0
  public void run() {
    try {
      _db.init();
    } catch (DBException e) {
      // TODO make error logging level configurable
      e.printStackTrace();
      return;
    }

    try {
      _workloadstate = _workload.initThread(_props);
    } catch (WorkloadException e) {
      e.printStackTrace();
      return;
    }

    // spread the thread operations out so they don't all hit the DB at the same time
    try {
      // GH issue 4 - throws exception if _target>1 because random.nextInt argument must be >0
      // and the sleep() doesn't make sense for granularities < 1 ms anyway
      if ((_target > 0) && (_target <= 1.0)) {
        sleep(Utils.random().nextInt((int) (1.0 / _target)));
      }
    } catch (InterruptedException e) {
      // do nothing.
    }

    try {
      if (_dotransactions) {
        run(
            new OperationHandler() {
              @Override
              public boolean doOperation(DB db, Object workloadstate) {
                return _workload.doTransaction(db, workloadstate);
              }
            });
      } else {
        run(
            new OperationHandler() {
              @Override
              public boolean doOperation(DB db, Object workloadstate) {
                return _workload.doInsert(db, workloadstate);
              }
            });
      }

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

    try {
      _db.cleanup();
    } catch (DBException e) {
      e.printStackTrace();
    }
  }
  private void fullAssociated() {

    boolean associated = true;

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where M_product IS NULL AND XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) {
        associated = false;
      }

      rs.close();
      pstmt.close();

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    }

    if (associated == true) {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='Y'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);

      //			LineRefProv.setXX_ReferenceIsAssociated(true);
      //			LineRefProv.save();

      int dialog = Env.getCtx().getContextAsInt("#Dialog_Associate_Aux");

      if (dialog == 1) {
        ADialog.info(m_WindowNo, m_frame, "MustRefresh");
        Env.getCtx().remove("#Dialog_Associate_Aux");
      }

    } else {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='N'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);
      //			LineRefProv.setXX_ReferenceIsAssociated(false);
      //			LineRefProv.save();
    }
  }
Пример #22
0
 /**
  * @param name property name
  * @param defaultValue default value
  * @return if property exists, return its value, otherwise defaultValue.
  */
 public String get(String name, String defaultValue) {
   try {
     if (prefix != null) name = prefix + name;
     SysConfig cfg = (SysConfig) db.session().get(SysConfig.class, name);
     if (cfg != null) return cfg.getValue();
   } catch (HibernateException e) {
     db.getLog().warn(e);
   }
   return defaultValue;
 }
Пример #23
0
  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // открываем подключение к БД
    db = new DB(this);
    db.open();
    cursor = db.getAllData();
    startManagingCursor(cursor);
  }
Пример #24
0
  private void Search() throws SQLException {
    System.out.println("Name:");
    String text = InputString();
    db.Start();
    String res = db.Search(text);
    db.Close();
    System.out.println(res);

    // go to the beginning
    Menu();
  }
Пример #25
0
  public PhoneBook() throws SQLException {
    scan = new Scanner(System.in);

    db = new DB();
    db.Start();
    db.CreateTable();
    db.Close();

    System.out.println("PhoneBook v0.01\n");
    Menu();
  }
Пример #26
0
 public boolean hasProperty(String name) {
   try {
     if (prefix != null) name = prefix + name;
     SysConfig cfg = (SysConfig) db.session().get(SysConfig.class, name);
     return cfg != null;
   } catch (ObjectNotFoundException e) {
     // okay to happen
   } catch (HibernateException e) {
     db.getLog().warn(e);
   }
   return false;
 }
Пример #27
0
 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   String[] from = new String[] {CompanyTable.NAME};
   int[] to = new int[] {R.id.tv_company_item_without_button_name};
   db = DB.getInstance(MyDBHelper.getInstance(getActivity().getApplicationContext()));
   db.open();
   cursorAdapter = new CompanyCursorAdapter(getActivity().getApplicationContext(), null, 0, db);
   setListAdapter(cursorAdapter);
   db.companyCursorAdapter = cursorAdapter;
   getLoaderManager().initLoader(0, null, this);
 }
Пример #28
0
  public void save() {
    boolean isNoticed = false;
    if (!notice.isVisible()) {
      isNoticed = true;
      notice.setVisible(true);
      notice.setText("Saving...");
    }
    if (getOptions() != null) {
      DB database = null;
      try {
        database = factory.open(this.leveldbStore.getSelectedFile(), getOptions());
        DBIterator iterator = database.iterator();
        HashSet<byte[]> keys = new HashSet<>();

        for (iterator.seekToFirst(); iterator.hasNext(); iterator.next()) {
          keys.add(iterator.peekNext().getKey());
        }
        iterator.close();

        for (byte[] key : keys) {
          database.delete(key);
        }

        for (int i = 0; i < dataList.getModel().getSize(); ++i) {
          DBItem item = dataList.getModel().getElementAt(i);
          database.put(item.key, item.value);
        }
      } catch (Exception e) {
        JOptionPane.showMessageDialog(pane, "Unable to open database:\n" + e);
        e.printStackTrace();
      } finally {
        if (database != null) {
          try {
            database.close();
          } catch (IOException e) {
            JOptionPane.showMessageDialog(pane, "Unable to close database:\n" + e);
            e.printStackTrace();
          }
        }
        saveButton.setEnabled(false);
      }
    }
    if (isNoticed) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      notice.setVisible(false);
      notice.setText("");
    }
  }
Пример #29
0
 public static DB newDB(String name, Properties properties) throws UnknownDBException {
   ClassLoader classLoader = DBFactory.class.getClassLoader();
   DB db;
   try {
     Class dbClass = classLoader.loadClass(name);
     db = (DB) dbClass.newInstance();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
   db.setProperties(properties);
   return db;
 }
Пример #30
0
 public ResultCode get(long id) {
   try {
     return (ResultCode) db.session().load(ResultCode.class, new Long(id));
   } catch (ObjectNotFoundException e) {
     LogEvent evt = db.getLog().createWarn();
     evt.addMessage("error loading unconfigured result code " + id);
     evt.addMessage(e);
     Logger.log(evt);
   } catch (HibernateException e) {
     db.getLog().warn(e);
   }
   return null;
 }