List of usage examples for java.math BigDecimal divide
public BigDecimal divide(BigDecimal divisor)
From source file:org.jvnet.hudson.plugins.backup.utils.RestoreTask.java
public void run() { assert (logFilePath != null); assert (backupFileName != null); startDate = new Date(); try {//from w w w. j av a 2s. c o m logger = new BackupLogger(logFilePath, configuration.isVerbose()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to open log file for writing : {0}", logFilePath); return; } logger.info("Restore started at " + getTimestamp(startDate)); File directory = new File(hudsonWorkDir); String tempDirectoryPath = hudsonWorkDir + "_restore"; logger.info("Working into " + tempDirectoryPath + " directory"); File temporary_directory = new File(tempDirectoryPath); if (temporary_directory.exists()) { logger.info("A old restore working dir exists, cleaning ..."); try { FileUtils.deleteDirectory(temporary_directory); } catch (IOException e) { logger.error("Unable to delete " + tempDirectoryPath); e.printStackTrace(logger.getWriter()); finished = true; return; } } temporary_directory.mkdir(); File archive = new File(backupFileName); logger.info("Uncompressing archive file..."); UnArchiver unAchiver = configuration.getArchiveType().getUnArchiver(); try { unAchiver.unArchive(archive, tempDirectoryPath); } catch (Exception e) { e.printStackTrace(logger.getWriter()); logger.error("Error uncompressiong archive : " + e.getMessage()); finished = true; return; } // Not using tools like FileUtils.deleteDirectory // because it is failing with non existing symbolic links logger.info("Removing old configuration files..."); delete(directory); logger.info("Making temporary directory the hudson home..."); temporary_directory.renameTo(directory); logger.info("*****************************************"); logger.info("Reloading hudson configuration from disk."); logger.info("*****************************************"); StaplerRequest request = FakeObject.getStaplerRequestFake(servletContext); StaplerResponse response = FakeObject.getStaplerResponseFake(); try { Hudson.getInstance().doReload(request, response); } catch (IOException e) { logger.error("Error reloading config files from disk."); logger.error("Call this method manually"); e.printStackTrace(logger.getWriter()); } endDate = new Date(); logger.info("Backup end at " + getTimestamp(endDate)); BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime()); delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP); delay = delay.divide(new BigDecimal("1000")); logger.info("[" + delay.toPlainString() + "s]"); finished = true; logger.close(); }
From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java
private String formatByteSize(final long value) { final String suffix; final String suffixedValue; if (value >= 0) { final BigDecimal KB = new BigDecimal(1000L); final BigDecimal MB = new BigDecimal(1000L * 1000); final BigDecimal GB = new BigDecimal(1000L * 1000 * 1000); BigDecimal bd = new BigDecimal(value); if (bd.compareTo(GB) > 0) { bd = bd.divide(GB); suffix = "GB"; } else if (bd.compareTo(MB) > 0) { bd = bd.divide(MB);//w w w. ja v a 2s. com suffix = "MB"; } else if (bd.compareTo(KB) > 0) { bd = bd.divide(KB); suffix = "kB"; } else { suffix = "B"; } suffixedValue = bd.setScale(2, RoundingMode.UP).toString(); } else { suffixedValue = "n/a"; suffix = ""; } return suffixedValue + suffix; }
From source file:com.gamethrive.TrackGooglePurchase.java
private void sendPurchases(final ArrayList<String> skusToAdd, final ArrayList<String> newPurchaseTokens) { try {//from ww w. j a v a2 s. c om if (getSkuDetailsMethod == null) getSkuDetailsMethod = IInAppBillingServiceClass.getMethod("getSkuDetails", int.class, String.class, String.class, Bundle.class); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skusToAdd); Bundle skuDetails = (Bundle) getSkuDetailsMethod.invoke(mIInAppBillingService, 3, appContext.getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); Map<String, JSONObject> currentSkus = new HashMap<String, JSONObject>(); JSONObject jsonItem; for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); String sku = object.getString("productId"); BigDecimal price = new BigDecimal(object.getString("price_amount_micros")); price = price.divide(new BigDecimal(1000000)); jsonItem = new JSONObject(); jsonItem.put("sku", sku); jsonItem.put("iso", object.getString("price_currency_code")); jsonItem.put("amount", price.toString()); currentSkus.put(sku, jsonItem); } JSONArray purchasesToReport = new JSONArray(); for (String sku : skusToAdd) { if (!currentSkus.containsKey(sku)) continue; purchasesToReport.put(currentSkus.get(sku)); } // New purchases to report. // Wait until we have a playerID then send purchases to server. If successful then mark them as tracked. if (purchasesToReport.length() > 0) { final JSONArray finalPurchasesToReport = purchasesToReport; gameThrive.idsAvailable(new IdsAvailableHandler() { public void idsAvailable(String playerId, String registrationId) { gameThrive.sendPurchases(finalPurchasesToReport, newAsExisting, new JsonHttpResponseHandler() { public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.i(GameThrive.TAG, "JSON sendPurchases Failed"); throwable.printStackTrace(); isWaitingForPurchasesRequest = false; } public void onSuccess(int statusCode, Header[] headers, JSONObject response) { purchaseTokens.addAll(newPurchaseTokens); prefsEditor.putString("purchaseTokens", purchaseTokens.toString()); prefsEditor.remove("ExistingPurchases"); prefsEditor.commit(); newAsExisting = false; isWaitingForPurchasesRequest = false; } }); } }); } } } catch (Throwable t) { t.printStackTrace(); } }
From source file:org.openhab.binding.denonmarantz.internal.connector.telnet.DenonMarantzTelnetConnector.java
private BigDecimal fromDenonValue(String string) { /*/*from www .j a v a 2 s . c o m*/ * 455 = 45,5 * 45 = 45 * 045 = 4,5 * 04 = 4 */ BigDecimal value = new BigDecimal(string); if (value.compareTo(NINETYNINE) == 1 || (string.startsWith("0") && string.length() > 2)) { value = value.divide(BigDecimal.TEN); } return value; }
From source file:easycare.load.util.db.loader.UserDataLoader.java
private void createPaddingUsers(ContextOfCurrentLoad context, Organisation organisation, String organisationNumber) { BigDecimal numberOfPatientsPerOrg = context.numberOfPatientsInPassedOrg(organisation, organisationNumber); int numberOfPaddingUsers = numberOfPatientsPerOrg.divide(PADDING_FACTOR).setScale(0, RoundingMode.FLOOR) .intValue();//from w w w . j a v a 2 s. co m List<Role> roles = newArrayList(seedData.getRole(RoleEnum.ROLE_CLINICIAN)); for (int i = 0; i < numberOfPaddingUsers; i++) { buildUser(context, String.format("paddy%s-%d", organisationNumber, i), context.getFaker().firstName(), context.getFaker().lastName(), organisation, roles, organisationNumber); } }
From source file:org.jvnet.hudson.plugins.backup.utils.BackupTask.java
public void run() { assert (logFilePath != null); assert (configuration.getFileNameTemplate() != null); SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); startDate = new Date(); try {/* w ww . j a v a2 s. co m*/ logger = new BackupLogger(logFilePath, configuration.isVerbose()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to open log file for writing: {0}", logFilePath); return; } logger.info("Backup started at " + getTimestamp(startDate)); // Have to include shutdown time in backup time ? waitNoJobsInQueue(); // file filter specific to what's inside jobs' worskpace IOFileFilter jobsExclusionFileFilter = null; // Creating global exclusions List<String> exclusions = new ArrayList<String>(); exclusions.addAll(Arrays.asList(DEFAULT_EXCLUSIONS)); exclusions.addAll(configuration.getCustomExclusions()); if (!configuration.getKeepWorkspaces()) { exclusions.add(WORKSPACE_NAME); } else { jobsExclusionFileFilter = createJobsExclusionFileFilter(hudsonWorkDir, configuration.getJobIncludes(), configuration.getJobExcludes(), configuration.getCaseSensitive()); } if (!configuration.getKeepFingerprints()) { exclusions.add(FINGERPRINTS_NAME); } if (!configuration.getKeepBuilds()) { exclusions.add(BUILDS_NAME); } if (!configuration.getKeepArchives()) { exclusions.add(ARCHIVE_NAME); } IOFileFilter filter = createFileFilter(exclusions, jobsExclusionFileFilter); try { BackupEngine backupEngine = new BackupEngine(logger, hudsonWorkDir, backupFileName, configuration.getArchiveType().getArchiver(), filter); backupEngine.doBackup(); } catch (BackupException e) { e.printStackTrace(logger.getWriter()); } finally { cancelNoJobs(); endDate = new Date(); logger.info("Backup end at " + getTimestamp(endDate)); BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime()); delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP); delay = delay.divide(new BigDecimal("1000")); logger.info("[" + delay.toPlainString() + "s]"); finished = true; logger.close(); } }
From source file:com.onesignal.TrackGooglePurchase.java
private void sendPurchases(final ArrayList<String> skusToAdd, final ArrayList<String> newPurchaseTokens) { try {//from ww w. j a v a2 s . co m if (getSkuDetailsMethod == null) { getSkuDetailsMethod = getGetSkuDetailsMethod(IInAppBillingServiceClass); getSkuDetailsMethod.setAccessible(true); } Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skusToAdd); Bundle skuDetails = (Bundle) getSkuDetailsMethod.invoke(mIInAppBillingService, 3, appContext.getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); Map<String, JSONObject> currentSkus = new HashMap<String, JSONObject>(); JSONObject jsonItem; for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); String sku = object.getString("productId"); BigDecimal price = new BigDecimal(object.getString("price_amount_micros")); price = price.divide(new BigDecimal(1000000)); jsonItem = new JSONObject(); jsonItem.put("sku", sku); jsonItem.put("iso", object.getString("price_currency_code")); jsonItem.put("amount", price.toString()); currentSkus.put(sku, jsonItem); } JSONArray purchasesToReport = new JSONArray(); for (String sku : skusToAdd) { if (!currentSkus.containsKey(sku)) continue; purchasesToReport.put(currentSkus.get(sku)); } // New purchases to report. // Wait until we have a userID then send purchases to server. If successful then mark them as tracked. if (purchasesToReport.length() > 0) { final JSONArray finalPurchasesToReport = purchasesToReport; OneSignal.idsAvailable(new IdsAvailableHandler() { public void idsAvailable(String userId, String registrationId) { OneSignal.sendPurchases(finalPurchasesToReport, newAsExisting, new OneSignalRestClient.ResponseHandler() { public void onFailure(int statusCode, JSONObject response, Throwable throwable) { OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "HTTP sendPurchases failed to send.", throwable); isWaitingForPurchasesRequest = false; } public void onSuccess(String response) { purchaseTokens.addAll(newPurchaseTokens); prefsEditor.putString("purchaseTokens", purchaseTokens.toString()); prefsEditor.remove("ExistingPurchases"); prefsEditor.commit(); newAsExisting = false; isWaitingForPurchasesRequest = false; } }); } }); } } } catch (Throwable t) { OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "Failed to track IAP purchases", t); } }
From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG Date,Open,High,Low,Close,Volume,Adj Close 2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30 2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00 *///www .j a v a 2 s . c o m int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January int fromDD = Integer.valueOf(request.getParameter("b")); int fromYYYY = Integer.valueOf(request.getParameter("c")); int toMM = Integer.valueOf(request.getParameter("d")); int toDD = Integer.valueOf(request.getParameter("e")); int toYYYY = Integer.valueOf(request.getParameter("f")); String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear ValidationUtils.validateResolution(resolution); String symbol = request.getParameter("s"); ValidationUtils.validateSymbol(symbol); String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING)); String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache FileCache fileCache = JsquantContextListener.getFileCache(request); String responseBody = fileCache.get(cacheKey); if (responseBody == null) { HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString); ResponseHandler<String> responseHandler = new BasicResponseHandler(); log.debug("requesting uri=" + httpget.getURI()); responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler); //httpget.setReleaseTrigger(releaseTrigger); // no need to close? fileCache.put(cacheKey, responseBody); } String[] lines = responseBody.split("\n"); List<Stock> dayPrices = new ArrayList<Stock>(); int index = 0; for (String line : lines) if (index++ > 0 && line.length() > 0) dayPrices.add(new Stock(line)); Collections.reverse(dayPrices); index = 0; BigDecimal allTimeHighClose = new BigDecimal(0); BigDecimal stopAt = null; BigDecimal boughtPrice = null; Stock sPrev = null; for (Stock s : dayPrices) { allTimeHighClose = allTimeHighClose.max(s.adjClose); s.allTimeHighClose = allTimeHighClose; if (index > 0) { sPrev = dayPrices.get(index - 1); //true range = max(high,closeprev) - min(low,closeprev) s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose)); } int rng = 10; if (index > rng) { BigDecimal sum = new BigDecimal(0); for (Stock s2 : dayPrices.subList(index - rng, index)) sum = sum.add(s2.trueRange); s.ATR10 = sum.divide(new BigDecimal(rng)); if (allTimeHighClose.equals(s.adjClose)) { stopAt = s.adjClose.subtract(s.ATR10); } } s.stopAt = stopAt; if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) { s.order = OrderAction.SELL; s.soldPrice = s.adjClose; s.soldDifference = s.soldPrice.subtract(boughtPrice); } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null && sPrev.order == OrderAction.IGNORE) { s.order = OrderAction.BUY; boughtPrice = s.adjClose; s.boughtPrice = boughtPrice; } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) { s.order = OrderAction.HOLD; } else { s.order = OrderAction.IGNORE; } index++; } ServletOutputStream out = response.getOutputStream(); out.println(lines[0] + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference"); for (Stock s : dayPrices) out.println(s.getCSV()); }
From source file:com.coinblesk.client.utils.UIUtils.java
public static String coinToAmount(Context context, Coin coin) { // transform a given coin value to the "amount string". BigDecimal coinAmount = new BigDecimal(coin.getValue()); BigDecimal div = new BigDecimal(Coin.COIN.getValue()); if (SharedPrefUtils.isBitcoinScaleBTC(context)) { div = new BigDecimal(Coin.COIN.getValue()); } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) { div = new BigDecimal(Coin.MILLICOIN.getValue()); } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) { div = new BigDecimal(Coin.MICROCOIN.getValue()); }/*from w w w . ja v a 2 s .c o m*/ DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.DOWN); df.setMaximumFractionDigits(4); DecimalFormatSymbols decFormat = new DecimalFormatSymbols(); decFormat.setDecimalSeparator('.'); df.setDecimalFormatSymbols(decFormat); String amount = df.format(coinAmount.divide(div)); return amount; }
From source file:com.repay.android.adddebt.AddDebtActivity.java
private void submitToDB() { try {//from w ww. jav a 2s . c o m if (mSelectedFriends.size() == 0) { throw new NullPointerException(); } else if (mSelectedFriends.size() == 1) { BigDecimal latestAmount = new BigDecimal(mAmount.toString()); if (mNegativeDebt) { latestAmount = latestAmount.negate(); } if (mSplitAmount) { latestAmount = latestAmount.divide(BigDecimal.valueOf(2)); } mDB.addDebt(mSelectedFriends.get(0).getRepayID(), latestAmount, mDescription); mSelectedFriends.get(0).setDebt(mSelectedFriends.get(0).getDebt().add(latestAmount)); mDB.updateFriendRecord(mSelectedFriends.get(0)); } else if (mSelectedFriends.size() > 1) { BigDecimal debtPerPerson; if (mSplitAmount) { int numOfPeeps = mSelectedFriends.size(); Log.i(TAG, Integer.toString(numOfPeeps) + " people selected"); numOfPeeps += (mInclMe) ? 1 : 0; // If is including me then add me into this Log.i(TAG, "isIncludingMe=" + Boolean.toString(mInclMe)); debtPerPerson = new BigDecimal(mAmount.toString()); debtPerPerson = debtPerPerson.divide(new BigDecimal(numOfPeeps), RoundingMode.CEILING); } else { debtPerPerson = new BigDecimal(mAmount.toString()); } if (mNegativeDebt) { debtPerPerson = debtPerPerson.negate(); } for (int i = 0; i <= mSelectedFriends.size() - 1; i++) { mDB.addDebt(mSelectedFriends.get(i).getRepayID(), debtPerPerson, mDescription); mSelectedFriends.get(i).setDebt(mSelectedFriends.get(i).getDebt().add(debtPerPerson)); mDB.updateFriendRecord(mSelectedFriends.get(i)); } } requestBackup(); finish(); } catch (SQLException e) { Toast.makeText(this, "Database Error", Toast.LENGTH_SHORT).show(); } catch (NullPointerException e) { Toast.makeText(this, "Select a person and enter an amount first!", Toast.LENGTH_SHORT).show(); } catch (NumberFormatException e) { Toast.makeText(this, "Please enter a valid amount!", Toast.LENGTH_SHORT).show(); } catch (ArithmeticException e) { Toast.makeText(this, "You can't divide this number between this many people", Toast.LENGTH_SHORT) .show(); } }