Example #1
0
  public static long toLong(Object obj, final long longDefault) {

    if (obj instanceof Long) {
      return (Long) obj;
    }

    if (obj instanceof Number) {
      return ((Number) obj).longValue();
    } else if (obj instanceof CharSequence) {
      String str = Str.toString(obj);
      if (Dates.isJsonDate(str)) {
        return Dates.fromJsonDate(str).getTime();
      }

      try {
        return StringScanner.parseLong(str);
      } catch (Exception ex) {
        return longDefault;
      }
    } else if (obj instanceof Date) {
      return ((Date) obj).getTime();
    } else {
      return toInt(obj);
    }
  }
Example #2
0
  @Test
  public void Dates() {
    long current = System.currentTimeMillis();
    int dayInMillis = 24 * 60 * 60 * 1000;
    Date start = new Date(current);
    ds.delete(ds.createQuery(Dates.class));
    Dates d = new Dates();
    d.setDate(new Date(current + dayInMillis));
    ds.save(d);
    Date end = new Date(current + 2 * dayInMillis);

    assertEquals(d, query(dates).where(dates.date.between(start, end)).singleResult());
    assertEquals(0, query(dates).where(dates.date.between(new Date(0), start)).count());
  }
Example #3
0
  public static Date toEuroDate(String string) {

    String[] split = StringScanner.splitByChars(string, new char[] {'.', '\\', '/', ':'});

    if (split.length == 3) {
      return Dates.getEuroDate(toInt(split[0]), toInt(split[1]), toInt(split[2]));
    } else if (split.length >= 6) {
      return Dates.getEuroDate(
          toInt(split[0]),
          toInt(split[1]),
          toInt(split[2]),
          toInt(split[3]),
          toInt(split[4]),
          toInt(split[5]));
    } else {
      die(String.format("Not able to parse %s into a Euro date", string));
      return null;
    }
  }
Example #4
0
  public static Date toDate(Object object) {

    if (object instanceof Date) {
      return (Date) object;
    } else if (object instanceof Value) {
      return ((Value) object).dateValue();
    } else if (object instanceof Calendar) {
      return ((Calendar) object).getTime();
    } else if (object instanceof Long) {
      return new Date((long) object);
    } else if (object instanceof String) {
      String val = (String) object;
      char[] chars = FastStringUtils.toCharArray(val);
      if (Dates.isISO8601QuickCheck(chars)) {
        return Dates.fromISO8601DateLoose(chars);
      } else {
        return toDateUS(val);
      }
    }
    return null;
  }
