Example usage for java.util GregorianCalendar add

List of usage examples for java.util GregorianCalendar add

Introduction

In this page you can find the example usage for java.util GregorianCalendar add.

Prototype

@Override
public void add(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.

Usage

From source file:com.sapienter.jbilling.server.process.AgeingBL.java

/**
 * Goes over all the users that are not active, and calls age on them.
 * This doesn't discriminate over entities.
 *///from   w w w. j a  v  a2  s . co  m
public void reviewAll(Date today) throws NamingException, SessionInternalError, SQLException {
    // go over all the users already in the ageing system
    for (UserDTO userRow : new UserDAS().findAgeing()) {
        age(userRow, today);
    }

    // now go over the active users with payable invoices
    UserBL user = new UserBL();
    CachedRowSet usersSql;
    try {
        usersSql = user.findActiveWithOpenInvoices();
    } catch (Exception e) {
        // avoid further problems
        LOG.error("Exception finding users to age", e);
        return;
    }

    InvoiceBL invoiceBL = new InvoiceBL();

    while (usersSql.next()) {
        Integer userId = new Integer(usersSql.getInt(1));
        user.set(userId);
        UserDTO userRow = user.getEntity();
        // get the grace period for the entity of this user
        PreferenceBL prefs = new PreferenceBL();
        prefs.set(userRow.getEntity().getId(), Constants.PREFERENCE_GRACE_PERIOD);
        int gracePeriod = prefs.getInt();
        LOG.debug("Reviewing invoices of user:" + userRow.getUserId() + " grace: " + gracePeriod);
        // now go over this user's pending invoices
        for (Iterator it2 = invoiceBL.getHome().findProccesableByUser(userRow).iterator(); it2.hasNext();) {
            InvoiceDTO invoice = (InvoiceDTO) it2.next();
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(invoice.getDueDate());
            if (gracePeriod > 0) {
                cal.add(Calendar.DATE, gracePeriod);
            }

            if (userRow.getUserId().intValue() == 17) {
                LOG.debug("invoice " + invoice.getId() + " due+grace=" + cal.getTime() + " today=" + today
                        + " compare=" + (cal.getTime().compareTo(today)));
            }

            if (cal.getTime().compareTo(today) < 0) {
                // ok, this user has an overdue invoice
                age(userRow, today);
                break;
            }
        }
    }
}

From source file:com.silverpeas.ical.ImportIcalManager.java

/**
 * IMPORT SilverpeasCalendar in Ical format
 * @param file/*from ww  w.  java  2s . c o  m*/
 * @return
 * @throws Exception
 */
public String importIcalAgenda(File file) throws Exception {
    SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_ENTER_METHOD");
    String returnCode = AgendaSessionController.IMPORT_FAILED;
    InputStreamReader inputStream = null;
    XmlReader xr = null;
    try {
        String charsetUsed = agendaSessionController.getSettings().getString("defaultCharset");
        if (StringUtil.isDefined(charset)) {
            charsetUsed = charset;
        }

        // File Encoding detection
        xr = new XmlReader(file);
        SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "Encoding = " + xr.getEncoding());
        if (StringUtil.isDefined(xr.getEncoding())) {
            charsetUsed = xr.getEncoding();
        }
        inputStream = new InputStreamReader(new FileInputStream(file), charsetUsed);
        CalendarBuilder builder = new CalendarBuilder();
        Calendar calendar = builder.build(inputStream);
        // Get all EVENTS
        for (Object o : calendar.getComponents(Component.VEVENT)) {
            VEvent eventIcal = (VEvent) o;
            String name = getFieldEvent(eventIcal.getProperty(Property.SUMMARY));

            String description = null;
            if (StringUtil.isDefined(getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION)))) {
                description = getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION));
            }

            // Name is mandatory in the Silverpeas Agenda
            if (!StringUtil.isDefined(name)) {
                if (StringUtil.isDefined(description)) {
                    name = description;
                } else {
                    name = " ";
                }
            }

            String priority = getFieldEvent(eventIcal.getProperty(Property.PRIORITY));
            if (!StringUtil.isDefined(priority)) {
                priority = Priority.UNDEFINED.getValue();
            }
            String classification = getFieldEvent(eventIcal.getProperty(Property.CLASS));
            String startDate = getFieldEvent(eventIcal.getProperty(Property.DTSTART));
            String endDate = getFieldEvent(eventIcal.getProperty(Property.DTEND));
            Date startDay = getDay(startDate);
            String startHour = getHour(startDate);
            Date endDay = getDay(endDate);
            String endHour = getHour(endDate);
            // Duration of the event
            long duration = endDay.getTime() - startDay.getTime();
            boolean allDay = false;

            // All day case
            // I don't know why ??
            if (("00:00".equals(startHour) && "00:00".equals(endHour))
                    || (!StringUtil.isDefined(startHour) && !StringUtil.isDefined(endHour))) {
                // For complete Day
                startHour = "";
                endHour = "";
                allDay = true;
            }

            // Get reccurrent dates
            Collection reccurenceDates = getRecurrenceDates(eventIcal);

            // No reccurent dates
            if (reccurenceDates == null) {
                String idEvent = isExist(eventIcal);
                // update if event already exists, create if does not exist
                if (StringUtil.isDefined(idEvent)) {
                    agendaSessionController.updateJournal(idEvent, name, description, priority, classification,
                            startDay, startHour, endDay, endHour);
                } else {
                    idEvent = agendaSessionController.addJournal(name, description, priority, classification,
                            startDay, startHour, endDay, endHour);
                }

                // Get Categories
                processCategories(eventIcal, idEvent);
            } else {
                for (Object reccurenceDate : reccurenceDates) {
                    // Reccurent event startDate
                    startDay = (DateTime) reccurenceDate;
                    // Reccurent event endDate
                    long newEndDay = startDay.getTime() + duration;
                    endDay = new DateTime(newEndDay);
                    if (allDay) {
                        // So we have to convert this date to agenda format date
                        GregorianCalendar gregCalendar = new GregorianCalendar();
                        gregCalendar.setTime(endDay);
                        gregCalendar.add(GregorianCalendar.DATE, -1);
                        endDay = new Date(gregCalendar.getTime());
                    }
                    String idEvent = isExist(eventIcal, startDay, endDay, startHour);
                    // update if event already exists, create if does not exist
                    if (StringUtil.isDefined(idEvent)) {
                        SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()",
                                "root.MSG_GEN_PARAM_VALUE" + "Update event: " + DateUtil.date2SQLDate(startDay)
                                        + " " + startHour + " to " + DateUtil.date2SQLDate(endDay) + " "
                                        + endHour);
                        agendaSessionController.updateJournal(idEvent, name, description, priority,
                                classification, startDay, startHour, endDay, endHour);
                    } else {
                        SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()",
                                "root.MSG_GEN_PARAM_VALUE" + "Create event: " + DateUtil.date2SQLDate(startDay)
                                        + " " + startHour + " to " + DateUtil.date2SQLDate(endDay) + " "
                                        + endHour);
                        idEvent = agendaSessionController.addJournal(name, description, priority,
                                classification, startDay, startHour, endDay, endHour);
                    }
                    // Get Categories
                    processCategories(eventIcal, idEvent);
                }
            }
        }
        returnCode = AgendaSessionController.IMPORT_SUCCEEDED;
    } catch (Exception e) {
        SilverTrace.error("agenda", "ImportIcalManager.importIcalAgenda()", e.getCause().toString());
        returnCode = AgendaSessionController.IMPORT_FAILED;
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(xr);
    }
    SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_EXIT_METHOD");
    return returnCode;
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from   w  ww  .j av a 2 s .  c o m*/
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }

        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }

    // check that
    try {
        tx.setFtChargedAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();

        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);

        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        boolean found = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                found = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(found);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

