List of usage examples for org.joda.time Days getDays
public int getDays()
From source file:org.libreplan.web.montecarlo.MonteCarloTask.java
License:Open Source License
public static BigDecimal calculateRealDurationFor(MonteCarloTask task, BigDecimal daysDuration) { LocalDate start = task.getStartDate(); Validate.notNull(start);//from w ww .j a v a 2 s . c om LocalDate end = calculateEndDateFor(task, daysDuration); Days daysBetween = Days.daysBetween(start, end); return BigDecimal.valueOf(daysBetween.getDays()); }
From source file:org.mifos.domain.builders.ScheduledEventBuilder.java
License:Open Source License
public ScheduledEventBuilder on(final Days withDayOfWeek) { this.dayOfWeek = withDayOfWeek.getDays(); return this; }
From source file:org.milleni.dunning.process.test.DunningTestProcesses.java
License:Apache License
private static void dateDiff() { System.out.println("Calculate difference between two dates"); System.out.println("================================================================="); DateTime startDate = new DateTime(new Date()); DateTime endDate = new DateTime(); Days d = Days.daysBetween(startDate, endDate); int days = d.getDays(); System.out.println(" Difference between " + endDate); System.out.println(" and " + startDate + " is " + days + " days."); }
From source file:org.multibit.viewsystem.swing.WalletAssetSummaryTableModel.java
License:MIT License
@Override public Object getValueAt(int row, int column) { WalletAssetTableData rowObj = null;//from w w w . j a v a 2s . com if (row >= 0 && row < walletAssetData.size()) { rowObj = walletAssetData.get(row); } if (rowObj == null) { return null; } CSBitcoinAssetTableData btcObj = null; boolean isBitcoin = (rowObj instanceof CSBitcoinAssetTableData); if (isBitcoin) { btcObj = (CSBitcoinAssetTableData) rowObj; } CSAsset asset = rowObj.getAsset(); CSAsset.CSAssetState assetState = CSAsset.CSAssetState.INVALID; if (asset != null) { assetState = asset.getAssetState(); } //boolean noDetailsFlag = assetState. // NOTE: If asset is null, this should be the Bitcoin object. /* Get the balance and spendable balance of the asset. */ boolean showAssetSpendableFlag = false; boolean showAssetUpdatingNowFlag = false; Wallet wallet = bitcoinController.getModel().getActiveWallet(); Wallet.CoinSpark.AssetBalance assetBalance = null; if (asset != null) { int id = asset.getAssetID(); assetBalance = wallet.CS.getAssetBalance(id); showAssetSpendableFlag = (assetBalance.total.compareTo(assetBalance.spendable) != 0); showAssetUpdatingNowFlag = assetBalance.updatingNow; } int threshold = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; String sendAssetWithJustOneConfirmation = controller.getModel() .getUserPreference("sendAssetWithJustOneConfirmation"); if (Boolean.TRUE.toString().equals(sendAssetWithJustOneConfirmation)) { threshold = 1; } int lastHeight = 0; if (wallet != null) lastHeight = wallet.getLastBlockSeenHeight(); int numConfirms = 0; CoinSparkAssetRef assetRef = null; if (asset != null) assetRef = asset.getAssetReference(); if (assetRef != null) { int blockIndex = (int) assetRef.getBlockNum(); numConfirms = lastHeight - blockIndex + 1; // 0 means no confirmation, 1 is yes for sa } int numConfirmsStillRequired = threshold - numConfirms; // Switch on string, makes it easier for us to re-order columns without // having to reorganize the case statements. // http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java switch (COLUMN_HEADER_KEYS[column]) { case COLUMN_DESCRIPTION: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } // is the symbol industry group wants to use in 2014. // If there is no tooltip, no description, than dont show icon. String s = asset.getDescription(); if (s != null && !"".equals(s)) { String units = asset.getUnits(); // mandatory field but we are getting null sometimes if (units != null) { s = s + "<br><br>1 unit = " + units; } ImageIcon icon = ImageLoader.fatCow16(ImageLoader.FATCOW.information); map.put("icon", icon); map.put("tooltip", s); } ; return map; } case COLUMN_ISSUER: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } String issuerName = asset.getIssuer(); if (issuerName != null) { ImageIcon icon = ImageLoader.fatCow16(ImageLoader.FATCOW.ceo); map.put("icon", icon); String tip = "Asset issued by " + asset.getIssuer(); map.put("tooltip", tip); } return map; } case COLUMN_SPENDABLE: { HashMap<String, Object> map = new HashMap<>(); String s = ""; if (isBitcoin) { s = btcObj.syncText; if (s == null) { s = btcObj.spendableText; } else { if (btcObj.syncPercentText != null) { s = s + " " + btcObj.syncPercentText; } } //if (btcObj.syncPercentToolTipText) if (s == null) { s = ""; } } else if (asset != null && showAssetSpendableFlag) { s = "(" + CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.spendable) + " spendable)"; } // Replace asset spendable flag if new asset needs more confirmaions // and this asset is almost ready to be sent i.e. has name, quantity. // Does not make sense to show this if asset files need to be uploaded. if (!isBitcoin && numConfirmsStillRequired > 0 && asset != null && asset.getName() != null) { int n = numConfirmsStillRequired; // we dont want to show high number if wallet is resyncing from start. if (n > NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD) { n = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; } s = "(Waiting for " + n + " confirmation" + ((n > 1) ? "s)" : ")"); } map.put("label", s); return map; } case COLUMN_EXPIRY: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } String tip = null; Date issueDate = asset.getIssueDate(); if (issueDate != null) { LocalDateTime issueDateTime = new DateTime(issueDate).toLocalDateTime(); tip = "Issued on " + issueDateTime.toString("d MMM y, HH:mm:ss") + "."; } else { tip = "No issue date given."; } Date d = asset.getExpiryDate(); ImageIcon icon = null; String s = null; if (d != null) { LocalDateTime expiryDateTime = new DateTime(d).toLocalDateTime(); tip = tip + " Expires on " + expiryDateTime.toString("d MMM y, HH:mm:ss") + "."; LocalDateTime now = LocalDateTime.now(); //For testing, plusDays and minusDays. //expiryDateTime = now.minusDays(600); Days daysDifference = Days.daysBetween(expiryDateTime, now); //, expiryDateTime); int daysBetween = daysDifference.getDays(); int weeksBetween = daysDifference.toStandardWeeks().getWeeks(); daysBetween = Math.abs(daysBetween); weeksBetween = Math.abs(weeksBetween); String diff = null; if (daysBetween <= 13) { diff = daysBetween + " days"; } else if (weeksBetween <= 12) { diff = weeksBetween + " weeks"; } else { diff = Math.abs(weeksBetween / 4) + " months"; } if (now.compareTo(expiryDateTime) > 0) { s = "Expired " + diff + " ago"; icon = ImageLoader.fatCow16(ImageLoader.FATCOW.skull_old); if (daysBetween <= 7) { s = s + " (" + expiryDateTime.toString("d MMM y h:mm a z") + ")"; } else { s = s + " (" + expiryDateTime.toString("d MMM y") + ")"; } } else { s = "Expires on " + expiryDateTime.toString("d MMM y"); //expiryDateTime.toString("d MMM y, HH:mm:ss") + "."; if (daysBetween <= 30) { // s = "Expires in " + diff; icon = ImageLoader.fatCow16(ImageLoader.FATCOW.fire); // s = s + " (" + expiryDateTime.toString("d MMM, h:mm a z") + ")"; } else { // s = "Expires in " + diff; icon = ImageLoader.fatCow16(ImageLoader.FATCOW.clock); // s = s + " (" + expiryDateTime.toString("d MMM y") + ")"; } } } else { // No expiry date info. icon = null; s = null; tip = null; // If also no issue date info, that means we have not loaded the asset page yet if (issueDate != null) { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.thumb_up); s = "Does not expire"; } } // Expired!!! skull icon? thumbs down. map.put("icon", icon); map.put("text", s); map.put("tooltip", tip); return map; } case COLUMN_REFRESH: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } ImageIcon icon = null; String tip = null; if (assetState == CSAsset.CSAssetState.REFRESH) { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.hourglass); tip = "Refreshing..."; } else { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.arrow_refresh_small); tip = "Click to manually refresh the status of the asset"; } map.put("tooltip", tip); map.put("icon", icon); return map; } case COLUMN_QUANTITY: { if (isBitcoin) { String s = btcObj.balanceText; if (s == null) { s = ""; } return s; } if (asset.getName() == null) { return ""; // TODO: Change to webPageJSON==null } String displayString = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.total); if (showAssetUpdatingNowFlag) { if (assetBalance.total.equals(BigInteger.ZERO) == true) { displayString = "..."; } else { displayString += " + ..."; } } // For debugging, round-trip to see if values match. // BigInteger y = CSMiscUtils.getRawUnitsFromDisplayString(asset, displayString); // System.out.println("DISPLAY: " + displayString + " ----> RAW: " + y); return displayString; } case COLUMN_NAME: { HashMap map = new HashMap<>(); if (isBitcoin) { String s = btcObj.dataChangedText; if (s != null) { // Show important warning that wallet was changed by another process map.put("text", s); StyleRange style = new StyleRange(0, -1, Font.BOLD, Color.RED); map.put("style", style); map.put("tooltip", btcObj.dataChangedToolTipText); } else { map.put("text", "Bitcoin"); //map.put("text2", "(bitcoin.org)"); Font defaultFont = FontSizer.INSTANCE.getAdjustedDefaultFont(); map.put("style", new StyleRange(0, -1, defaultFont.getStyle())); } map.put("noaction", true); // disable action return map; } String name = asset.getNameShort(); // Short name is upto 16 chars, better for small table column. String domain = CSMiscUtils.getDomainHost(asset.getDomainURL()); boolean uploadFiles = false; if (name != null) { map.put("text", name); map.put("text2", "(" + domain + ")"); } else { String s; if (asset.getAssetSource() == CSAsset.CSAssetSource.GENESIS) { s = "Upload files to " + asset.getAssetWebPageURL(); uploadFiles = true; } else { if (domain == null) { s = "Locating new asset.."; } else { s = "Loading new asset from " + domain + "..."; } } map.put("text", s); StyleRange style = new StyleRange(0, -1, Font.PLAIN, Color.RED); map.put("style", style); map.put("noaction", true); // disable action } map.put("tooltip", "Click to visit the asset web page or the home page of the asset issuer."); if (uploadFiles) map.put("tooltip", map.get("text")); // for upload, it's long so show url. return map; } case COLUMN_CONFIRMATION: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } ImageIcon icon = null; String tip = null; //CoinSparkAssetRef assetRef = asset.getAssetReference(); PeerGroup pg = this.bitcoinController.getMultiBitService().getPeerGroup(); //Wallet wallet = this.bitcoinController.getModel().getActiveWallet(); //int lastHeight = wallet.getLastBlockSeenHeight(); // FIXME: when resyncing, last seen height will be less than genesis block. // Do we have another source of latest block height of testnet3 or production? // txid could be null if user manually adds a bogus asset reference. String txid = asset.getGenTxID(); Transaction tx = null; if (txid != null) { tx = wallet.getTransaction(new Sha256Hash(txid)); } // System.out.println("New? --- asset ref = " + asset.getAssetReference()); // System.out.println(" --- name = " + asset.getName()); // System.out.println(" --- transaction = " + tx); // System.out.println(" --- CSAsset has txid = " + txid); // System.out.println(" --- CSAsset has genesis = " + asset.getGenesis()); // tx can be null. // trying to find block, not found, // A regular CoinSpark transaction, where the wallet does not have the blockheader // for genesis transaction, must get the block, and get the transaction at the // index mentioned in asset ref. if (assetRef != null && tx == null) { final int blockIndex = (int) assetRef.getBlockNum(); final PeerGroup peerGroup = pg; final WalletAssetSummaryTableModel thisModel = this; Block block = blockCache.get(blockIndex); if (block == null) { //System.out.println("FAILED, NEED TO GET BLOCK"); executorService.execute(new Runnable() { @Override public void run() { Block block = peerGroup.getBlock(blockIndex); if (block != null) { blockCache.put(blockIndex, block); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // System.out.println("GOT THE BLOCK SO NOW INFORMING TABLE MODEL OF CHANGE"); thisModel.fireTableDataChanged(); } }); } if (block == null) { /* In a situation where the .spvchain and .fbhchain were deleted, and they need to be recreated, we can get, the following error: ERROR o.coinspark.core.CSBlockHeaderStore - Cannot read block hash, header file too small: block 266131, file size 3840032 */ } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } //System.out.println("getBlock() for asset ref height " + n + " , returned: " + block); if (block != null) { tx = block.getTransactionByOffset((int) assetRef.getTxOffset()); if (tx == null) { // FIXME: We have an asset ref, but cannot get a valid transaction using the asset-ref and checking the genesis block header datda, so this is most likely an invalid asset. // System.out.println("Asset: Cannot find transaction with offset " + (int) assetRef.getTxnOffset() + " in block " + block.getHashAsString()); } } } int txHeight = 0; int numConfirmations = 0; int numBroadcasts = 0; String newAssetString = null; if (tx != null && assetRef != null) { TransactionConfidence confidence = tx.getConfidence(); numBroadcasts = confidence.getBroadcastByCount(); // System.out.println("confidence.getDepthInBlocks() = " + confidence.getDepthInBlocks()); if (confidence.getConfidenceType() == ConfidenceType.BUILDING) { txHeight = confidence.getAppearedAtChainHeight(); } else { // Note: assetRef could be NULL causing exception. txHeight = (int) assetRef.getBlockNum(); } numConfirmations = lastHeight - txHeight + 1; // 0 means no confirmation, 1 is yes for same block. String issueString = null; Date issueDate = asset.getIssueDate(); String sinceString = null; if (issueDate != null) { LocalDateTime issueDateTime = new DateTime(issueDate).toLocalDateTime(); issueString = "Date of issue was " + issueDateTime.toString("d MMM y, HH:mm:ss z"); // Compute the 'minutes/hours/days/weeks ago' string. LocalDateTime now = LocalDateTime.now(); Minutes theDiff = Minutes.minutesBetween(issueDateTime, now); //Days daysDifference = Days.daysBetween(issueDateTime, now); int minutesBetween = theDiff.getMinutes(); int hoursBetween = theDiff.toStandardHours().getHours(); int daysBetween = theDiff.toStandardDays().getDays(); int weeksBetween = theDiff.toStandardWeeks().getWeeks(); minutesBetween = Math.abs(minutesBetween); hoursBetween = Math.abs(hoursBetween); daysBetween = Math.abs(daysBetween); weeksBetween = Math.abs(weeksBetween); if (minutesBetween <= 120) { sinceString = minutesBetween + " minutes"; } else if (hoursBetween <= 48) { sinceString = hoursBetween + " hours"; } else if (daysBetween <= 14) { sinceString = daysBetween + " days"; } else { sinceString = weeksBetween + " weeks"; } } else { // TODO: Find a new issue date, or date of first insert into blockchain? // Transaction.getUpdateTime() first seen // tx.getUpdateTime() issueString = "No issue date given"; } // issue date is null when tx is null, getUpdateTime returning junk. tip = String.format("Issued %s ago, at block height %d, number of confirmations %d (%s)", sinceString, txHeight, numConfirmations, issueString); newAssetString = String.format( "Asset issued only %s ago, caution recommended.<br>Issued at block height %d, number of confirmations %d (%s)", sinceString, txHeight, numConfirmations, issueString); } if (assetRef == null) { // Fix for... GDG Issue 8: If an asset does not yet have an asset ref, the reason can only be that it's a genesis that has not yet been confirmed. icon = ImageLoader.fatCow16(ImageLoader.FATCOW.warning); tip = "Awaiting new asset confirmation..."; } else if (asset.getName() != null && numConfirmations < 0) { // <= icon = ImageLoader.fatCow16(ImageLoader.FATCOW.warning); // If the computer is not online, that should be the message StatusEnum state = this.multiBitFrame.getOnlineStatus(); if (state != StatusEnum.ONLINE) { tip = "Waiting to connect to network"; } else { int n = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; if (numConfirmsStillRequired < n) n = numConfirmsStillRequired; tip = "Waiting for wallet to sync blocks, need " + n + " more confirmations"; // tip is usually null now. : " + tip; } } else if (tx == null) { // Example: manually add an asset-ref which is bogus. tip = "Searching for the asset's genesis transaction"; icon = ImageLoader.fatCow16(ImageLoader.FATCOW.find); // if (asset.getAssetSource() == CSAsset.CSAssetSource.GENESIS) { // } } else if (assetState == CSAsset.CSAssetState.ASSET_SPECS_NOT_FOUND || assetState == CSAsset.CSAssetState.ASSET_SPECS_NOT_PARSED || assetState == CSAsset.CSAssetState.ASSET_WEB_PAGE_NOT_FOUND || assetState == CSAsset.CSAssetState.REQUIRED_FIELD_MISSING) { tip = "Waiting for asset files to be uploaded."; if (asset.getAssetState() == CSAsset.CSAssetState.REQUIRED_FIELD_MISSING) { tip = "Asset files are missing required data."; } icon = ImageLoader.fatCow16(ImageLoader.FATCOW.server_error); } else if (assetState == CSAsset.CSAssetState.HASH_MISMATCH) { tip = "Caution: asset details do not match what was encoded by issuer.<br><br>" + tip; icon = ImageLoader.fatCow16(ImageLoader.FATCOW.warning); } else if (assetState == CSAsset.CSAssetState.REFRESH) { tip = null; icon = null; // tip = "Refreshing..."; // icon = ImageLoader.fatCow16(ImageLoader.FATCOW.hourglass); } else if (tx != null && asset.getName() != null && numConfirmations >= 1 && numConfirmations < 1008) { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.new_new); tip = newAssetString; } else if (tx != null && numConfirmations >= 1008) { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.tick_shield); } map.put("tooltip", tip); map.put("icon", icon); return map; } case COLUMN_CONTRACT: { HashMap<String, Object> map = new HashMap<>(); if (isBitcoin) { return map; } ImageIcon icon = null; //null; // TODO: Change to webPageJSON==null String tip = null; if (assetState != CSAsset.CSAssetState.VALID && asset.getContractPath() != null) { //(asset.getName() == null && icon = ImageLoader.fatCow16(ImageLoader.FATCOW.page_white_error); tip = "Click to read the cached copy of the contract"; } else if (assetState == CSAsset.CSAssetState.VALID) { icon = ImageLoader.fatCow16(ImageLoader.FATCOW.page_white_text); tip = "Click to read the contract at the web site of the issuer"; } if (tip != null && icon != null) { map.put("tooltip", tip); map.put("icon", icon); } return map; } // case "walletAssetTableColumn.issuer": // return asset.getIssuer(); // case "walletAssetTableColumn.issueDate": // return asset.getIssueDate(); // case "walletAssetTableColumn.contractUrl": // return asset.getContractUrl(); default: return null; // return rowObj.getDescription(); // case 3: // // Amount in BTC // BigInteger debitAmount = rowObj.getDebit(); // if (debitAmount != null && debitAmount.compareTo(BigInteger.ZERO) > 0) { // return controller.getLocaliser().bitcoinValueToString(debitAmount.negate(), false, true); // } // // BigInteger creditAmount = rowObj.getCredit(); // if (creditAmount != null) { // return controller.getLocaliser().bitcoinValueToString(creditAmount, false, true); // } // // return null; // case 4: // // Amount in fiat // if (rowObj.getDebit() != null && rowObj.getDebit().compareTo(BigInteger.ZERO) > 0) { // Money debitAmountFiat = CurrencyConverter.INSTANCE.convertFromBTCToFiat(rowObj.getDebit()); // if (debitAmountFiat != null) { // return CurrencyConverter.INSTANCE.getFiatAsLocalisedString(debitAmountFiat.negated(), false, false); // } // } // // Money creditAmountFiat = CurrencyConverter.INSTANCE.convertFromBTCToFiat(rowObj.getCredit()); // if (creditAmountFiat != null) { // return CurrencyConverter.INSTANCE.getFiatAsLocalisedString(creditAmountFiat, false, false); // } // // return ""; } }
From source file:org.openmrs.module.pihmalawi.common.AppointmentInfo.java
License:Open Source License
/** * @return the days remaining until the appointment date. a negative number indicates that number of days overdue. null indicates no scheduled appointment found. *//* w ww. j a v a 2 s . c o m*/ public Integer getDaysToAppointment() { // No scheduled appointment if (nextScheduledDate == null || !currentlyEnrolled) { return null; } // No scheduled appointment since prevoius encounter if (lastEncounterDate != null && nextScheduledDate.compareTo(lastEncounterDate) <= 0) { return null; } Date today = DateUtil.getStartOfDay(effectiveDate); Date apptDate = DateUtil.getStartOfDay(nextScheduledDate); int multiplier = apptDate.compareTo(today); // If appt date is in the past, multiply by -1 Date fromDate = (multiplier < 0 ? apptDate : today); Date toDate = (multiplier < 0 ? today : apptDate); Days days = Days.daysBetween(new DateTime(fromDate), new DateTime(toDate.getTime())); return days.getDays() * multiplier; }
From source file:org.openmrs.module.reporting.data.converter.AgeConverter.java
License:Open Source License
private Double getYearsToOneDecimalPlace(Age age) { if (age.getBirthDate() == null) { return null; }// w w w . j a v a2s . co m Days days = Days.daysBetween(new DateTime(age.getBirthDate().getTime()), new DateTime((age.getCurrentDate() == null ? new Date() : age.getCurrentDate()).getTime())); return Math.round(10d * (days.getDays() / 365.25d)) / 10d; }
From source file:org.sistemafinanciero.rest.impl.CuentaBancariaRESTService.java
License:Apache License
@Override public Response getCertificado(BigInteger id) { OutputStream file;/* ww w. jav a2 s . c o m*/ CuentaBancariaView cuentaBancaria = cuentaBancariaServiceNT.findById(id); String codigoAgencia = ProduceObject.getCodigoAgenciaFromNumeroCuenta(cuentaBancaria.getNumeroCuenta()); Agencia agencia = agenciaServiceNT.findByCodigo(codigoAgencia); if (agencia == null) { JsonObject model = Json.createObjectBuilder().add("message", "Agencia no encontrado").build(); return Response.status(Response.Status.NOT_FOUND).entity(model).build(); } try { file = new FileOutputStream(new File(certificadoURL + "\\" + id + ".pdf")); //Document document = new Document(PageSize.A5.rotate()); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, file); document.open(); //recuperando moneda, redondeando y dando formato Moneda moneda = monedaServiceNT.findById(cuentaBancaria.getIdMoneda()); BigDecimal saldo = cuentaBancaria.getSaldo(); BigDecimal decimalValue = saldo.subtract(saldo.setScale(0, RoundingMode.FLOOR)) .movePointRight(saldo.scale()); Long integerValue = saldo.longValue(); String decimalString = decimalValue.toString(); if (decimalString.length() < 2) decimalString = "0" + decimalString; NumberFormat df1 = NumberFormat.getCurrencyInstance(); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setCurrencySymbol(""); dfs.setGroupingSeparator(','); dfs.setMonetaryDecimalSeparator('.'); ((DecimalFormat) df1).setDecimalFormatSymbols(dfs); //recuperando el plazo en dias Date fechaApertura = cuentaBancaria.getFechaApertura(); Date fechaCierre = cuentaBancaria.getFechaCierre(); LocalDate localDateApertura = new LocalDate(fechaApertura); LocalDate localDateCierre = new LocalDate(fechaCierre); Days days = Days.daysBetween(localDateApertura, localDateCierre); //fuentes Font fontTitulo = FontFactory.getFont("Times New Roman", 14, Font.BOLD); Font fontSubTitulo = FontFactory.getFont("Times New Roman", 8); Font fontContenidoNegrita = FontFactory.getFont("Times New Roman", 10, Font.BOLD); Font fontContenidoNormal = FontFactory.getFont("Times New Roman", 10); //dando formato a las fechas DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String fechaAperturaString = df.format(cuentaBancaria.getFechaApertura()); String fechaVencimientoString = df.format(cuentaBancaria.getFechaCierre()); //ingresando datos al documento document.add(new Paragraph("\n")); document.add(new Paragraph("\n")); //parrafo titulo Paragraph parrafoTitulo = new Paragraph(); parrafoTitulo.setFont(fontTitulo); parrafoTitulo.setSpacingBefore(30); parrafoTitulo.setAlignment(Element.ALIGN_CENTER); //parrafo subtitulo Paragraph parrafoSubTitulo = new Paragraph(); parrafoSubTitulo.setFont(fontSubTitulo); parrafoSubTitulo.setSpacingAfter(30); parrafoSubTitulo.setAlignment(Element.ALIGN_CENTER); //parrafo contenido Paragraph parrafoContenido = new Paragraph(); parrafoContenido.setIndentationLeft(50); parrafoContenido.setAlignment(Element.ALIGN_LEFT); //parrafo firmas Paragraph parrafoFirmas = new Paragraph(); parrafoFirmas.setAlignment(Element.ALIGN_CENTER); //agregar titulo al documento Chunk titulo = new Chunk("CERTIFICADO DE PLAZO FIJO"); parrafoTitulo.add(titulo); //agregar titulo al documento Chunk subTitulo; if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) { subTitulo = new Chunk("DEPSITO A PLAZO FIJO - DOLARES AMERICANOS"); } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) { subTitulo = new Chunk("DEPSITO A PLAZO FIJO - NUEVOS SOLES"); } else { subTitulo = new Chunk("DEPSITO A PLAZO FIJO - EUROS"); } parrafoSubTitulo.add(subTitulo); //agregando contenido al documento //Agencia Chunk agencia1 = new Chunk("AGENCIA", fontContenidoNegrita); Chunk agencia2 = new Chunk(": " + agencia.getCodigo() + " - " + agencia.getDenominacion().toUpperCase(), fontContenidoNormal); parrafoContenido.add(agencia1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(agencia2); parrafoContenido.add("\n"); //cuenta Chunk numeroCuenta1 = new Chunk("N CUENTA", fontContenidoNegrita); Chunk numeroCuenta2 = new Chunk(": " + cuentaBancaria.getNumeroCuenta(), fontContenidoNormal); parrafoContenido.add(numeroCuenta1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(numeroCuenta2); parrafoContenido.add("\n"); //codigo cliente Chunk codigoSocio1 = new Chunk("CODIGO CLIENTE", fontContenidoNegrita); Chunk codigoSocio2 = new Chunk(": " + cuentaBancaria.getIdSocio().toString(), fontContenidoNormal); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(codigoSocio1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(codigoSocio2); parrafoContenido.add("\n"); //cliente Chunk socio1 = new Chunk("CLIENTE", fontContenidoNegrita); Chunk socio2 = new Chunk(": " + cuentaBancaria.getSocio(), fontContenidoNormal); parrafoContenido.add(socio1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(socio2); parrafoContenido.add("\n"); //tipo cuenta Chunk tipoCuenta1 = new Chunk("TIPO CUENTA", fontContenidoNegrita); Chunk tipoCuenta2 = new Chunk(": " + "INDIVIDUAL", fontContenidoNormal); parrafoContenido.add(tipoCuenta1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(tipoCuenta2); parrafoContenido.add("\n"); //tipo moneda Chunk tipoMoneda1 = new Chunk("TIPO MONEDA", fontContenidoNegrita); Chunk tipoMoneda2; if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) { tipoMoneda2 = new Chunk(": " + "DOLARES AMERICANOS", fontContenidoNormal); } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) { tipoMoneda2 = new Chunk(": " + "NUEVOS SOLES", fontContenidoNormal); } else { tipoMoneda2 = new Chunk(": " + "EUROS", fontContenidoNormal); } parrafoContenido.add(tipoMoneda1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(tipoMoneda2); parrafoContenido.add("\n"); //Monto Chunk monto1 = new Chunk("MONTO", fontContenidoNegrita); Chunk monto2 = new Chunk(": " + moneda.getSimbolo() + df1.format(saldo) + " - " + NumLetrasJ.Convierte(integerValue.toString() + "", Tipo.Pronombre).toUpperCase() + " Y " + decimalString + "/100 " + moneda.getDenominacion(), fontContenidoNormal); parrafoContenido.add(monto1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(monto2); parrafoContenido.add("\n"); //Plazo Chunk plazo1 = new Chunk("PLAZO", fontContenidoNegrita); Chunk plazo2 = new Chunk(": " + days.getDays() + " D?AS", fontContenidoNormal); parrafoContenido.add(plazo1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(plazo2); parrafoContenido.add("\n"); //Fecha Apertura Chunk fechaApertura1 = new Chunk("FEC. APERTURA", fontContenidoNegrita); Chunk fechaApertura2 = new Chunk(": " + fechaAperturaString, fontContenidoNormal); parrafoContenido.add(fechaApertura1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(fechaApertura2); parrafoContenido.add("\n"); //Fecha Vencimiento Chunk fechaVencimiento1 = new Chunk("FEC. VENCIMIENTO", fontContenidoNegrita); Chunk fechaVencimiento2 = new Chunk(": " + fechaVencimientoString, fontContenidoNormal); parrafoContenido.add(fechaVencimiento1); parrafoContenido.add(Chunk.SPACETABBING); parrafoContenido.add(fechaVencimiento2); parrafoContenido.add("\n"); //tasa efectiva anual Chunk tasaEfectivaAnual1 = new Chunk("TASA EFECTIVA ANUAL", fontContenidoNegrita); Chunk tasaEfectivaAnual2 = new Chunk( ": " + cuentaBancaria.getTasaInteres().multiply(new BigDecimal(100)).toString() + "%", fontContenidoNormal); parrafoContenido.add(tasaEfectivaAnual1); parrafoContenido.add(tasaEfectivaAnual2); parrafoContenido.add("\n"); //frecuencia de capitalizacion Chunk frecuenciaCapitalizacion1 = new Chunk("FREC. CAPITALIZACION", fontContenidoNegrita); Chunk frecuenciaCapitalizacion2 = new Chunk(": " + "DIARIA", fontContenidoNormal); parrafoContenido.add(frecuenciaCapitalizacion1); parrafoContenido.add(frecuenciaCapitalizacion2); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); //importante Chunk importante = new Chunk("IMPORTANTE: ", fontContenidoNegrita); Chunk importanteDetalle1 = new Chunk( "DEPSITO CUBIERTO POR EL FONDO DE SEGURO DE DEPOSITOS ESTABLECIDO POR EL BANCO CENTRAL DE RESERVA DEL PER HASTA S/.82,073.00.", fontSubTitulo); Chunk importanteDetalle2 = new Chunk( "LAS PERSONAS JUR?DICAS SIN FINES DE LUCRO SON CUBIERTAS POR EL FONDO DE SEGURO DE DEPSITOS.", fontSubTitulo); parrafoContenido.add(importante); parrafoContenido.add(importanteDetalle1); parrafoContenido.add("\n"); parrafoContenido.add(importanteDetalle2); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); //certificado intranferible Chunk certificadoIntransferible = new Chunk("CERTIFICADO INTRANSFERIBLE.", fontContenidoNegrita); parrafoContenido.add(certificadoIntransferible); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); parrafoContenido.add("\n"); //Firmas Chunk subGion = new Chunk("___________________", fontContenidoNormal); Chunk firmaCajero = new Chunk("CAJERO", fontContenidoNormal); Chunk firmaCliente = new Chunk("CLIENTE", fontContenidoNormal); parrafoFirmas.add(subGion); parrafoFirmas.add(Chunk.SPACETABBING); parrafoFirmas.add(Chunk.SPACETABBING); parrafoFirmas.add(subGion); parrafoFirmas.add("\n"); parrafoFirmas.add(firmaCajero); parrafoFirmas.add(Chunk.SPACETABBING); parrafoFirmas.add(Chunk.SPACETABBING); parrafoFirmas.add(Chunk.SPACETABBING); parrafoFirmas.add(firmaCliente); //agregando los parrafos al documento document.add(parrafoTitulo); document.add(parrafoSubTitulo); document.add(parrafoContenido); document.add(parrafoFirmas); document.close(); file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PdfReader reader; try { reader = new PdfReader(certificadoURL + "\\" + id + ".pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper pdfStamper = new PdfStamper(reader, out); AcroFields acroFields = pdfStamper.getAcroFields(); acroFields.setField("field_title", "test"); pdfStamper.close(); reader.close(); return Response.ok(out.toByteArray()).type("application/pdf").build(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Jsend.getErrorJSend("No encontrado")) .build(); }
From source file:org.smartdeveloperhub.harvesters.it.testing.generator.ProjectActivityGenerator.java
License:Apache License
private Duration estimateEffort(final LocalDateTime start, final LocalDateTime dueTo) { final Days daysBetween = Days.daysBetween(start, dueTo); int workingDays = 0; for (int i = 0; i < daysBetween.getDays(); i++) { if (Utils.isWorkingDay(start.toLocalDate().plusDays(i))) { workingDays++;//from www. j ava 2s. c o m } } final int maxMinutes = workingDays * this.workDay.effortPerDay(); final double ratio = (100 + this.random.nextInt(900)) / 1000d; Duration result = Duration.standardMinutes( 33 * maxMinutes / 100 + DoubleMath.roundToInt(67 * maxMinutes / 100 * ratio, RoundingMode.CEILING)); if (result.isShorterThan(MINIMUM_EFFORT)) { result = MINIMUM_EFFORT; } return result; }
From source file:org.zanata.client.commands.UpdateChecker.java
License:Open Source License
public boolean needToCheckUpdates(boolean interactiveMode) { DateTime today = new DateTime(); try {// ww w. j av a 2s . c o m if (!updateMarker.exists()) { createUpdateMarkerFile(updateMarker); console.printfln(_("update.marker.created"), updateMarker); console.printfln(_("update.marker.hint")); return true; } // read the content and see if we need to check Properties props = loadFileToProperties(updateMarker); DateTime lastCheckedDate = readLastCheckedDate(props); Days daysPassed = Days.daysBetween(lastCheckedDate, today); Frequency frequency = readFrequency(props); boolean timeToCheck = daysPassed.compareTo(frequency.days()) >= 0; boolean noAsking = readNoAsking(props); if (timeToCheck && !noAsking && interactiveMode) { console.printf(_("check.update.yes.no"), daysPassed.getDays()); String check = console.expectAnswerWithRetry(AnswerValidator.YES_NO); if (check.toLowerCase().startsWith("n")) { return false; } } return timeToCheck; } catch (Exception e) { log.debug("Error checking update marker file", e); log.warn("Error checking update marker file {}", updateMarker); log.warn("Please make sure its permission and content format"); return false; } }
From source file:org.zkoss.ganttz.util.Interval.java
License:Open Source License
public Fraction getProportion(DateTime date) { Days fromStartToDate = Days.daysBetween(startInclusive, date.toLocalDate()); Fraction result = Fraction.getFraction(fromStartToDate.getDays(), this.daysBetween.getDays()); try {/*from ww w .jav a 2 s . c o m*/ return result.add(inTheDayIncrement(date)); } catch (ArithmeticException e) { return result; } }