List of usage examples for org.joda.time LocalDateTime toString
public String toString(String pattern)
From source file:org.gnucash.android.ui.report.linechart.CashFlowLineChartFragment.java
License:Apache License
/** * Returns entries which represent a user data of the specified account type * @param accountType account's type which user data will be processed * @return entries which represent a user data *//*from w w w . ja v a2 s.c o m*/ private List<Entry> getEntryList(AccountType accountType) { List<String> accountUIDList = new ArrayList<>(); for (Account account : mAccountsDbAdapter.getSimpleAccountList()) { if (account.getAccountType() == accountType && !account.isPlaceholderAccount() && account.getCommodity().equals(mCommodity)) { accountUIDList.add(account.getUID()); } } LocalDateTime earliest; LocalDateTime latest; if (mReportPeriodStart == -1 && mReportPeriodEnd == -1) { earliest = new LocalDateTime(mEarliestTimestampsMap.get(accountType)); latest = new LocalDateTime(mLatestTimestampsMap.get(accountType)); } else { earliest = new LocalDateTime(mReportPeriodStart); latest = new LocalDateTime(mReportPeriodEnd); } Log.d(TAG, "Earliest " + accountType + " date " + earliest.toString("dd MM yyyy")); Log.d(TAG, "Latest " + accountType + " date " + latest.toString("dd MM yyyy")); int xAxisOffset = getDateDiff(new LocalDateTime(mEarliestTransactionTimestamp), earliest); int count = getDateDiff(earliest, latest); List<Entry> values = new ArrayList<>(count + 1); for (int i = 0; i <= count; i++) { long start = 0; long end = 0; switch (mGroupInterval) { case QUARTER: int quarter = getQuarter(earliest); start = earliest.withMonthOfYear(quarter * 3 - 2).dayOfMonth().withMinimumValue().millisOfDay() .withMinimumValue().toDate().getTime(); end = earliest.withMonthOfYear(quarter * 3).dayOfMonth().withMaximumValue().millisOfDay() .withMaximumValue().toDate().getTime(); earliest = earliest.plusMonths(3); break; case MONTH: start = earliest.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate() .getTime(); end = earliest.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime(); earliest = earliest.plusMonths(1); break; case YEAR: start = earliest.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime(); end = earliest.dayOfYear().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime(); earliest = earliest.plusYears(1); break; } float balance = (float) mAccountsDbAdapter.getAccountsBalance(accountUIDList, start, end).asDouble(); values.add(new Entry(balance, i + xAxisOffset)); Log.d(TAG, accountType + earliest.toString(" MMM yyyy") + ", balance = " + balance); } return values; }
From source file:org.gnucash.android.ui.report.LineChartFragment.java
License:Apache License
/** * Returns entries which represent a user data of the specified account type * @param accountType account's type which user data will be processed * @return entries which represent a user data */// w ww.ja v a2 s . co m private List<Entry> getEntryList(AccountType accountType) { List<String> accountUIDList = new ArrayList<>(); for (Account account : mAccountsDbAdapter.getSimpleAccountList()) { if (account.getAccountType() == accountType && !account.isPlaceholderAccount() && account.getCurrency() == mCurrency) { accountUIDList.add(account.getUID()); } } LocalDateTime earliest; LocalDateTime latest; if (mReportStartTime == -1 && mReportEndTime == -1) { earliest = new LocalDateTime(mEarliestTimestampsMap.get(accountType)); latest = new LocalDateTime(mLatestTimestampsMap.get(accountType)); } else { earliest = new LocalDateTime(mReportStartTime); latest = new LocalDateTime(mReportEndTime); } Log.d(TAG, "Earliest " + accountType + " date " + earliest.toString("dd MM yyyy")); Log.d(TAG, "Latest " + accountType + " date " + latest.toString("dd MM yyyy")); int xAxisOffset = getDateDiff(new LocalDateTime(mEarliestTransactionTimestamp), earliest); int count = getDateDiff(earliest, latest); List<Entry> values = new ArrayList<>(count + 1); for (int i = 0; i <= count; i++) { long start = 0; long end = 0; switch (mGroupInterval) { case QUARTER: int quarter = getQuarter(earliest); start = earliest.withMonthOfYear(quarter * 3 - 2).dayOfMonth().withMinimumValue().millisOfDay() .withMinimumValue().toDate().getTime(); end = earliest.withMonthOfYear(quarter * 3).dayOfMonth().withMaximumValue().millisOfDay() .withMaximumValue().toDate().getTime(); earliest = earliest.plusMonths(3); break; case MONTH: start = earliest.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate() .getTime(); end = earliest.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime(); earliest = earliest.plusMonths(1); break; case YEAR: start = earliest.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime(); end = earliest.dayOfYear().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime(); earliest = earliest.plusYears(1); break; } float balance = (float) mAccountsDbAdapter.getAccountsBalance(accountUIDList, start, end).asDouble(); values.add(new Entry(balance, i + xAxisOffset)); Log.d(TAG, accountType + earliest.toString(" MMM yyyy") + ", balance = " + balance); } return values; }
From source file:org.kuali.kpme.tklm.time.timesummary.service.TimeSummaryServiceImpl.java
License:Educational Community License
/** * Helper function to generate display text for the summary header. * @param currentDate The date we are generating for. * @param virtualDays Whether or not virtual days apply. * @return A string appropriate for UI display. *///ww w .j a va 2 s . co m private String makeHeaderDiplayString(LocalDateTime currentDate, boolean virtualDays) { StringBuilder display = new StringBuilder(); display.append(currentDate.toString("E")); if (virtualDays) { LocalDateTime nextDate = currentDate.plusDays(1); display.append(" - "); display.append(nextDate.toString("E")); } display.append("<br />"); display.append(currentDate.toString(TkConstants.DT_ABBREV_DATE_FORMAT)); if (virtualDays) { LocalDateTime nextDate = currentDate.plusDays(1); display.append(" - "); display.append(nextDate.toString(TkConstants.DT_ABBREV_DATE_FORMAT)); } return display.toString(); }
From source file:org.multibit.viewsystem.swing.view.panels.CSAssetDetailPanel.java
License:MIT License
String prettyFormatDate(Date d) { if (d == null) return ""; LocalDateTime dt = new DateTime(d).toLocalDateTime(); return dt.toString("d MMM y, HH:mm:ss z"); }
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 ww . j a v a2s . co m*/ 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.multibit.viewsystem.swing.WalletAssetTableModel.java
License:MIT License
@Override public Object getValueAt(int row, int column) { WalletAssetTableData rowObj = null;/* w w w.j a va2s.com*/ if (row >= 0 && row < walletAssetData.size()) { rowObj = walletAssetData.get(row); } if (rowObj == null) { return null; } CSAsset asset = rowObj.getAsset(); // 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 "walletAssetTableColumn.assetID": { // can return null, date object return asset.getAssetID(); } case "walletAssetTableColumn.visibility": { return new Boolean(asset.isVisible()); } case "walletAssetTableColumn.state": { CSAsset.CSAssetState state = asset.getAssetState(); // TODO: Special case where the asset is valid, but we asset reference is nul. if (state == CSAsset.CSAssetState.VALID && asset.getAssetReference() == null) { return "Awaiting new asset confirmation..."; } return CSMiscUtils.getHumanReadableAssetState(asset.getAssetState()); } case "walletAssetTableColumn.assetRef": { if (asset.getAssetReference() == null) { return "Awaiting new asset confirmation..."; } return CSMiscUtils.getHumanReadableAssetRef(asset); } case "walletAssetTableColumn.quantity": { if (asset.getName() == null) { return "..."; } Wallet wallet = this.bitcoinController.getModel().getActiveWallet(); int assetID = asset.getAssetID(); Wallet.CoinSpark.AssetBalance assetBalance = wallet.CS.getAssetBalance(assetID); BigInteger x = assetBalance.total; //wallet.CS.getUnspentAssetQuantity(assetID); String display = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, x); if (assetBalance.updatingNow) { if (x.intValue() == 0) { display = "..."; } else { display += " + ..."; } } return display; } case "walletAssetTableColumn.name": { HashMap map = new HashMap<>(); String name = asset.getNameShort(); Font f = null; if (name == null) { CoinSparkGenesis genesis = asset.getGenesis(); if (genesis != null) { name = genesis.getPagePath(); } if (name != null) { name = "/" + name + "/"; } else { name = "Unknown Name"; } //name = asset.getAssetWebPageURL(); f = new Font(null, Font.ITALIC, 12); } else { f = FontSizer.INSTANCE.getAdjustedDefaultFont(); } map.put("label", name); map.put("font", f); map.put("truncatedTooltip", Boolean.TRUE); return map; } case "walletAssetTableColumn.issuer": { HashMap map = new HashMap<>(); Font f = null; String issuer = asset.getIssuer(); if (issuer == null) { issuer = CSMiscUtils.getDomainHost(asset.getDomainURL()); f = new Font(null, Font.ITALIC, 12); } else { f = FontSizer.INSTANCE.getAdjustedDefaultFont(); } map.put("label", issuer); map.put("font", f); map.put("truncatedTooltip", true); return map; } case "walletAssetTableColumn.issueDate": { Date d = asset.getIssueDate(); if (d == null) return ""; LocalDateTime dt = new DateTime(d).toLocalDateTime(); return dt.toString("d MMM y"); } 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.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java
License:MIT License
@Override public synchronized Boolean createwallet(String name) throws com.bitmechanic.barrister.RpcException { log.info("CREATE WALLET"); log.info("wallet name = " + name); boolean isNameSane = sanityCheckName(name); if (!isNameSane) { JSONRPCError.WALLET_NAME_BAD_CHARS.raiseRpcException(); }// w w w.j a v a 2s . co m if (name.startsWith("-") || name.startsWith("_")) { JSONRPCError.WALLET_NAME_BEGINS_WITH_SYMBOL.raiseRpcException(); } String newWalletFilename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + name + MultiBitService.WALLET_SUFFIX; File newWalletFile = new File(newWalletFilename); if (newWalletFile.exists()) { JSONRPCError.WALLET_ID_ALREADY_EXISTS.raiseRpcException(); } LocalDateTime dt = new DateTime().toLocalDateTime(); String description = name + " (jsonrpc " + dt.toString("YYYY-MM-DD HH:mm" + ")"); //.SSS"); // Create a new wallet - protobuf.2 initially for backwards compatibility. try { Wallet newWallet = new Wallet(this.controller.getModel().getNetworkParameters()); ECKey newKey = new ECKey(); newWallet.addKey(newKey); WalletData perWalletModelData = new WalletData(); /* CoinSpark START */ // set default address label for first key WalletInfoData walletInfo = new WalletInfoData(newWalletFilename, newWallet, MultiBitWalletVersion.PROTOBUF); NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); Address defaultReceivingAddress = newKey.toAddress(networkParams); walletInfo.getReceivingAddresses() .add(new WalletAddressBookData("Default Address", defaultReceivingAddress.toString())); perWalletModelData.setWalletInfo(walletInfo); /* CoinSpark END */ perWalletModelData.setWallet(newWallet); perWalletModelData.setWalletFilename(newWalletFilename); perWalletModelData.setWalletDescription(description); this.controller.getFileHandler().savePerWalletModelData(perWalletModelData, true); // Start using the new file as the wallet. this.controller.addWalletFromFilename(newWalletFile.getAbsolutePath()); // We could select the new wallet if we wanted to. //this.controller.getModel().setActiveWalletByFilename(newWalletFilename); //controller.getModel().setUserPreference(BitcoinModel.GRAB_FOCUS_FOR_ACTIVE_WALLET, "true"); // Save the user properties to disk. FileHandler.writeUserPreferences(this.controller); //log.debug("User preferences with new wallet written successfully"); // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(controller.getFileHandler(), perWalletModelData); controller.fireRecreateAllViews(true); controller.fireDataChangedUpdateNow(); } catch (Exception e) { JSONRPCError.CREATE_WALLET_FAILED.raiseRpcException(); //JSONRPCError.throwAsRpcException("Could not create wallet", e); } // updateWalletFilenameMap(); return true; }
From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java
License:MIT License
@Override public synchronized JSONRPCAddressBookEntry[] createaddresses(String walletID, Long quantity) throws com.bitmechanic.barrister.RpcException { log.info("CREATE ADDRESSES"); log.info("wallet name = " + walletID); log.info("quantity = " + quantity); Wallet w = getWalletForWalletName(walletID); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); }// w ww . j av a 2s .com int qty = quantity.intValue(); if (qty <= 0) { JSONRPCError.CREATE_ADDRESS_TOO_FEW.raiseRpcException(); } if (qty > CREATE_ADDRESSES_LIMIT) { JSONRPCError.CREATE_ADDRESS_TOO_MANY.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.createaddress"); this.controller.fireWalletBusyChange(true); } List<JSONRPCAddressBookEntry> addresses = new ArrayList<JSONRPCAddressBookEntry>(); try { List<ECKey> newKeys = new ArrayList<ECKey>(); for (int i = 0; i < qty; i++) { ECKey newKey = new ECKey(); newKeys.add(newKey); } FileHandler fileHandler = this.controller.getFileHandler(); synchronized (wd.getWallet()) { wd.getWallet().addKeys(newKeys); } // Recalculate the bloom filter. if (this.controller.getMultiBitService() != null) { this.controller.getMultiBitService().recalculateFastCatchupAndFilter(); } // Add keys to address book. int n = 1, count = newKeys.size(); for (ECKey newKey : newKeys) { String lastAddressString = newKey.toAddress(this.controller.getModel().getNetworkParameters()) .toString(); LocalDateTime dt = new DateTime().toLocalDateTime(); String label = "Created on " + dt.toString("d MMM y, HH:mm:ss z") + " (" + n++ + " of " + count + ")"; // unlikely address is already present, we don't want to update the label wd.getWalletInfo().addReceivingAddress(new WalletAddressBookData(label, lastAddressString), false); // Create structure for JSON response String sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(lastAddressString); if (sparkAddress == null) sparkAddress = "Internal error creating CoinSparkAddress from this Bitcoin address"; JSONRPCAddressBookEntry entry = new JSONRPCAddressBookEntry(label, lastAddressString, sparkAddress); addresses.add(entry); } // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(fileHandler, wd); } catch (KeyCrypterException e) { JSONRPCError.throwAsRpcException("Create addresses failed with KeyCrypterException", e); } catch (Exception e) { JSONRPCError.throwAsRpcException("Create addresses failed", e); } finally { // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } CSEventBus.INSTANCE.postAsync(new SBEvent(SBEventType.ADDRESS_CREATED)); wd.setDirty(true); JSONRPCAddressBookEntry[] resultArray = addresses.toArray(new JSONRPCAddressBookEntry[0]); return resultArray; }
From source file:org.supercsv.cellprocessor.joda.FmtLocalDateTime.java
License:Apache License
/** * {@inheritDoc}// ww w .ja v a 2 s . co m */ @Override protected String format(final LocalDateTime jodaType, final DateTimeFormatter formatter) { return jodaType.toString(formatter); }
From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java
protected WebElement setLocalDateTimeInDateField(String caption, LocalDateTime localDateTime) { doPreOperationChecks();/*from w w w .j a va2 s . com*/ String localDateAsString = localDateTime == null ? "" : localDateTime.toString("MM/dd/yyyy hh:mm aaa"); logStep.info("Setting date in date field with caption: " + caption + " to: " + localDateAsString); WebElement textField = getDateField(caption); assertNotNull("Could not set date in datefield with caption " + caption + " because it wasn't found.", textField); textField.click(); //so that it receives focus, otherwise sendKeys() loses characteres textField.clear(); textField.sendKeys(localDateAsString); assertNoExceptionOccurred(); assertFieldHasValue(caption, textField, localDateAsString); unblurField(textField); doPostOperationChecks(); return textField; }