From source file:org.silverpeas.core.web.calendar.ical.ImportIcalManager.java

/**
   * IMPORT SilverpeasCalendar in Ical format
   * @param file//from  ww  w  .ja v a 2 s . co m
   * @return
   * @throws Exception
   */
  public String importIcalAgenda(File file) throws Exception {
      String returnCode = AgendaSessionController.IMPORT_FAILED;
      InputStreamReader inputStream = null;
      XmlReader xr = null;
      try {
          String charsetUsed = agendaSessionController.getSettings().getString("defaultCharset");
          if (isDefined(charset)) {
              charsetUsed = charset;
          }

          // File Encoding detection
          xr = new XmlReader(file);
          if (isDefined(xr.getEncoding())) {
              charsetUsed = xr.getEncoding();
          }
          inputStream = new InputStreamReader(new FileInputStream(file), charsetUsed);
          CalendarBuilder builder = new CalendarBuilder();
          Calendar calendar = builder.build(inputStream);
          // Get all EVENTS
          for (Object o : calendar.getComponents(Component.VEVENT)) {
              VEvent eventIcal = (VEvent) o;
              String name = getFieldEvent(eventIcal.getProperty(Property.SUMMARY));

              String description = null;
              if (isDefined(getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION)))) {
                  description = getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION));
              }

              // Name is mandatory in the Silverpeas Agenda
              if (!isDefined(name)) {
                  if (isDefined(description)) {
                      name = description;
                  } else {
                      name = " ";
                  }
              }

              String priority = getFieldEvent(eventIcal.getProperty(Property.PRIORITY));
              if (!isDefined(priority)) {
                  priority = Priority.UNDEFINED.getValue();
              }
              String classification = getFieldEvent(eventIcal.getProperty(Property.CLASS));
              String startDate = getFieldEvent(eventIcal.getProperty(Property.DTSTART));
              String endDate = getFieldEvent(eventIcal.getProperty(Property.DTEND));
              Date startDay = getDay(startDate);
              String startHour = getHour(startDate);
              Date endDay = getDay(endDate);
              String endHour = getHour(endDate);
              // Duration of the event
              long duration = endDay.getTime() - startDay.getTime();
              boolean allDay = false;

              // All day case
              // I don't know why ??
              if (("00:00".equals(startHour) && "00:00".equals(endHour))
                      || (!isDefined(startHour) && !isDefined(endHour))) {
                  // For complete Day
                  startHour = "";
                  endHour = "";
                  allDay = true;
              }

              // Get reccurrent dates
              Collection reccurenceDates = getRecurrenceDates(eventIcal);

              // No reccurent dates
              if (reccurenceDates.isEmpty()) {
                  String idEvent = isExist(eventIcal);
                  // update if event already exists, create if does not exist
                  if (isDefined(idEvent)) {
                      agendaSessionController.updateJournal(idEvent, name, description, priority, classification,
                              startDay, startHour, endDay, endHour);
                  } else {
                      idEvent = agendaSessionController.addJournal(name, description, priority, classification,
                              startDay, startHour, endDay, endHour);
                  }

                  // Get Categories
                  processCategories(eventIcal, idEvent);
              } else {
                  for (Object reccurenceDate : reccurenceDates) {
                      // Reccurent event startDate
                      startDay = (DateTime) reccurenceDate;
                      // Reccurent event endDate
                      long newEndDay = startDay.getTime() + duration;
                      endDay = new DateTime(newEndDay);
                      if (allDay) {
                          // So we have to convert this date to agenda format date
                          GregorianCalendar gregCalendar = new GregorianCalendar();
                          gregCalendar.setTime(endDay);
                          gregCalendar.add(GregorianCalendar.DATE, -1);
                          endDay = new Date(gregCalendar.getTime());
                      }
                      String idEvent = isExist(eventIcal, startDay, endDay, startHour);
                      // update if event already exists, create if does not exist
                      if (isDefined(idEvent)) {
                          agendaSessionController.updateJournal(idEvent, name, description, priority,
                                  classification, startDay, startHour, endDay, endHour);
                      } else {
                          idEvent = agendaSessionController.addJournal(name, description, priority,
                                  classification, startDay, startHour, endDay, endHour);
                      }
                      // Get Categories
                      processCategories(eventIcal, idEvent);
                  }
              }
          }
          returnCode = AgendaSessionController.IMPORT_SUCCEEDED;
      } catch (Exception e) {
          SilverTrace.error("agenda", "ImportIcalManager.importIcalAgenda()", e.getCause().toString());
          returnCode = AgendaSessionController.IMPORT_FAILED;
      } finally {
          IOUtils.closeQuietly(inputStream);
          IOUtils.closeQuietly(xr);
      }
      return returnCode;
  }