Example #5
0
 // El número de factura para una factura nueva
 private String getCodigo() {
   // Usamos inicialización vaga
   if (codigo == null) {
     // Una consulta JPA para obtener el último número
     Query query =
         getManager().createQuery("select max(f.codigo) from Factura f where f.ano = :ano");
     // Dates es una utilidad de OpenXava
     query.setParameter("ano", Dates.getYear(new Date()));
     Integer lastNumber = (Integer) query.getSingleResult();
     if (lastNumber == null) lastNumber = 0;
     // Añadimos 1 al último número de factura
     codigo = Integer.toString(lastNumber + 1);
   }
   return codigo;
 }
  public void execute() throws Exception {
    // TODO Auto-generated method stub

    Long key = (Long) getView().getAllValues().get("id");

    System.out.println("\n\n\n\n\n\n\n\n\n\n The value sent===" + getView().getAllValues());
    Map payingAcct = (Map) getView().getAllValues().get("payingAccount");

    PaymentBatch batch = XPersistence.getManager().find(PaymentBatch.class, key);
    TransitAccount debitAccount = batch.getPayingAccount();

    if (payingAcct.get("id") != null) {
      debitAccount = (TransitAccount) MapFacade.findEntity("TransitAccount", payingAcct);
      batch.setPayingAccount(debitAccount);
      XPersistence.getManager().merge(batch);
    }
    if (UserManager.loginUserHasRole("funder") && debitAccount == null) {
      addError("As funder, You Need to Attach Debit Account", null);
      return;
    }

    Long transId = (Long) getView().getObject("transId");

    Boolean fina = (Boolean) getView().getObject("final");

    if (fina) {
      if (debitAccount == null) {
        addError(" Debit Account Yet To be Attached", null);
        return;
      }
      String token = (String) getView().getObject("token");
      String softToken = (String) getView().getValue("softToken");
      if (Is.empty(softToken)) {
        addError("Soft Token Is Required", null);
        return;
      }
      DateTime dT = (DateTime) getView().getObject("fiveMinutes");
      DateTime presentTime = new DateTime(Dates.withTime(Dates.createCurrent()));

      if (!Is.equalAsStringIgnoreCase(token, softToken)) {
        addError("Incorrect Soft Token", null);
        return;
      }
      if (dT.getMillis() < presentTime.getMillis()) {
        addError("Token Has Expired", null);
        return;
      }

      System.out.println(
          "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n The sent object to this place ===" + transId);
    }

    Transaction transaction = XPersistence.getManager().find(Transaction.class, transId);

    AsyncEventBus eventBus = new AsyncEventBus(Executors.newCachedThreadPool());
    eventBus.register(transaction);
    System.out.println(" 1111111approve already commented out......... ");
    eventBus.post(new Object());

    // transaction.approve();
    closeDialog();
    setNextMode(LIST);
  }
  public Object executeTask(Object object) throws Exception {
    List result;
    try {
      Map incomingRequest = (Map) object;
      DBSession dbs = (DBSession) incomingRequest.get("dbsession");
      String o = (String) incomingRequest.get("organizationId");
      String userId = (String) incomingRequest.get("userId");
      String userDateFormat = (String) incomingRequest.get("userDateFormat");
      BrowseObject b = (BrowseObject) incomingRequest.get("browseObject");
      List groupFilters = b.getGroupFilters();
      List groupFilterOptions = new ArrayList();
      List commodities = new ArrayList();
      // boolean unspscCommodities = PropertiesManager.getInstance(o).getProperty("MISC",
      // "CommodityType", "").equalsIgnoreCase("UNSPSC");
      boolean unspscCommodities = false;
      boolean commoditySet = false;

      PropertiesManager propertiesManager = PropertiesManager.getInstance(o);

      if (Utility.isEmpty(userDateFormat)) {
        userDateFormat = propertiesManager.getProperty("MISC", "DateFormat", "MM-dd-yyyy");
      }

      for (int ix = 0; ix < groupFilters.size(); ix++) {
        BrowseGroupFilter gf = (BrowseGroupFilter) groupFilters.get(ix);
        StringBuffer query = new StringBuffer();
        StringBuffer queryFilter = new StringBuffer();

        if (!Utility.isEmpty(gf.getType()) && gf.getType().equals("CostRange")) {
          incomingRequest.put("CostRange_itemType", incomingRequest.get("as_item_type"));
        }

        List dateArguments = new ArrayList();

        if (Utility.isEmpty(gf.getType()) || !gf.getType().equals("Keywords")) {
          query.append(gf.getSqlSelect() + " from " + gf.getSqlFrom() + " where 1 = 1");

          if (Utility.ckNull(gf.getSqlWhere()).length() > 0) {
            query.append(" and ( " + gf.getSqlWhere() + ")");
          }
          if (Utility.ckNull(b.getSqlWhere()).length() > 0) {
            String sqlWhere = b.getSqlWhere();
            sqlWhere = sqlWhere.replaceAll(":as_userid", "'" + userId + "'");
            if (sqlWhere.indexOf(":as_today") > 0) {
              dateArguments.add(
                  Dates.getDate(
                      Dates.today(userDateFormat, (String) incomingRequest.get("userTimeZone"))));
            }
            sqlWhere = sqlWhere.replaceAll(":as_today", "?");

            query.append(" and ( " + sqlWhere + ")");
          }

          List filters = b.getBrowseFilters();
          if (filters != null) {
            for (int i = 0; i < filters.size(); i++) {
              BrowseFilter filter = (BrowseFilter) filters.get(i);
              String key = filter.getColumnName();

              if (!b.validateColumn(key)) {
                // skip this filter
                continue;
              }

              String value = encoder.encodeForSQL(new OracleCodec(), filter.getValue());

              String operator = filter.getOperator();
              String logicalOperator = filter.getLogicalOperator();

              if (!BrowseValidationUtility.permissibleOperators.contains(operator)) {
                operator = "=";
              }

              if (!BrowseValidationUtility.permissibleLogicalOperators.contains(logicalOperator)) {
                logicalOperator = "AND";
              }

              String type = filter.getType();

              if (!Utility.isEmpty(value)) {
                if (Utility.isEmpty(operator)) {
                  operator = "=";
                }
                if (Utility.isEmpty(logicalOperator)) {
                  logicalOperator = "AND";
                }
                if (Utility.isEmpty(type)) {
                  type = "STRING";
                }

                if (queryFilter.length() > 0) {
                  queryFilter.append(" " + logicalOperator + " ");
                }

                if (type.equalsIgnoreCase("DATE")) {
                  dateArguments.add(Dates.getDate(userDateFormat, value));
                  queryFilter.append(" " + key + " " + operator + " ?");
                } else if (operator.equalsIgnoreCase("LIKE")) {
                  queryFilter.append(" UPPER(" + key + ") " + operator + " '" + value + "'");
                } else {
                  queryFilter.append(" " + key + " " + operator + " '" + value + "'");
                }

                if (key.indexOf(".commodity") > 0) {
                  if (!Utility.isEmpty(value)) {
                    commoditySet = true;
                    if (value.indexOf("%") > 0) {
                      String commodity = "00000000";
                      for (int iv = 0; iv < value.length(); iv++) {
                        char temp = value.charAt(iv);
                        if (temp != '%') {
                          if (iv == 0) {
                            commodity = temp + commodity.substring(iv + 1);
                          } else if (commodity.length() >= (iv + 1)) {
                            commodity =
                                commodity.substring(0, iv) + temp + commodity.substring(iv + 1);
                          } else {
                            commodity = commodity.substring(0, iv) + temp;
                          }
                        }
                      }
                      if (!commodities.contains(commodity)) {
                        commodities.add(commodity);
                      }
                    }
                  }
                }
              }
            }
          }

          if (queryFilter.length() > 0) {
            query.append("AND (" + queryFilter + " )");
          }

          if (gf.getType().equalsIgnoreCase("Commodity") && unspscCommodities) {
            String originalQueryString = query.toString();
            List commodityList = null;
            CommodityGetUNSPSCWhereClause commodityWhere = new CommodityGetUNSPSCWhereClause();

            int attempts = 0;
            while ((commodityList == null || commodityList.size() == 0) && attempts <= 3) {
              query = new StringBuffer(originalQueryString);

              String commodityArray[] = new String[commodities.size()];
              commodities.toArray(commodityArray);
              incomingRequest.put("Commodity_commodity", commodityArray);
              incomingRequest.put("retrieveAllCodes", "N");

              if (attempts > 0) {
                incomingRequest.put("retrieveAllFamilies", "Y");
                if (attempts > 1) {
                  incomingRequest.put("retrieveAllGroups", "Y");
                  if (attempts > 2) {
                    incomingRequest.put("retrieveAllCommodities", "Y");
                  }
                }
              }

              String unspscWhere = (String) commodityWhere.executeTask(incomingRequest);
              if (!Utility.isEmpty(unspscWhere)) {
                query.append(" AND (" + unspscWhere + ")");
              }

              if (!Utility.isEmpty(gf.getSqlGroupBy())) {
                query.append(" group by " + gf.getSqlGroupBy());
              }
              if (!Utility.isEmpty(gf.getSqlOrderBy())) {
                query.append(" order by " + gf.getSqlOrderBy());
              }

              Log.debug(this, "group filter query: " + query.toString());

              Object arguments[] = new Object[dateArguments.size()];
              for (int i = 0; i < dateArguments.size(); i++) {
                arguments[i] = dateArguments.get(i);
              }
              commodityList = dbs.query(query.toString(), arguments);

              attempts++;
            }

            gf.setSelectionValues(commodityList);
          } else {
            if (!Utility.isEmpty(gf.getSqlGroupBy())) {
              query.append(" group by " + gf.getSqlGroupBy());
            }
            if (!Utility.isEmpty(gf.getSqlOrderBy())) {
              query.append(" order by " + gf.getSqlOrderBy());
            }

            Log.debug(this, "group filter query: " + query.toString());

            Object arguments[] = new Object[dateArguments.size()];
            for (int i = 0; i < dateArguments.size(); i++) {
              arguments[i] = dateArguments.get(i);
            }
            List list = dbs.query(query.toString(), arguments);

            gf.setSelectionValues(list);
          }
        }
      }

      result = groupFilters;

      this.setStatus(dbs.getStatus());
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
    return result;
  }
  /* (non-Javadoc)
   * @see com.tsagate.puridiom.process.ITask#executeTask(java.lang.Object)
   */
  public Object executeTask(Object object) throws Exception {

    Map incomingRequest = (Map) object;
    Object result = null;

    try {
      String organizationId = (String) incomingRequest.get("organizationId");
      String userDateFormat = (String) incomingRequest.get("userDateFormat");
      PropertiesManager propertiesManager = PropertiesManager.getInstance(organizationId);
      CatalogSecurity catalogSecurity = (CatalogSecurity) incomingRequest.get("catalogSecurity");
      String isCatalog = HiltonUtility.ckNull((String) incomingRequest.get("isCatalog"));
      String catalogId = (String) catalogSecurity.getCatalogId();
      String accesType = (String) catalogSecurity.getAccessType();
      String accessId = (String) catalogSecurity.getAccessId();

      if (HiltonUtility.isEmpty(userDateFormat)) {
        userDateFormat = propertiesManager.getProperty("MISC", "DateFormat", "MM-dd-yyyy");
      }

      String today = Dates.today(userDateFormat, (String) incomingRequest.get("userTimeZone"));

      if (isCatalog.equalsIgnoreCase("V")) {
        DBSession dbs = (DBSession) incomingRequest.get("dbsession");

        String queryString =
            "from CatalogSecurity as cs "
                + "where cs.catalogId = ? and cs.itemNumber != '0' "
                + "and cs.accessType = ? ";

        List resultList =
            dbs.query(
                queryString,
                new Object[] {catalogId, accesType},
                new Type[] {Hibernate.STRING, Hibernate.STRING});

        if (resultList != null && resultList.size() > 0) {
          for (int i = 0; i < resultList.size(); i++) {
            CatalogSecurity catalogItemSecurity = (CatalogSecurity) resultList.get(i);

            if (!accessId.equalsIgnoreCase(catalogItemSecurity.getAccessId())) {
              PuridiomProcessLoader processLoader =
                  new PuridiomProcessLoader((String) incomingRequest.get("organizationId"));
              PuridiomProcess process = processLoader.loadProcess("catalogsecurity-add.xml");

              Map updateParameters = new HashMap();

              updateParameters.put("organizationId", organizationId);
              updateParameters.put("dbsession", incomingRequest.get("dbsession"));

              updateParameters.put(
                  "CatalogSecurity_catalogId", (String) catalogSecurity.getCatalogId());
              updateParameters.put(
                  "CatalogSecurity_itemNumber", (String) catalogItemSecurity.getItemNumber());
              updateParameters.put(
                  "CatalogSecurity_accessType", (String) catalogSecurity.getAccessType());
              updateParameters.put(
                  "CatalogSecurity_accessId", (String) catalogSecurity.getAccessId());
              updateParameters.put("CatalogSecurity_owner", (String) catalogSecurity.getOwner());
              updateParameters.put("CatalogSecurity_dateEntered", today);
              updateParameters.put("CatalogSecurity_dateChanged", today);
              updateParameters.put(
                  "CatalogSecurity_lastChangedBy", (String) catalogSecurity.getCatalogId());

              process.executeProcess(updateParameters);

              catalogSecurity.setAccessId(accessId);

              dbs.add(catalogSecurity);
              if (dbs.getStatus() != Status.SUCCEEDED) {
                throw new TsaException(
                    "error ocurred at update catalog security from  for "
                        + catalogSecurity.getItemNumber());
              }
            }
          }
        }
      }

      this.setStatus(Status.SUCCEEDED);
    } catch (Exception e) {
      this.setStatus(Status.FAILED);
      Log.error(this, "An Error occurred at CatalogItemSecurityAddFromCatalog" + e);
      e.printStackTrace();
      throw e;
    }
    return result;
  }