List of usage examples for java.util Currency getInstance
public static Currency getInstance(Locale locale)
Currency
instance for the country of the given locale. From source file:no.abmu.lise.util.LiseImportExcelParser.java
private Currency getCurrencyFromCurrencyCode(String string) { String currencyCode = string.trim(); Currency currency = null;/*from w w w. j a v a 2 s . c o m*/ try { currency = Currency.getInstance(currencyCode); } catch (IllegalArgumentException e) { if (logger.isDebugEnabled()) { logger.debug("'" + currencyCode + "' is not a valid currencyCode."); } } return currency; }
From source file:org.apache.cordova.core.Globalization.java
private JSONObject getCurrencyPattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {/* w w w . jav a2 s .com*/ //get ISO 4217 currency code String code = options.getJSONObject(0).getString(CURRENCYCODE); //uses java.text.DecimalFormat to format value DecimalFormat fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); //set currency format Currency currency = Currency.getInstance(code); fmt.setCurrency(currency); //return properties obj.put("pattern", fmt.toPattern()); obj.put("code", currency.getCurrencyCode()); obj.put("fraction", fmt.getMinimumFractionDigits()); obj.put("rounding", new Integer(0)); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); } }
From source file:org.gnucash.android.ui.account.AccountFormFragment.java
private void saveAccount() { if (mAccount == null) { String name = getEnteredName(); if (name == null || name.length() == 0) { Toast.makeText(getSherlockActivity(), R.string.toast_no_account_name_entered, Toast.LENGTH_LONG) .show();/*from ww w . ja v a2s.c o m*/ return; } mAccount = new Account(getEnteredName()); } else mAccount.setName(getEnteredName()); String curCode = mCurrencyCodes.get(mCurrencySpinner.getSelectedItemPosition()); mAccount.setCurrency(Currency.getInstance(curCode)); Account.AccountType selectedAccountType = getSelectedAccountType(); mAccount.setAccountType(selectedAccountType); mAccount.setPlaceHolderFlag(mPlaceholderCheckBox.isChecked()); mAccount.setColorCode(mSelectedColor); if (mParentCheckBox.isChecked()) { long id = mParentAccountSpinner.getSelectedItemId(); mAccount.setParentUID(mAccountsDbAdapter.getAccountUID(id)); } else { //need to do this explicitly in case user removes parent account mAccount.setParentUID(null); } if (mDefaultTransferAccountCheckBox.isChecked()) { long id = mDefaulTransferAccountSpinner.getSelectedItemId(); mAccount.setDefaultTransferAccountUID(mAccountsDbAdapter.getAccountUID(id)); } else { //explicitly set in case of removal of default account mAccount.setDefaultTransferAccountUID(null); } if (mAccountsDbAdapter == null) mAccountsDbAdapter = new AccountsDbAdapter(getActivity()); mAccountsDbAdapter.addAccount(mAccount); finishFragment(); }
From source file:org.openestate.io.idx.IdxRecord.java
public Currency getCurrency() { String value = this.get(FIELD_CURRENCY); try {// w ww .ja va2s.co m return (value != null) ? Currency.getInstance(value) : null; } catch (IllegalArgumentException ex) { LOGGER.warn("Can't read currency from '" + value + "'!"); LOGGER.warn("> " + ex.getLocalizedMessage(), ex); return null; } }
From source file:de.schildbach.pte.AbstractHafasMobileProvider.java
protected final QueryTripsResult jsonTripSearch(Location from, @Nullable Location via, Location to, final Date time, final boolean dep, final @Nullable Set<Product> products, final String moreContext) throws IOException { if (!from.hasId()) { from = jsonTripSearchIdentify(from); if (from == null) return new QueryTripsResult(new ResultHeader(network, SERVER_PRODUCT), QueryTripsResult.Status.UNKNOWN_FROM); }/*from w w w. j a v a2 s.com*/ if (via != null && !via.hasId()) { via = jsonTripSearchIdentify(via); if (via == null) return new QueryTripsResult(new ResultHeader(network, SERVER_PRODUCT), QueryTripsResult.Status.UNKNOWN_VIA); } if (!to.hasId()) { to = jsonTripSearchIdentify(to); if (to == null) return new QueryTripsResult(new ResultHeader(network, SERVER_PRODUCT), QueryTripsResult.Status.UNKNOWN_TO); } final Calendar c = new GregorianCalendar(timeZone); c.setTime(time); final CharSequence outDate = jsonDate(c); final CharSequence outTime = jsonTime(c); final CharSequence outFrwdKey = "1.11".equals(apiVersion) ? "outFrwd" : "frwd"; final CharSequence outFrwd = Boolean.toString(dep); final CharSequence jnyFltr = productsString(products); final CharSequence jsonContext = moreContext != null ? "\"ctxScr\":" + JSONObject.quote(moreContext) + "," : ""; final String request = wrapJsonApiRequest("TripSearch", "{" // + jsonContext // + "\"depLocL\":[" + jsonLocation(from) + "]," // + "\"arrLocL\":[" + jsonLocation(to) + "]," // + (via != null ? "\"viaLocL\":[{\"loc\":" + jsonLocation(via) + "}]," : "") // + "\"outDate\":\"" + outDate + "\"," // + "\"outTime\":\"" + outTime + "\"," // + "\"" + outFrwdKey + "\":" + outFrwd + "," // + "\"jnyFltrL\":[{\"value\":\"" + jnyFltr + "\",\"mode\":\"BIT\",\"type\":\"PROD\"}]," // + "\"gisFltrL\":[{\"mode\":\"FB\",\"profile\":{\"type\":\"F\",\"linDistRouting\":false,\"maxdist\":2000},\"type\":\"P\"}]," // + "\"getPolyline\":false,\"getPasslist\":true,\"getIST\":false,\"getEco\":false,\"extChgTime\":-1}", // false); final HttpUrl url = checkNotNull(mgateEndpoint); final CharSequence page = httpClient.get(url, request, "application/json"); try { final JSONObject head = new JSONObject(page.toString()); final String headErr = head.optString("err", null); if (headErr != null) throw new RuntimeException(headErr); final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, head.getString("ver"), null, 0, null); final JSONArray svcResList = head.getJSONArray("svcResL"); checkState(svcResList.length() == 1); final JSONObject svcRes = svcResList.optJSONObject(0); checkState("TripSearch".equals(svcRes.getString("meth"))); final String err = svcRes.getString("err"); if (!"OK".equals(err)) { final String errTxt = svcRes.getString("errTxt"); log.debug("Hafas error: {} {}", err, errTxt); if ("H890".equals(err)) // No connections found. return new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS); if ("H891".equals(err)) // No route found (try entering an intermediate station). return new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS); if ("H895".equals(err)) // Departure/Arrival are too near. return new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE); if ("H9220".equals(err)) // Nearby to the given address stations could not be found. return new QueryTripsResult(header, QueryTripsResult.Status.UNRESOLVABLE_ADDRESS); if ("H9240".equals(err)) // HAFAS Kernel: Internal error. return new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN); if ("H9360".equals(err)) // Date outside of the timetable period. return new QueryTripsResult(header, QueryTripsResult.Status.INVALID_DATE); if ("H9380".equals(err)) // Departure/Arrival/Intermediate or equivalent stations def'd more // than once. return new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE); if ("FAIL".equals(err) && "HCI Service: request failed".equals(errTxt)) return new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN); throw new RuntimeException(err + " " + errTxt); } final JSONObject res = svcRes.getJSONObject("res"); final JSONObject common = res.getJSONObject("common"); /* final List<String[]> remarks = */ parseRemList(common.getJSONArray("remL")); final List<Location> locations = parseLocList(common.getJSONArray("locL")); final List<String> operators = parseOpList(common.getJSONArray("opL")); final List<Line> lines = parseProdList(common.getJSONArray("prodL"), operators); final JSONArray outConList = res.optJSONArray("outConL"); final List<Trip> trips = new ArrayList<>(outConList.length()); for (int iOutCon = 0; iOutCon < outConList.length(); iOutCon++) { final JSONObject outCon = outConList.getJSONObject(iOutCon); final Location tripFrom = locations.get(outCon.getJSONObject("dep").getInt("locX")); final Location tripTo = locations.get(outCon.getJSONObject("arr").getInt("locX")); c.clear(); ParserUtils.parseIsoDate(c, outCon.getString("date")); final Date baseDate = c.getTime(); final JSONArray secList = outCon.optJSONArray("secL"); final List<Trip.Leg> legs = new ArrayList<>(secList.length()); for (int iSec = 0; iSec < secList.length(); iSec++) { final JSONObject sec = secList.getJSONObject(iSec); final String secType = sec.getString("type"); final JSONObject secDep = sec.getJSONObject("dep"); final Stop departureStop = parseJsonStop(secDep, locations, c, baseDate); final JSONObject secArr = sec.getJSONObject("arr"); final Stop arrivalStop = parseJsonStop(secArr, locations, c, baseDate); final Trip.Leg leg; if ("JNY".equals(secType)) { final JSONObject jny = sec.getJSONObject("jny"); final Line line = lines.get(jny.getInt("prodX")); final String dirTxt = jny.optString("dirTxt", null); final Location destination = dirTxt != null ? new Location(LocationType.ANY, null, null, dirTxt) : null; final JSONArray stopList = jny.getJSONArray("stopL"); checkState(stopList.length() >= 2); final List<Stop> intermediateStops = new ArrayList<>(stopList.length()); for (int iStop = 1; iStop < stopList.length() - 1; iStop++) { final JSONObject stop = stopList.getJSONObject(iStop); final Stop intermediateStop = parseJsonStop(stop, locations, c, baseDate); intermediateStops.add(intermediateStop); } leg = new Trip.Public(line, destination, departureStop, arrivalStop, intermediateStops, null, null); } else if ("WALK".equals(secType) || "TRSF".equals(secType)) { final JSONObject gis = sec.getJSONObject("gis"); final int distance = gis.optInt("dist", 0); leg = new Trip.Individual(Trip.Individual.Type.WALK, departureStop.location, departureStop.getDepartureTime(), arrivalStop.location, arrivalStop.getArrivalTime(), null, distance); } else { throw new IllegalStateException("cannot handle type: " + secType); } legs.add(leg); } final JSONObject trfRes = outCon.optJSONObject("trfRes"); final List<Fare> fares = new LinkedList<>(); if (trfRes != null) { final JSONArray fareSetList = trfRes.getJSONArray("fareSetL"); for (int iFareSet = 0; iFareSet < fareSetList.length(); iFareSet++) { final JSONObject fareSet = fareSetList.getJSONObject(iFareSet); final String fareSetName = fareSet.optString("name", null); final String fareSetDescription = fareSet.optString("desc", null); if (fareSetName != null || fareSetDescription != null) { final JSONArray fareList = fareSet.getJSONArray("fareL"); for (int iFare = 0; iFare < fareList.length(); iFare++) { final JSONObject jsonFare = fareList.getJSONObject(iFare); final String name = jsonFare.getString("name"); final JSONArray ticketList = jsonFare.optJSONArray("ticketL"); if (ticketList != null) { for (int iTicket = 0; iTicket < ticketList.length(); iTicket++) { final JSONObject jsonTicket = ticketList.getJSONObject(iTicket); final String ticketName = jsonTicket.getString("name"); final Currency currency = Currency.getInstance(jsonTicket.getString("cur")); final float price = jsonTicket.getInt("prc") / 100f; final Fare fare = parseJsonTripFare(name, fareSetDescription, ticketName, currency, price); if (fare != null) fares.add(fare); } } else { final Currency currency = Currency.getInstance(jsonFare.getString("cur")); final float price = jsonFare.getInt("prc") / 100f; final Fare fare = parseJsonTripFare(fareSetName, fareSetDescription, name, currency, price); if (fare != null) fares.add(fare); } } } } } final Trip trip = new Trip(null, tripFrom, tripTo, legs, fares, null, null); trips.add(trip); } final JsonContext context = new JsonContext(from, via, to, time, dep, products, res.optString("outCtxScrF"), res.optString("outCtxScrB")); return new QueryTripsResult(header, null, from, null, to, context, trips); } catch (final JSONException x) { throw new ParserException("cannot parse json: '" + page + "' on " + url, x); } }
From source file:fragment.web.RegistrationControllerTest.java
@Test public void testRegisterTrialForInvalidPromoCode() throws Exception { MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/signup?pc=testpromo"); UserRegistration registration = new UserRegistration(); registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null)); registration.setAcceptedTerms(true); AccountType disposition = accountTypeDAO.getTrialAccountType(); BindingResult result = setupRegistration(disposition, registration); PromotionSignup promotionSignup = new PromotionSignup("test" + random.nextInt(), "Citrix", "PromotionSignUp@citrix.com"); promotionSignup.setCreateBy(getRootUser()); promotionSignup.setCurrency(Currency.getInstance("USD")); promotionSignup.setPhone("9999999999"); CampaignPromotion campaignPromotion = new CampaignPromotion(); campaignPromotion.setCode("USD" + random.nextInt()); campaignPromotion.setCreateBy(getRootUser()); campaignPromotion.setTrial(true);/*w w w .jav a 2 s . c om*/ campaignPromotion.setUpdateBy(getRootUser()); campaignpromotiondao.save(campaignPromotion); PromotionToken promotionToken = new PromotionToken(campaignPromotion, "TESTPROMOCODE"); promotionToken.setCreateBy(getRootUser()); tokendao.save(promotionToken); promotionSignup.setPromotionToken(promotionToken); registration.setTrialCode("testpromo"); beforeRegisterCall(mockRequest, registration); String view = controller.register(registration, result, "abc", "abc", map, null, status, mockRequest); Assert.assertEquals("register.fail", view); Assert.assertFalse(status.isComplete()); }
From source file:org.apache.cordova.globalization.Globalization.java
private JSONObject getCurrencyPattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {/*from w ww. ja va2 s.c o m*/ //get ISO 4217 currency code String code = options.getJSONObject(0).getString(CURRENCYCODE); //uses java.text.DecimalFormat to format value DecimalFormat fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); //set currency format Currency currency = Currency.getInstance(code); fmt.setCurrency(currency); //return properties obj.put("pattern", fmt.toPattern()); obj.put("code", currency.getCurrencyCode()); obj.put("fraction", fmt.getMinimumFractionDigits()); obj.put("rounding", Integer.valueOf(0)); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); } }
From source file:ch.silviowangler.dox.DocumentServiceImpl.java
@SuppressWarnings("unchecked") private Object makeAssignable(AttributeDataType desiredDataType, Object valueToConvert) { if (valueToConvert instanceof ch.silviowangler.dox.api.Range && isRangeCompatible(desiredDataType)) { logger.debug("Found a range parameter. Skip this one"); if (DATE.equals(desiredDataType)) { ch.silviowangler.dox.api.Range<DateTime> original = (ch.silviowangler.dox.api.Range<DateTime>) valueToConvert; return new Range<>(original.getFrom(), original.getTo()); } else if (DOUBLE.equals(desiredDataType)) { ch.silviowangler.dox.api.Range<BigDecimal> original = (ch.silviowangler.dox.api.Range<BigDecimal>) valueToConvert; return new Range<>(original.getFrom(), original.getTo()); } else if (INTEGER.equals(desiredDataType)) { ch.silviowangler.dox.api.Range<Integer> original = (ch.silviowangler.dox.api.Range<Integer>) valueToConvert; return new Range<>(original.getFrom(), original.getTo()); } else if (LONG.equals(desiredDataType)) { ch.silviowangler.dox.api.Range<Long> original = (ch.silviowangler.dox.api.Range<Long>) valueToConvert; return new Range<>(original.getFrom(), original.getTo()); } else if (SHORT.equals(desiredDataType)) { ch.silviowangler.dox.api.Range<Short> original = (ch.silviowangler.dox.api.Range<Short>) valueToConvert; return new Range<>(original.getFrom(), original.getTo()); }// ww w . j a v a 2 s . co m throw new IllegalArgumentException(); } if (DATE.equals(desiredDataType) && valueToConvert instanceof String) { final String stringValueToConvert = (String) valueToConvert; String regexPattern; if (stringValueToConvert.matches("\\d{4}-\\d{2}-\\d{2}")) { regexPattern = YYYY_MM_DD; } else if (stringValueToConvert.matches("\\d{2}\\.\\d{2}\\.\\d{4}")) { regexPattern = DD_MM_YYYY; } else { logger.error("Unsupported format of a date string '{}'", stringValueToConvert); throw new UnsupportedOperationException("Unknown date format " + stringValueToConvert); } return DateTimeFormat.forPattern(regexPattern).parseDateTime(stringValueToConvert); } else if (DATE.equals(desiredDataType) && valueToConvert instanceof Date) { return new DateTime(valueToConvert); } else if (DOUBLE.equals(desiredDataType) && valueToConvert instanceof Double) { return BigDecimal.valueOf((Double) valueToConvert); } else if (DOUBLE.equals(desiredDataType) && valueToConvert instanceof String && ((String) valueToConvert).matches("(\\d.*|\\d.*\\.\\d{1,2})")) { return new BigDecimal((String) valueToConvert); } else if (DOUBLE.equals(desiredDataType) && valueToConvert instanceof Integer) { return BigDecimal.valueOf(Long.parseLong(String.valueOf(valueToConvert))); } else if (DOUBLE.equals(desiredDataType) && valueToConvert instanceof Long) { return BigDecimal.valueOf((Long) valueToConvert); } else if (CURRENCY.equals(desiredDataType) && valueToConvert instanceof String) { String value = (String) valueToConvert; return new AmountOfMoney(value); } else if (CURRENCY.equals(desiredDataType) && valueToConvert instanceof Money) { Money money = (Money) valueToConvert; return new AmountOfMoney(money.getCurrency(), money.getAmount()); } else if (CURRENCY.equals(desiredDataType) && valueToConvert instanceof Map) { Map money = (Map) valueToConvert; return new AmountOfMoney(Currency.getInstance((String) money.get("currency")), new BigDecimal((String) money.get("amount"))); } logger.error("Unable to convert data type '{}' and value '{}' (class: '{}')", new Object[] { desiredDataType, valueToConvert, valueToConvert.getClass().getCanonicalName() }); throw new IllegalArgumentException("Unable to convert data type '" + desiredDataType + "' and value '" + valueToConvert + "' (Target class: '" + valueToConvert.getClass().getCanonicalName() + "')"); }
From source file:ch.silviowangler.dox.DocumentServiceIntegrationTest.java
@Test public void importPdfWithEncryption() throws DocumentClassNotFoundException, DocumentDuplicationException, ValidationException, IOException { File singlePagePdf = loadFile("Zinsausweis2013-CS-680419-20.pdf"); Map<TranslatableKey, DescriptiveIndex> indexes = newHashMapWithExpectedSize(1); indexes.put(COMPANY, new DescriptiveIndex("Sunrise")); indexes.put(MONEY, new DescriptiveIndex(new Money(Currency.getInstance("CHF"), new BigDecimal("1235.50")))); indexes.put(INVOICE_AMOUNT, new DescriptiveIndex(12350L)); indexes.put(INVOICE_DATE, new DescriptiveIndex(new Date())); PhysicalDocument doc = new PhysicalDocument(documentClass, readFileToByteArray(singlePagePdf), indexes, singlePagePdf.getName());/*from w w w. ja v a 2s . co m*/ doc.setClient(CLIENT_WANGLER); final DocumentReference documentReference = documentService.importDocument(doc); assertThat(documentReference.getPageCount(), is(1)); final Money money = (Money) documentReference.getIndices().get(MONEY).getValue(); assertThat(money, is(not(nullValue()))); assertThat(money.getCurrency().getCurrencyCode(), is("CHF")); assertThat(money.getAmount().toPlainString(), is("1235.50")); }
From source file:de.javakaffee.kryoserializers.KryoTest.java
@DataProvider(name = "typesAsSessionAttributesProvider") protected Object[][] createTypesAsSessionAttributesData() { return new Object[][] { { Boolean.class, Boolean.TRUE }, { String.class, "42" }, { StringBuilder.class, new StringBuilder("42") }, { StringBuffer.class, new StringBuffer("42") }, { Class.class, String.class }, { Long.class, new Long(42) }, { Integer.class, new Integer(42) }, { Character.class, new Character('c') }, { Byte.class, new Byte("b".getBytes()[0]) }, { Double.class, new Double(42d) }, { Float.class, new Float(42f) }, { Short.class, new Short((short) 42) }, { BigDecimal.class, new BigDecimal(42) }, { AtomicInteger.class, new AtomicInteger(42) }, { AtomicLong.class, new AtomicLong(42) }, { MutableInt.class, new MutableInt(42) }, { Integer[].class, new Integer[] { 42 } }, { Date.class, new Date(System.currentTimeMillis() - 10000) }, { Calendar.class, Calendar.getInstance() }, { Currency.class, Currency.getInstance("EUR") }, { ArrayList.class, new ArrayList<String>(Arrays.asList("foo")) }, { int[].class, new int[] { 1, 2 } }, { long[].class, new long[] { 1, 2 } }, { short[].class, new short[] { 1, 2 } }, { float[].class, new float[] { 1, 2 } }, { double[].class, new double[] { 1, 2 } }, { int[].class, new int[] { 1, 2 } }, { byte[].class, "42".getBytes() }, { char[].class, "42".toCharArray() }, { String[].class, new String[] { "23", "42" } }, { Person[].class, new Person[] { createPerson("foo bar", Gender.MALE, 42) } } }; }