From source file:org.xdi.oxauth.client.TokenRequest.java

public String getClientAssertion() {
    Jwt clientAssertion = new Jwt();

    if (algorithm == null) {
        algorithm = SignatureAlgorithm.HS256;
    }//w  w  w. j  a  v a  2 s .c  o  m
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    Date issuedAt = calendar.getTime();
    calendar.add(Calendar.MINUTE, 5);
    Date expirationTime = calendar.getTime();

    // Header
    clientAssertion.getHeader().setType(JwtType.JWS);
    clientAssertion.getHeader().setAlgorithm(algorithm);
    if (StringUtils.isNotBlank(keyId)) {
        clientAssertion.getHeader().setKeyId(keyId);
    }

    // Claims
    clientAssertion.getClaims().setIssuer(getAuthUsername());
    clientAssertion.getClaims().setSubjectIdentifier(getAuthUsername());
    clientAssertion.getClaims().setAudience(audience);
    clientAssertion.getClaims().setJwtId(UUID.randomUUID());
    clientAssertion.getClaims().setExpirationTime(expirationTime);
    clientAssertion.getClaims().setIssuedAt(issuedAt);

    // Signature
    try {
        if (algorithm == SignatureAlgorithm.HS256 || algorithm == SignatureAlgorithm.HS384
                || algorithm == SignatureAlgorithm.HS512) {
            if (sharedKey == null) {
                sharedKey = getAuthPassword();
            }
            HMACSigner hmacSigner = new HMACSigner(algorithm, sharedKey);
            clientAssertion = hmacSigner.sign(clientAssertion);
        } else if (algorithm == SignatureAlgorithm.RS256 || algorithm == SignatureAlgorithm.RS384
                || algorithm == SignatureAlgorithm.RS512) {
            RSASigner rsaSigner = new RSASigner(algorithm, rsaPrivateKey);
            clientAssertion = rsaSigner.sign(clientAssertion);
        } else if (algorithm == SignatureAlgorithm.ES256 || algorithm == SignatureAlgorithm.ES384
                || algorithm == SignatureAlgorithm.ES512) {
            ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, ecPrivateKey);
            clientAssertion = ecdsaSigner.sign(clientAssertion);
        }
    } catch (SignatureException e) {
        return null;
    } catch (InvalidJwtException e) {
        return null;
    }

    return clientAssertion.toString();
}

