List of usage examples for org.joda.time DateTime minusSeconds
public DateTime minusSeconds(int seconds)
From source file:niche.newres.timedevents2owl.randomizer.TimedEvents2OWLRandomizer.java
public static DateTime minusRandomSeconds(DateTime dateTime, int minRange, int maxRange) { int randomSeconds = TimedEvents2OWLRandomizer.randInt(minRange, maxRange); return dateTime.minusSeconds(randomSeconds); }
From source file:org.adeptnet.auth.saml.SAMLClient.java
License:Apache License
private void validate(final Response response) throws ValidationException { if (response.getStatus() == null || response.getStatus().getStatusCode() == null || !(StatusCode.SUCCESS_URI.equals(response.getStatus().getStatusCode().getValue()))) { throw new ValidationException("Response has an unsuccessful status code"); }/* ww w . j av a 2 s. c o m*/ // response destination must match ACS if (!config.getSPConfig().getAcs().equals(response.getDestination())) { throw new ValidationException("Response is destined for a different endpoint"); } final DateTime now = DateTime.now(); // issue instant must be within a day final DateTime issueInstant = response.getIssueInstant(); if (issueInstant != null) { if (issueInstant.isBefore(now.minusDays(1).minusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the past"); } if (issueInstant.isAfter(now.plusDays(1).plusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the future"); } } for (Assertion assertion : response.getAssertions()) { // Assertion must be signed correctly if (!assertion.isSigned()) { throw new ValidationException("Assertion must be signed"); } final Signature sig2 = assertion.getSignature(); sigValidator.validate(sig2); // Assertion must contain an authnstatement // with an unexpired session if (assertion.getAuthnStatements().isEmpty()) { throw new ValidationException("Assertion should contain an AuthnStatement"); } for (AuthnStatement as : assertion.getAuthnStatements()) { if (as.getSessionNotOnOrAfter() == null) { LOG.error("SessionNotOnOrAfter is null"); continue; } final DateTime exp = as.getSessionNotOnOrAfter().plusSeconds(slack); if (exp != null && (now.isEqual(exp) || now.isAfter(exp))) { throw new ValidationException("AuthnStatement has expired"); } } if (assertion.getConditions() == null) { throw new ValidationException("Assertion should contain conditions"); } // Assertion IssueInstant must be within a day final DateTime instant = assertion.getIssueInstant(); if (instant != null) { if (instant.isBefore(now.minusDays(1).minusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the past"); } if (instant.isAfter(now.plusDays(1).plusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the future"); } } // Conditions must be met by current time final Conditions conditions = assertion.getConditions(); DateTime notBefore = conditions.getNotBefore(); DateTime notOnOrAfter = conditions.getNotOnOrAfter(); if (notBefore == null) { notBefore = now; } if (notBefore == null || notOnOrAfter == null) { throw new ValidationException("Assertion conditions must have limits"); } notBefore = notBefore.minusSeconds(slack); notOnOrAfter = notOnOrAfter.plusSeconds(slack); if (now.isBefore(notBefore)) { throw new ValidationException("Assertion conditions is in the future"); } if (now.isEqual(notOnOrAfter) || now.isAfter(notOnOrAfter)) { throw new ValidationException("Assertion conditions is in the past"); } // If subjectConfirmationData is included, it must // have a recipient that matches ACS, with a valid // NotOnOrAfter final Subject subject = assertion.getSubject(); if (subject != null && !subject.getSubjectConfirmations().isEmpty()) { boolean foundRecipient = false; for (SubjectConfirmation sc : subject.getSubjectConfirmations()) { if (sc.getSubjectConfirmationData() == null) { continue; } final SubjectConfirmationData scd = sc.getSubjectConfirmationData(); if (scd.getNotOnOrAfter() != null) { final DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack); if (now.isEqual(chkdate) || now.isAfter(chkdate)) { throw new ValidationException("SubjectConfirmationData is in the past"); } } if (config.getSPConfig().getAcs().equals(scd.getRecipient())) { foundRecipient = true; } } if (!foundRecipient) { throw new ValidationException("No SubjectConfirmationData found for ACS"); } } // audience must include intended SP issuer if (conditions.getAudienceRestrictions().isEmpty()) { throw new ValidationException("Assertion conditions must have audience restrictions"); } // only one audience restriction supported: we can only // check against the single SP. if (conditions.getAudienceRestrictions().size() > 1) { throw new ValidationException("Assertion contains multiple audience restrictions"); } final AudienceRestriction ar = conditions.getAudienceRestrictions().get(0); // at least one of the audiences must match our SP boolean foundSP = false; for (Audience a : ar.getAudiences()) { if (config.getSPConfig().getEntityId().equals(a.getAudienceURI())) { foundSP = true; } } if (!foundSP) { throw new ValidationException("Assertion audience does not include issuer"); } } }
From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java
License:Apache License
Object GetSmallerValue(Object v) { byte type = DataType.findType(v); if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP) return null; switch (type) { case DataType.CHARARRAY: String str = (String) v; if (str.length() > 0) return str.substring(0, str.length() - 1); else/*from w ww . jav a 2 s . c o m*/ return null; case DataType.BYTEARRAY: DataByteArray data = (DataByteArray) v; if (data.size() > 0) return new DataByteArray(data.get(), 0, data.size() - 1); else return null; case DataType.INTEGER: return Integer.valueOf((Integer) v - 1); case DataType.LONG: return Long.valueOf((Long) v - 1); case DataType.FLOAT: return Float.valueOf((Float) v - 1); case DataType.DOUBLE: return Double.valueOf((Double) v - 1); case DataType.BIGINTEGER: return ((BigInteger) v).subtract(BigInteger.ONE); case DataType.BIGDECIMAL: return ((BigDecimal) v).subtract(BigDecimal.ONE); case DataType.DATETIME: DateTime dt = (DateTime) v; if (dt.getMillisOfSecond() != 0) { return dt.minusMillis(1); } else if (dt.getSecondOfMinute() != 0) { return dt.minusSeconds(1); } else if (dt.getMinuteOfHour() != 0) { return dt.minusMinutes(1); } else if (dt.getHourOfDay() != 0) { return dt.minusHours(1); } else { return dt.minusDays(1); } default: return null; } }
From source file:org.apache.storm.st.tests.window.WindowVerifier.java
License:Apache License
/** * Run the topology and verify that the number and contents of time based windows is as expected * once the spout and bolt have emitted sufficient tuples. * The spout and bolt are required to log exactly one log line per emit/window using {@link StringDecorator} */// w ww .ja v a 2 s . c o m public void runAndVerifyTime(int windowSec, int slideSec, TestableTopology testable, TopoWrap topo) throws IOException, TException, java.net.MalformedURLException { topo.submitSuccessfully(); final int minSpoutEmits = 100; final int minBoltEmits = 5; String boltName = testable.getBoltName(); String spoutName = testable.getSpoutName(); //Waiting for spout tuples isn't strictly necessary since we also wait for bolt emits, but do it anyway //Allow two minutes for topology startup, then wait for at most the time it should take to produce 10 windows topo.assertProgress(minSpoutEmits, testable.getSpoutExecutors(), spoutName, 180 + 10 * slideSec); topo.assertProgress(minBoltEmits, testable.getBoltExecutors(), boltName, 180 + 10 * slideSec); final List<TimeData> allSpoutLogLines = topo.getDeserializedDecoratedLogLines(spoutName, TimeData::fromJson); final List<TimeDataWindow> allBoltLogLines = topo.getDeserializedDecoratedLogLines(boltName, TimeDataWindow::fromJson); Assert.assertTrue(allBoltLogLines.size() >= minBoltEmits, "Expecting min " + minBoltEmits + " bolt emits, found: " + allBoltLogLines.size() + " \n\t" + allBoltLogLines); final DateTime firstWindowEndTime = TimeUtil .ceil(new DateTime(allSpoutLogLines.get(0).getDate()).withZone(DateTimeZone.UTC), slideSec); final int numberOfWindows = allBoltLogLines.size(); /* * Windows should be aligned to the slide size, starting at firstWindowEndTime - windowSec. * Because all windows are aligned to the slide size, we can partition the spout emitted timestamps by which window they should fall in. * This checks that the partitioned spout emits fall in the expected windows, based on the logs from the spout and bolt. */ for (int i = 0; i < numberOfWindows; ++i) { final DateTime windowEnd = firstWindowEndTime.plusSeconds(i * slideSec); final DateTime windowStart = windowEnd.minusSeconds(windowSec); LOG.info("Comparing window: " + windowStart + " to " + windowEnd + " iter " + (i + 1) + "/" + numberOfWindows); final List<TimeData> expectedSpoutEmitsInWindow = allSpoutLogLines.stream().filter(spoutLog -> { DateTime spoutLogTime = new DateTime(spoutLog.getDate()); //The window boundaries are )windowStart, windowEnd) return spoutLogTime.isAfter(windowStart) && spoutLogTime.isBefore(windowEnd.plusMillis(1)); }).collect(Collectors.toList()); TimeDataWindow expectedWindow = new TimeDataWindow(expectedSpoutEmitsInWindow); final TimeDataWindow actualWindow = allBoltLogLines.get(i); LOG.info("Actual window: " + actualWindow.getDescription()); LOG.info("Expected window: " + expectedWindow.getDescription()); for (TimeData oneLog : expectedWindow.getTimeData()) { Assertions.assertTrue(actualWindow.getTimeData().contains(oneLog), () -> String.format("Missing: '%s' \n\tActual: '%s' \n\tComputed window: '%s'", oneLog, actualWindow, expectedWindow)); } for (TimeData oneLog : actualWindow.getTimeData()) { Assertions.assertTrue(expectedWindow.getTimeData().contains(oneLog), () -> String.format("Extra: '%s' \n\tActual: '%s' \n\tComputed window: '%s'", oneLog, actualWindow, expectedWindow)); } } }
From source file:org.apereo.portal.portlet.container.services.PortletCookieServiceImpl.java
License:Apache License
/** * (non-Javadoc)/*from w w w . j av a 2 s .co m*/ * * @see * org.apereo.portal.portlet.container.services.IPortletCookieService#updatePortalCookie(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void updatePortalCookie(HttpServletRequest request, HttpServletResponse response) { //Get the portal cookie object final IPortalCookie portalCookie = this.getOrCreatePortalCookie(request); //Create the browser cookie final Cookie cookie = this.convertToCookie(portalCookie, this.portalCookieAlwaysSecure || request.isSecure()); //Update the expiration date of the portal cookie stored in the DB if the update interval has passed final DateTime expires = portalCookie.getExpires(); if (DateTime.now().minusMillis(this.maxAgeUpdateInterval).isAfter(expires.minusSeconds(this.maxAge))) { try { this.portletCookieDao.updatePortalCookieExpiration(portalCookie, cookie.getMaxAge()); } catch (HibernateOptimisticLockingFailureException e) { // Especially with ngPortal UI multiple requests for individual portlet content may come at // the same time. Sometimes another thread updated the portal cookie between our dao fetch and // dao update. If this happens, simply ignore the update since another thread has already // made the update. logger.debug("Attempted to update expired portal cookie but another thread beat me to it." + " Ignoring update since the other thread handled it."); return; } // Update expiration dates of portlet cookies stored in session removeExpiredPortletCookies(request); } //Update the cookie in the users browser response.addCookie(cookie); }
From source file:org.efaps.esjp.accounting.report.AccountDataSource_Base.java
License:Apache License
/** * @see org.efaps.esjp.common.jasperreport.EFapsDataSource_Base#init(net.sf.jasperreports.engine.JasperReport) * @param _jasperReport JasperReport/*from w w w .j a v a 2 s. c om*/ * @param _parameter Parameter * @param _parentSource JRDataSource * @param _jrParameters map that contains the report parameters * @throws EFapsException on error */ @Override public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource, final Map<String, Object> _jrParameters) throws EFapsException { final List<Instance> instances = new ArrayList<>(); if (_parameter.getInstance() != null && _parameter.getInstance().isValid() && _parameter.getInstance().getType().isKindOf(CIAccounting.AccountAbstract.getType())) { instances.add(_parameter.getInstance()); final PrintQuery printRep = new PrintQuery(_parameter.getInstance()); printRep.addAttribute(CIAccounting.AccountAbstract.Name); printRep.execute(); final String name = printRep.<String>getAttribute(CIAccounting.ReportAbstract.Name).replaceAll(" ", "_"); _jrParameters.put("FileName", name); } else { final String[] oids = (String[]) Context.getThreadContext().getSessionAttribute("selectedOIDs"); final Set<Instance> instSet = new LinkedHashSet<>(); for (final String oid : oids) { final Instance instancetmp = Instance.get(oid); if (instancetmp.isValid()) { instSet.addAll(getAccountInstances(_parameter, instancetmp)); } } instances.addAll(instSet); } final List<Instance> posInstances = new ArrayList<>(); final DateTime dateFrom = new DateTime(_parameter.getParameterValue("dateFrom")); final DateTime dateTo = new DateTime(_parameter.getParameterValue("dateTo")); final Map<DateTime, BigDecimal> rates = new HashMap<>(); _jrParameters.put("Rates", rates); if ("true".equalsIgnoreCase(_parameter.getParameterValue("filterActive"))) { final Instance curr = Instance.get(CIERP.Currency.getType(), Long.valueOf(_parameter.getParameterValue("currency"))); if (curr.isValid()) { final CurrencyInst curInst = new CurrencyInst(curr); _jrParameters.put("TargetCurrencyId", curr.getId()); _jrParameters.put("TargetCurrencyLabel", curInst.getName()); rates.putAll(getRates4DateRange(_parameter, curInst.getInstance(), dateFrom, dateTo)); } } else { _jrParameters.put("TargetCurrencyId", null); } for (final Instance accInst : instances) { final QueryBuilder attrQueryBldr = new QueryBuilder(CIAccounting.TransactionAbstract); attrQueryBldr.addWhereAttrLessValue(CIAccounting.TransactionAbstract.Date, dateTo.plusDays(1)); attrQueryBldr.addWhereAttrGreaterValue(CIAccounting.TransactionAbstract.Date, dateFrom.minusSeconds(1)); final AttributeQuery attrQuery = attrQueryBldr.getAttributeQuery(CIAccounting.TransactionAbstract.ID); final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId()); queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery); final InstanceQuery query = queryBldr.getQuery(); posInstances.addAll(query.execute()); } if (posInstances.size() > 0) { final MultiPrintQuery multi = new MultiPrintQuery(posInstances); for (final JRField field : _jasperReport.getMainDataset().getFields()) { final String select = field.getPropertiesMap().getProperty("Select"); if (select != null) { multi.addSelect(select); } } multi.setEnforceSorted(true); multi.execute(); setPrint(multi); } final SystemConfiguration config = ERP.getSysConfig(); if (config != null) { final String companyName = ERP.COMPANY_NAME.get(); final String companyTaxNumb = ERP.COMPANY_TAX.get(); if (companyName != null && companyTaxNumb != null && !companyName.isEmpty() && !companyTaxNumb.isEmpty()) { _jrParameters.put("CompanyName", companyName); _jrParameters.put("CompanyTaxNum", companyTaxNumb); } } }
From source file:org.efaps.esjp.accounting.report.DocTransactionsSource_Base.java
License:Apache License
/** * @see org.efaps.esjp.common.jasperreport.EFapsDataSource_Base#init(net.sf.jasperreports.engine.JasperReport) * @param _jasperReport JasperReport/*from w w w . ja v a 2 s .c o m*/ * @param _parameter Parameter * @param _parentSource JRDataSource * @param _jrParameters map that contains the report parameters * @throws EFapsException on error */ @SuppressWarnings("unchecked") @Override public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource, final Map<String, Object> _jrParameters) throws EFapsException { final Instance instance = _parameter.getInstance(); final DateTime dateFrom = new DateTime( _parameter.getParameterValue(CIFormAccounting.Accounting_DocTransactionsForm.dateFrom.name)); final DateTime dateTo = new DateTime( _parameter.getParameterValue(CIFormAccounting.Accounting_DocTransactionsForm.dateTo.name)); _jrParameters.put("FromDate", dateFrom.toDate()); _jrParameters.put("ToDate", dateTo.toDate()); _jrParameters.put("Mime", _parameter.getParameterValue("mime")); final boolean filter = "true".equalsIgnoreCase( _parameter.getParameterValue(CIFormAccounting.Accounting_DocTransactionsForm.filterActive.name)); final Instance contactInst = Instance .get(_parameter.getParameterValue(CIFormAccounting.Accounting_DocTransactionsForm.contact.name)); final String[] creditAccount = _parameter .getParameterValues(CIFormAccounting.Accounting_DocTransactionsForm.creditAccount.name); final String[] debitAccount = _parameter .getParameterValues(CIFormAccounting.Accounting_DocTransactionsForm.debitAccount.name); // filter the documents by the given dates final QueryBuilder docAttrQueryBldr = new QueryBuilder(CIERP.DocumentAbstract); docAttrQueryBldr.addWhereAttrLessValue(CIERP.DocumentAbstract.Date, dateTo.plusDays(1)); docAttrQueryBldr.addWhereAttrGreaterValue(CIERP.DocumentAbstract.Date, dateFrom.minusSeconds(1)); if (filter && contactInst.isValid() && contactInst.getType().isKindOf(CIContacts.Contact.getType())) { docAttrQueryBldr.addWhereAttrEqValue(CIERP.DocumentAbstract.Contact, contactInst.getId()); } final AttributeQuery docAttrQuery = docAttrQueryBldr.getAttributeQuery(CIERP.DocumentAbstract.ID); final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction2SalesDocument); attrQuerBldr.addWhereAttrInQuery(CIAccounting.Transaction2SalesDocument.ToLink, docAttrQuery); final AttributeQuery attrQuery = attrQuerBldr .getAttributeQuery(CIAccounting.Transaction2SalesDocument.FromLink); final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.Transaction); queryBuilder.addWhereAttrInQuery(CIAccounting.Transaction.ID, attrQuery); queryBuilder.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink, instance.getId()); final MultiPrintQuery multi = queryBuilder.getPrint(); final SelectBuilder selDoc = new SelectBuilder() .linkfrom(CIAccounting.Transaction2SalesDocument, CIAccounting.Transaction2SalesDocument.FromLink) .linkto(CIAccounting.Transaction2SalesDocument.ToLink); final SelectBuilder selDocName = new SelectBuilder(selDoc).attribute(CIERP.DocumentAbstract.Name); final SelectBuilder selDocDate = new SelectBuilder(selDoc).attribute(CIERP.DocumentAbstract.Date); final SelectBuilder selDocType = new SelectBuilder(selDoc).type().label(); final SelectBuilder selDocContactName = new SelectBuilder(selDoc).linkto(CIERP.DocumentAbstract.Contact) .attribute(CIContacts.Contact.Name); final SelectBuilder selDocContactTaxNumber = new SelectBuilder(selDoc) .linkto(CIERP.DocumentAbstract.Contact).clazz(CIContacts.ClassOrganisation) .attribute(CIContacts.ClassOrganisation.TaxNumber); multi.addSelect(selDocName, selDocContactName, selDocContactTaxNumber, selDocType, selDocDate); multi.addAttribute(CIAccounting.Transaction.Date, CIAccounting.Transaction.Description, CIAccounting.Transaction.Name); multi.execute(); while (multi.next()) { final String docType = multi.<String>getSelect(selDocType); final String docName = multi.<String>getSelect(selDocName); final DateTime docDate = multi.<DateTime>getSelect(selDocDate); final String contactName = multi.<String>getSelect(selDocContactName); final String taxNumber = multi.<String>getSelect(selDocContactTaxNumber); final DateTime transDate = multi.<DateTime>getAttribute(CIAccounting.Transaction.Date); final String transDescr = multi.<String>getAttribute(CIAccounting.Transaction.Description); final String transOID = multi.getCurrentInstance().getOid(); final String transName = multi.<String>getAttribute(CIAccounting.Transaction.Name); final QueryBuilder posQueryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); posQueryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.TransactionLink, multi.getCurrentInstance().getId()); final MultiPrintQuery posMulti = posQueryBldr.getPrint(); final SelectBuilder selAcc = new SelectBuilder() .linkto(CIAccounting.TransactionPositionAbstract.AccountLink); final SelectBuilder selAccName = new SelectBuilder(selAcc).attribute(CIAccounting.AccountAbstract.Name); final SelectBuilder selAccDesc = new SelectBuilder(selAcc) .attribute(CIAccounting.AccountAbstract.Description); posMulti.addSelect(selAccName, selAccDesc); posMulti.addAttribute(CIAccounting.TransactionPositionAbstract.Amount); posMulti.execute(); while (posMulti.next()) { final String accName = posMulti.<String>getSelect(selAccName); if (!filter || (filter && add(accName, posMulti.getCurrentInstance().getType() .isKindOf(CIAccounting.TransactionPositionCredit.getType()) ? creditAccount : debitAccount))) { final Map<String, Object> row = new HashMap<>(); row.put("docName", docName); row.put("docType", docType); row.put("docDate", docDate); row.put("contactName", contactName); row.put("taxNumber", taxNumber); row.put("transOID", transOID); row.put("transDate", transDate); row.put("transName", transName); row.put("transDescr", transDescr); row.put("amount", posMulti.getAttribute(CIAccounting.TransactionPositionAbstract.Amount)); row.put("accName", accName); row.put("accDescr", posMulti.getSelect(selAccDesc)); getValues().add(row); } } } final ComparatorChain chain = new ComparatorChain(); chain.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _arg0, final Map<String, Object> _arg1) { return String.valueOf(_arg0.get("taxNumber")).compareTo(String.valueOf(_arg1.get("taxNumber"))); } }); chain.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _arg0, final Map<String, Object> _arg1) { return String.valueOf(_arg0.get("docName")).compareTo(String.valueOf(_arg1.get("docName"))); } }); chain.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _arg0, final Map<String, Object> _arg1) { return ((DateTime) _arg0.get("transDate")).compareTo((DateTime) _arg1.get("transDate")); } }); chain.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _arg0, final Map<String, Object> _arg1) { return String.valueOf(_arg0.get("transOID")).compareTo(String.valueOf(_arg1.get("transOID"))); } }); chain.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _arg0, final Map<String, Object> _arg1) { return String.valueOf(_arg0.get("accName")).compareTo(String.valueOf(_arg1.get("accName"))); } }); Collections.sort(getValues(), chain); final SystemConfiguration config = ERP.getSysConfig(); if (config != null) { final String companyName = ERP.COMPANY_NAME.get(); final String companyTaxNumb = ERP.COMPANY_TAX.get(); if (companyName != null && companyTaxNumb != null && !companyName.isEmpty() && !companyTaxNumb.isEmpty()) { _jrParameters.put("CompanyName", companyName); _jrParameters.put("CompanyTaxNum", companyTaxNumb); } } }
From source file:org.efaps.esjp.accounting.report.JournalDataSource_Base.java
License:Apache License
@Override protected void analyze() throws EFapsException { if (isSubDataSource()) { super.analyze(); } else {/*w ww.ja v a 2s. co m*/ final DateTime dateFrom = new DateTime(getParameter().getParameterValue("dateFrom")); final DateTime dateTo = new DateTime(getParameter().getParameterValue("dateTo")); final Map<?, ?> props = (Map<?, ?>) getParameter().get(ParameterValues.PROPERTIES); final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.TransactionAbstract); if (getParameter().getInstance().isValid() && getParameter().getInstance().getType().isKindOf(CIAccounting.ReportSubJournal.getType())) { final QueryBuilder attrQueryBldr = new QueryBuilder(CIAccounting.Report2Transaction); attrQueryBldr.addWhereAttrEqValue(CIAccounting.Report2Transaction.FromLinkAbstract, getParameter().getInstance().getId()); final AttributeQuery attrQuery = attrQueryBldr .getAttributeQuery(CIAccounting.Report2Transaction.ToLinkAbstract); queryBuilder.addWhereAttrInQuery(CIAccounting.TransactionAbstract.ID, attrQuery); final QueryBuilder attrQueryBldr2 = new QueryBuilder(CIAccounting.ReportSubJournal); attrQueryBldr2.addWhereAttrEqValue(CIAccounting.ReportSubJournal.ID, getInstance()); final AttributeQuery attrQuery2 = attrQueryBldr2 .getAttributeQuery(CIAccounting.ReportSubJournal.PeriodLink); queryBuilder.addWhereAttrInQuery(CIAccounting.TransactionAbstract.PeriodLink, attrQuery2); } else { queryBuilder.addWhereAttrEqValue(CIAccounting.TransactionAbstract.PeriodLink, getInstance()); } queryBuilder.addWhereAttrLessValue(CIAccounting.TransactionAbstract.Date, dateTo.plusDays(1)); queryBuilder.addWhereAttrGreaterValue(CIAccounting.TransactionAbstract.Date, dateFrom.minusSeconds(1)); queryBuilder.addOrderByAttributeAsc(CIAccounting.TransactionAbstract.Date); queryBuilder.addOrderByAttributeAsc(CIAccounting.TransactionAbstract.Name); queryBuilder.addOrderByAttributeAsc(CIAccounting.TransactionAbstract.Description); if (props.containsKey("Classifications")) { final String classStr = (String) props.get("Classifications"); final String[] clazzes = classStr.split(";"); for (final String clazz : clazzes) { final Classification classif = (Classification) Type.get(clazz); if (classif != null) { queryBuilder.addWhereClassification(classif); } } } setPrint(queryBuilder.getPrint()); getPrint().setEnforceSorted(true); if (getJasperReport().getMainDataset().getFields() != null) { for (final JRField field : getJasperReport().getMainDataset().getFields()) { final String select = field.getPropertiesMap().getProperty("Select"); if (select != null) { getPrint().addSelect(select); getSelects().add(select); } } } getPrint().execute(); } }
From source file:org.efaps.esjp.accounting.report.ReportAccountDataSource_Base.java
License:Apache License
/** * Recursive method to get the Debit and Credit Amount of all Transactions * of the given account and the accounts children. * * @param _accInst Instance of the Account * @param _dateFrom dateFrom// ww w . j av a 2 s . c o m * @param _dateTo date To * @return Array of BigDecimal { Debit Amount, Credit Amount} * @throws EFapsException on error */ protected BigDecimal[] getDebitCredit(final Parameter _parameter, final Instance _accInst, final DateTime _dateFrom, final DateTime _dateTo) throws EFapsException { final boolean active = Boolean.parseBoolean(_parameter.getParameterValue("filterActive")); final String currency = _parameter.getParameterValue("currency"); final Instance curBase = Currency.getBaseCurrency(); BigDecimal debit = BigDecimal.ZERO; BigDecimal credit = BigDecimal.ZERO; // get the transactions fot the given account instance final QueryBuilder attrQueryBldr = new QueryBuilder(CIAccounting.TransactionAbstract); attrQueryBldr.addWhereAttrLessValue(CIAccounting.TransactionAbstract.Date, _dateTo.plusDays(1)); attrQueryBldr.addWhereAttrGreaterValue(CIAccounting.TransactionAbstract.Date, _dateFrom.minusSeconds(1)); final AttributeQuery attrQuery = attrQueryBldr.getAttributeQuery(CIAccounting.TransactionAbstract.ID); final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, _accInst.getId()); queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount, CIAccounting.TransactionPositionAbstract.RateAmount); final SelectBuilder selRateCur = new SelectBuilder() .linkto(CIAccounting.TransactionPositionAbstract.RateCurrencyLink).instance(); final SelectBuilder selTxnDate = new SelectBuilder() .linkto(CIAccounting.TransactionPositionAbstract.TransactionLink) .attribute(CIAccounting.TransactionAbstract.Date); multi.addSelect(selRateCur, selTxnDate); multi.execute(); while (multi.next()) { final CurrencyInst curInstTxnPos = new CurrencyInst(multi.<Instance>getSelect(selRateCur)); final DateTime date = multi.<DateTime>getSelect(selTxnDate); BigDecimal amount = BigDecimal.ZERO; if (active) { final Long rateCurType = Long.parseLong(_parameter.getParameterValue("rateCurrencyType")); final CurrencyInst curInst = new CurrencyInst(Instance.get(CIERP.Currency.getType(), currency)); if (curInstTxnPos.getInstance().getId() != curInst.getInstance().getId()) { if (curInstTxnPos.getInstance().getId() != curBase.getId()) { RateInfo rateInfo = getCurrency(_parameter).evaluateRateInfo(_parameter, date, curInstTxnPos.getInstance()); BigDecimal rate = RateInfo.getRate(_parameter, rateInfo, ReportAccountDataSource.class.getName()); final BigDecimal amountTmp = multi .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount) .divide(rate, BigDecimal.ROUND_HALF_UP); rateInfo = getCurrency(_parameter).evaluateRateInfo(_parameter, date, curInst.getInstance()); rate = RateInfo.getRate(_parameter, rateInfo, Report.class.getName()); amount = amountTmp.divide(rate, BigDecimal.ROUND_HALF_UP); } else { final RateInfo rateInfo = getCurrency(_parameter).evaluateRateInfo(_parameter, date, curInst.getInstance()); final BigDecimal rate = RateInfo.getRate(_parameter, rateInfo, Report.class.getName()); amount = multi.<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount) .divide(rate, BigDecimal.ROUND_HALF_UP); } } else { amount = multi.<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount); } } else { amount = multi.<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount); } if (multi.getCurrentInstance().getType().equals(CIAccounting.TransactionPositionCredit.getType())) { credit = credit.add(amount); } else { debit = debit.add(amount); } } // get the child accounts, andd the amounts by calling recursive final QueryBuilder accQueryBldr = new QueryBuilder(CIAccounting.AccountAbstract); accQueryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.ParentLink, _accInst.getId()); final InstanceQuery accQuery = accQueryBldr.getQuery(); accQuery.execute(); while (accQuery.next()) { final BigDecimal[] amounts = getDebitCredit(_parameter, accQuery.getCurrentValue(), _dateFrom, _dateTo); debit = debit.add(amounts[0]); credit = credit.add(amounts[1]); } return new BigDecimal[] { debit, credit }; }
From source file:org.efaps.esjp.accounting.report.ReportJournalDataSource_Base.java
License:Apache License
@Override protected void analyze() throws EFapsException { if (isSubDataSource()) { super.analyze(); } else {/*from ww w . j a va 2 s . c o m*/ final Instance instance = getParameter().getInstance(); final DateTime dateFrom = new DateTime(getParameter().getParameterValue("dateFrom")); final DateTime dateTo = new DateTime(getParameter().getParameterValue("dateTo")); this.jrParameters.put("FromDate", dateFrom.toDate()); this.jrParameters.put("ToDate", dateTo.toDate()); this.jrParameters.put("Mime", getParameter().getParameterValue("mime")); final PrintQuery printRep = new PrintQuery(instance); printRep.addAttribute(CIAccounting.ReportAbstract.Name); printRep.execute(); final String name = printRep.<String>getAttribute(CIAccounting.ReportAbstract.Name).replaceAll(" ", "_"); this.jrParameters.put("FileName", name); // get the root node, only the first one will be used final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.ReportNodeRoot); queryBldr.addWhereAttrEqValue(CIAccounting.ReportNodeRoot.ReportLink, instance.getId()); final InstanceQuery query = queryBldr.getQuery(); query.execute(); if (query.next()) { // only the ReportAccounts will be evaluated final QueryBuilder accQueryBldr = new QueryBuilder(CIAccounting.ReportNodeAccount); accQueryBldr.addWhereAttrEqValue(CIAccounting.ReportNodeAccount.ParentLink, query.getCurrentValue().getId()); final AttributeQuery attrQuery = accQueryBldr .getAttributeQuery(CIAccounting.ReportNodeAccount.AccountLink); final QueryBuilder tpQueryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); tpQueryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.AccountLink, attrQuery); final AttributeQuery tpAttrQuery = tpQueryBldr .getAttributeQuery(CIAccounting.TransactionPositionAbstract.TransactionLink); final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.TransactionAbstract); queryBuilder.addWhereAttrLessValue(CIAccounting.TransactionAbstract.Date, dateTo.plusDays(1)); queryBuilder.addWhereAttrGreaterValue(CIAccounting.TransactionAbstract.Date, dateFrom.minusSeconds(1)); queryBuilder.addOrderByAttributeAsc(CIAccounting.TransactionAbstract.Date); queryBuilder.addWhereAttrInQuery(CIAccounting.TransactionAbstract.ID, tpAttrQuery); setPrint(queryBuilder.getPrint()); getPrint().setEnforceSorted(true); if (getJasperReport().getMainDataset().getFields() != null) { for (final JRField field : getJasperReport().getMainDataset().getFields()) { final String select = field.getPropertiesMap().getProperty("Select"); if (select != null) { getPrint().addSelect(select); getSelects().add(select); } } } getPrint().execute(); } } }