From source file:edu.umm.radonc.ca_dash.model.ActivityFacade.java

public TreeMap<Date, SynchronizedDescriptiveStatistics> getWeeklyTrailingSummaryStats(Date start, Date end,
        Long hospitalser, boolean imrtOnly, boolean includeWeekends) {
    TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(end);//from w w  w.  j av  a2  s . c  o  m
    Date d;
    SynchronizedDescriptiveStatistics stats;
    while (gc.getTime().compareTo(start) > 0) {
        d = gc.getTime();
        gc.add(Calendar.DATE, -7);
        if (hospitalser <= 0) {
            stats = getDailyStats(gc.getTime(), d, imrtOnly, includeWeekends);
        } else {
            stats = getDailyStats(gc.getTime(), d, hospitalser, imrtOnly, includeWeekends);
        }
        retval.put(gc.getTime(), stats);
    }

    return retval;

}

From source file:com.handywedge.binarystore.store.azure.BinaryStoreManagerImpl.java

private BinaryInfo createReturnBinaryInfo(CloudBlockBlob blob) throws StoreException {
    BinaryInfo binary = new BinaryInfo();
    try {//from ww  w. j  av a2 s. c o  m
        if (blob.exists()) {
            long milliSeconds = Long.parseLong(PropertiesUtil.get("abs.presignedurl.expiration"));

            binary.setBucketName(blob.getContainer().getName());
            binary.setFileName(blob.getName());
            binary.setContentType(blob.getProperties().getContentType());
            binary.setSize(blob.getProperties().getLength());
            binary.setUrl(blob.getUri().toString());

            // Policy
            SharedAccessBlobPolicy itemPolicy = new SharedAccessBlobPolicy();

            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            calendar.setTime(new Date());
            itemPolicy.setSharedAccessStartTime(calendar.getTime());

            calendar.add(Calendar.SECOND, (int) (milliSeconds / 1000));
            itemPolicy.setSharedAccessExpiryTime(calendar.getTime());

            itemPolicy.setPermissions(
                    EnumSet.of(SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.READ));

            String sasToken = blob.generateSharedAccessSignature(itemPolicy, null);
            Thread.sleep(1500);

            String sasUri = String.format("%s?%s", blob.getUri().toString(), sasToken);
            binary.setPresignedUrl(sasUri);

            logger.debug(" ????URL: {}", binary.getUrl());
            logger.debug(" ????URL: {}", binary.getPresignedUrl());

        } else {
            binary = null;
        }
    } catch (URISyntaxException ue) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ue, blob.getName());
    } catch (NumberFormatException ne) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ne, blob.getName());
    } catch (InvalidKeyException ie) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ie, blob.getName());
    } catch (InterruptedException ite) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ite, blob.getName());
    } catch (StorageException se) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                se, blob.getName());
    }

    return binary;
}

From source file:org.mule.modules.zuora.zuora.api.CxfZuoraClient.java

@Override
public Map<String, Object> accountProfile(String accountId) throws Exception {
    // TODO Auto-generated method stub

    HashMap<String, Object> accountMap = new HashMap<String, Object>();
    Validate.notEmpty(accountId);/*  w  ww .  j  a v  a  2s  . c  o  m*/

    String accountQuery = "select AccountNumber,AdditionalEmailAddresses,AllowInvoiceEdit,AutoPay,Balance,Batch,BillCycleDay,BillToId,CommunicationProfileId,CreatedById,CreatedDate,CreditBalance,CrmId,Currency,CustomerServiceRepName,DefaultPaymentMethodId,InvoiceDeliveryPrefsEmail,InvoiceDeliveryPrefsPrint,InvoiceTemplateId,LastInvoiceDate,Name,Notes,ParentId,PaymentGateway,PaymentTerm,PurchaseOrderNumber,SalesRepName,SoldToId,Status,TaxExemptCertificateId,TaxExemptCertificateType,TaxExemptDescription,TaxExemptEffectiveDate,TaxExemptExpirationDate,TaxExemptIssuingJurisdiction,TaxExemptStatus,TotalInvoiceBalance,UpdatedById,UpdatedDate  from Account where id = '"
            + accountId + "'";

    QueryResult qr = this.soap.query(accountQuery);

    if (qr.getSize() != 0) {

        Collection<Entry<String, Object>> accountCollection = qr.getRecords().get(0).properties();

        accountMap = getAsHashMap(accountCollection);
        if (accountMap.get("defaultPaymentMethodId") != null) {
            String paymentMethodQuery = "SELECT AchAbaCode,AchAccountName,AchAccountNumberMask,AchAccountType,AchBankName,Active,BankBranchCode,BankCheckDigit,BankCity,BankCode,BankIdentificationNumber,BankName,BankPostalCode,BankStreetName,BankStreetNumber,BankTransferAccountName,BankTransferAccountType,BankTransferType,CreatedById,CreatedDate,CreditCardAddress1,CreditCardAddress2,CreditCardCity,CreditCardCountry,Id, CreditCardExpirationMonth, CreditCardExpirationYear, CreditCardMaskNumber,CreditCardHolderName,CreditCardPostalCode,CreditCardState,CreditCardType,DeviceSessionId,Email,IPAddress,LastFailedSaleTransactionDate,LastTransactionDateTime,LastTransactionStatus,MaxConsecutivePaymentFailures,Name,NumConsecutiveFailures,PaymentMethodStatus,PaymentRetryWindow,PaypalBaid,PaypalEmail,PaypalPreapprovalKey,PaypalType,Phone,TotalNumberOfErrorPayments,TotalNumberOfProcessedPayments,Type,UpdatedById,UpdatedDate,UseDefaultRetryRule from PaymentMethod where Id = '"
                    + accountMap.get("defaultPaymentMethodId") + "'";

            Collection<Entry<String, Object>> paymentMethodCollection = this.soap.query(paymentMethodQuery)
                    .getRecords().get(0).properties();

            if (paymentMethodCollection.size() > 0) {
                accountMap.put("paymentMethod", getAsHashMap(paymentMethodCollection));
            }
        }
        GregorianCalendar lastMonth = new GregorianCalendar();
        lastMonth.add(GregorianCalendar.MONTH, -1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        String lastMonthString = df.format(lastMonth.getTime());

        String paymentQuery = "SELECT AccountingCode,Amount,AppliedCreditBalanceAmount,AuthTransactionId,BankIdentificationNumber,CancelledOn,Comment,CreatedById,CreatedDate,EffectiveDate,GatewayOrderId,GatewayResponse,GatewayResponseCode,GatewayState,MarkedForSubmissionOn,PaymentMethodID,PaymentNumber,ReferenceId,RefundAmount,SecondPaymentReferenceId,SettledOn,SoftDescriptor, SoftDescriptorPhone, Status, SubmittedOn,TransferredToAccounting,Type,UpdatedById,UpdatedDate from Payment where Id = '"
                + accountId + "' and EffectiveDate >= '" + lastMonthString + "'";

        List<ZObject> paymentZList = this.soap.query(paymentQuery).getRecords();

        List<Map<String, Object>> paymentResultList = new ArrayList<Map<String, Object>>();
        for (ZObject zPayment : paymentZList) {
            if (zPayment != null) {
                Collection<Entry<String, Object>> paymentCollection = zPayment.properties();
                paymentResultList.add(getAsHashMap(paymentCollection));
            }
        }

        if (paymentResultList.size() > 0) {
            accountMap.put("payments", paymentResultList);
        }
        String billToQuery = "select AccountId, Address1, Address2, City, Country, County, CreatedById, CreatedDate, Description, Fax, FirstName, HomePhone, LastName, MobilePhone, NickName, OtherPhone, OtherPhoneType, PersonalEmail, PostalCode, State, TaxRegion, UpdatedById, UpdatedDate, WorkEmail, WorkPhone from contact where id='"
                + accountMap.get("billToId") + "'";
        QueryResult qrBillTo = this.soap.query(billToQuery);
        if (qrBillTo.getSize() > 0) {
            Collection<Entry<String, Object>> billToCollection = qrBillTo.getRecords().get(0).properties();
            HashMap<String, Object> billToMap = new HashMap<String, Object>();
            billToMap = getAsHashMap(billToCollection);
            if (billToMap.size() > 0) {
                accountMap.put("billTo", billToMap);
            }
        }

        String subscriptionQuery = "SELECT AutoRenew,CancelledDate,ContractAcceptanceDate,ContractEffectiveDate,CreatedById,CreatedDate,CreatorAccountId,InitialTerm,IsInvoiceSeparate,Name,Notes,OriginalCreatedDate,OriginalId,PreviousSubscriptionId,RenewalTerm,ServiceActivationDate,Status,SubscriptionEndDate,SubscriptionStartDate,TermEndDate,TermStartDate,TermType,UpdatedById,UpdatedDate,Version from Subscription where AccountId = '"
                + accountId + "' and status='Active'";

        List<ZObject> subscriptionZList = this.soap.query(subscriptionQuery).getRecords();

        List<Map<String, Object>> subscriptionResultList = new ArrayList<Map<String, Object>>();
        for (ZObject zSubscription : subscriptionZList) {
            if (zSubscription != null) {
                Collection<Entry<String, Object>> subscriptionCollection = zSubscription.properties();

                Map<String, Object> subscriptionMap = getAsHashMap(subscriptionCollection);

                String rateplanQuery = "SELECT AmendmentId,AmendmentSubscriptionRatePlanId,AmendmentType,CreatedById,CreatedDate,Name,ProductRatePlanId,UpdatedById,UpdatedDate from RatePlan where SubscriptionId ='"
                        + subscriptionMap.get("id") + "'";

                List<ZObject> ratePlanZList = this.soap.query(rateplanQuery).getRecords();

                List<Map<String, Object>> ratePlanResultList = new ArrayList<Map<String, Object>>();
                for (ZObject zRatePlan : ratePlanZList) {
                    if (zRatePlan != null) {
                        Collection<Entry<String, Object>> ratePlanCollection = zRatePlan.properties();

                        Map<String, Object> ratePlanMap = getAsHashMap(ratePlanCollection);
                        List<Map<String, Object>> ratePlanChargeResultList = new ArrayList<Map<String, Object>>();
                        String rateplanchargeQuery = "SELECT AccountingCode,ApplyDiscountTo,BillCycleDay,BillCycleType,BillingPeriodAlignment,ChargedThroughDate,ChargeModel,ChargeNumber,ChargeType,CreatedById,CreatedDate,Description,DiscountLevel,DMRC,DTCV,EffectiveEndDate,EffectiveStartDate,IsLastSegment,MRR,Name,NumberOfPeriods,OriginalId,OverageCalculationOption,OverageUnusedUnitsCreditOption,Price,ProcessedThroughDate,ProductRatePlanChargeId,Quantity,Segment,TCV,TriggerDate,TriggerEvent,UnusedUnitsCreditRates,UOM,UpdatedById,UpdatedDate,UpToPeriods,Version from RatePlanCharge where RatePlanId ='"
                                + ratePlanMap.get("id") + "'";
                        List<ZObject> ratePlanChargeZList = this.soap.query(rateplanchargeQuery).getRecords();
                        for (ZObject zRatePlanCharge : ratePlanChargeZList) {
                            if (zRatePlanCharge != null) {
                                Collection<Entry<String, Object>> ratePlanChargeCollection = zRatePlanCharge
                                        .properties();
                                ratePlanChargeResultList.add(getAsHashMap(ratePlanChargeCollection));

                            }
                        }
                        ratePlanMap.put("ratePlanCharges", ratePlanChargeResultList);
                        ratePlanResultList.add(ratePlanMap);
                    }
                }
                subscriptionMap.put("ratePlans", ratePlanResultList);

                subscriptionResultList.add(subscriptionMap);
            }
        }

        if (subscriptionResultList.size() > 0) {
            accountMap.put("subscriptions", subscriptionResultList);
        }

    } else {
        accountMap.put("error", "Unable to find an account with the id: " + accountId);
    }

    return accountMap;
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

private boolean isCorrectCRL(final CRL crl, final String issuerDN) {
    if (!(crl instanceof X509CRL)) {
        return false;
    }/*from w  ww.j av a 2  s.co m*/

    X509CRL x509crl = (X509CRL) crl;
    if (!StringUtils.equals(issuerDN, CertTools.getIssuerDN(x509crl))) {
        return false;
    }

    final Date now = new Date(System.currentTimeMillis());
    final Date nextUpdate = x509crl.getNextUpdate();
    if (nextUpdate != null) {
        if (nextUpdate.after(now)) {
            return true;
        }

        if (log.isDebugEnabled()) {
            log.debug("CRL issued by " + issuerDN + " is out of date");
        }
        return false;
    }

    final Date thisUpdate = x509crl.getThisUpdate();
    if (thisUpdate != null) {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(now);
        gc.add(Calendar.HOUR, 1);
        final Date expire = gc.getTime();

        if (expire.before(now)) {
            if (log.isDebugEnabled()) {
                log.debug("Could not find when CRL issued by " + issuerDN
                        + " should be updated and this CRL is over one hour old. Not using it");
            }
            return false;
        }

        log.warn("Could not find when CRL issued by " + issuerDN
                + " should be updated, but this CRL was issued less than an hour ago, so we are using it");
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Could not check issuance time for CRL issued by " + issuerDN);
    }
    return false;
}

From source file:es.tid.fiware.rss.controller.SettlementController.java

/**
 * Do settlement./*from  w ww.j  a  v a  2  s  .c  om*/
 * 
 * @param dateFrom
 * @param dateTo
 * @param aggregatorId
 * @param model
 * @return the model and view
 */
@RequestMapping(value = "/doSettlement", headers = "Accept=*/*", produces = "application/json")
@ResponseBody
public JsonResponse doSettlement(@QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo,
        @QueryParam("aggregatorId") String aggregatorId, @QueryParam("providerId") String providerId,
        ModelMap model) {
    try {
        logger.debug("doSettlement - Provider: {} , aggregator: {}", providerId, aggregatorId);
        logger.debug("doSettlement - Start: Init" + dateFrom + ",End:" + dateTo);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat getDate = new SimpleDateFormat("MM/yyyy");
        String initDate = "";
        String endDate = "";
        if (dateFrom != null && !"".equalsIgnoreCase(dateFrom) && dateTo != null
                && !"".equalsIgnoreCase(dateTo)) {
            Date from = getDate.parse(dateFrom);
            Date to = getDate.parse(dateTo);
            initDate = format.format(from);
            endDate = format.format(to);
        } else {
            // By default use the current month
            GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
            cal.setTime(new Date());
            cal.set(Calendar.DAY_OF_MONTH, 1);
            initDate = format.format(cal.getTime());
            cal.add(Calendar.MONTH, 1);
            endDate = format.format(cal.getTime());
        }
        // Calculate settlement.
        settlementManager.runSettlement(initDate, endDate, aggregatorId, providerId);
        JsonResponse response = new JsonResponse();
        response.setMessage("Settlement proccess launched correctly.");
        response.setSuccess(true);
        return response;

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        JsonResponse response = new JsonResponse();
        response.setMessage(e.getMessage());
        response.setSuccess(false);
        return response;
    }
}