Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

In this page you can find the example usage for java.math BigDecimal valueOf.

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:com.seyren.core.service.notification.BigPandaNotificationServiceTest.java

@Test
public void checkingOutTheHappyPath() {

    String seyrenUrl = clientDriver.getBaseUrl() + "/seyren";

    when(mockSeyrenConfig.getGraphiteUrl()).thenReturn(clientDriver.getBaseUrl() + "/graphite");
    when(mockSeyrenConfig.getBaseUrl()).thenReturn(seyrenUrl);
    when(mockSeyrenConfig.getBigPandaNotificationUrl())
            .thenReturn(clientDriver.getBaseUrl() + "/bigpanda/test");
    when(mockSeyrenConfig.getBigPandaAuthBearer()).thenReturn("test-auth-bearer");

    Check check = new Check().withEnabled(true).withName("check-name").withDescription("Testing Description")
            .withTarget("the.target.name").withState(AlertType.ERROR).withWarn(BigDecimal.ONE)
            .withError(BigDecimal.TEN).withId("testing");

    Subscription subscription = new Subscription().withType(SubscriptionType.BIGPANDA)
            .withTarget("testing_app_key");

    DateTime timestamp = new DateTime(1420070400000L);

    Alert alert = new Alert().withTarget("the.target.name").withValue(BigDecimal.valueOf(12))
            .withWarn(BigDecimal.valueOf(5)).withError(BigDecimal.valueOf(10)).withFromType(AlertType.WARN)
            .withToType(AlertType.ERROR).withTimestamp(timestamp);

    List<Alert> alerts = Arrays.asList(alert);

    BodyCapture<JsonNode> bodyCapture = new JsonBodyCapture();

    clientDriver.addExpectation(// w ww.  j a  va  2s.co m
            onRequestTo("/bigpanda/test").withMethod(Method.POST).capturingBodyIn(bodyCapture),
            giveResponse("success", "text/plain"));

    service.sendNotification(check, subscription, alerts);

    JsonNode node = bodyCapture.getContent();

    assertThat(node, hasJsonPath("$.seyrenCheckUrl", is(seyrenUrl + "/#/checks/" + check.getId())));
    assertThat(node, hasJsonPath("$.app_key", is("testing_app_key")));
    assertThat(node, hasJsonPath("$.check", is("the.target.name")));
    assertThat(node, hasJsonPath("$.status", is("critical")));
    assertThat(node, hasJsonPath("$.service", is("check-name")));
    assertThat(node, hasJsonPath("$.description", is("Testing Description")));
    assertThat(node, hasJsonPath("$.timestamp", is(1420070400L)));
    assertThat(node, hasJsonPath("$.currentValue", is(12)));
    assertThat(node, hasJsonPath("$.thresholdWarning", is(5)));
    assertThat(node, hasJsonPath("$.thresholdCritical", is(10)));
    assertThat(node, hasJsonPath("$.previewGraph", containsString("the.target.name")));
    assertThat(node, hasJsonPath("$.previewGraph", containsString("/graphite")));

}

From source file:com.opensymphony.xwork2.conversion.impl.NumberConverterTest.java

public void testStringToBigDecimalConversionWithDotsPL() throws Exception {
    // given//from www .  j av a 2s. co  m
    NumberConverter converter = new NumberConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("pl", "PL"));

    // when
    Object value = converter.convertValue(context, null, null, null, "1 234,4", BigDecimal.class);

    // then
    assertEquals(BigDecimal.valueOf(1234.4), value);
}

From source file:com.nortal.petit.orm.statement.InsertStatementInterceptorTest.java

private void prepareResultsetReturningMultipleKeys() {
    MockConnection connection = getJDBCMockObjectFactory().getMockConnection();
    PreparedStatementResultSetHandler statementHandler = connection.getPreparedStatementResultSetHandler();
    MockResultSet keysResult = statementHandler.createResultSet();
    keysResult.addColumn("id");
    keysResult.addRow(new Object[] { BigDecimal.valueOf(11L) });
    keysResult.addRow(new Object[] { BigDecimal.valueOf(12L) });
    keysResult.addRow(new Object[] { BigDecimal.valueOf(13L) });

    statementHandler.prepareGeneratedKeys("insert", keysResult);
}

From source file:com.stratio.cassandra.index.schema.ColumnMapperBigDecimal.java

/**
 * Builds a new {@link ColumnMapperBigDecimal} using the specified max number of digits for the integer and decimal
 * parts.//from ww  w .j av a 2s . c  om
 *
 * @param integerDigits The max number of digits for the integer part. If {@code null}, the {@link
 *                      #DEFAULT_INTEGER_DIGITS} will be used.
 * @param decimalDigits The max number of digits for the decimal part. If {@code null}, the {@link
 *                      #DEFAULT_DECIMAL_DIGITS} will be used.
 */
@JsonCreator
public ColumnMapperBigDecimal(@JsonProperty("integer_digits") Integer integerDigits,
        @JsonProperty("decimal_digits") Integer decimalDigits) {
    super(new AbstractType<?>[] { AsciiType.instance, UTF8Type.instance, Int32Type.instance, LongType.instance,
            IntegerType.instance, FloatType.instance, DoubleType.instance, DecimalType.instance },
            new AbstractType[] {});

    // Setup integer part mapping
    if (integerDigits != null && integerDigits <= 0) {
        throw new IllegalArgumentException("Positive integer part digits required");
    }
    this.integerDigits = integerDigits == null ? DEFAULT_INTEGER_DIGITS : integerDigits;

    // Setup decimal part mapping
    if (decimalDigits != null && decimalDigits <= 0) {
        throw new IllegalArgumentException("Positive decimal part digits required");
    }
    this.decimalDigits = decimalDigits == null ? DEFAULT_DECIMAL_DIGITS : decimalDigits;

    int totalDigits = this.integerDigits + this.decimalDigits;
    BigDecimal divisor = BigDecimal.valueOf(10).pow(this.decimalDigits);
    BigDecimal dividend = BigDecimal.valueOf(10).pow(totalDigits).subtract(BigDecimal.valueOf(1));
    complement = dividend.divide(divisor);
}

From source file:net.sourceforge.fenixedu.domain.Guide.java

public void updateTotalValue() {

    BigDecimal total = BigDecimal.ZERO;

    for (final GuideEntry guideEntry : getGuideEntriesSet()) {
        total = total//from   w w w .  ja v  a2  s.com
                .add(guideEntry.getPriceBigDecimal().multiply(BigDecimal.valueOf(guideEntry.getQuantity())));
    }

    total.setScale(2, RoundingMode.HALF_EVEN);

    setTotalBigDecimal(total);

}

From source file:es.tid.fiware.rss.service.RSSModelsManagerTest.java

/**
 * /* w  w  w .j a v  a 2  s  .c  o  m*/
 */
@Test
public void convertIntoApiModelTest() {
    logger.debug("convertIntoApiModelTest");
    SetRevenueShareConf model = new SetRevenueShareConf();
    SetRevenueShareConfId id = new SetRevenueShareConfId();
    model.setId(id);
    id.setProductClass("productClass");
    id.setTxAppProviderId("txAppProviderId");
    model.setNuPercRevenueShare(BigDecimal.valueOf(30));
    RSSModel finalModel = rssModelsManager.convertIntoApiModel(model);
    Assert.assertEquals(id.getProductClass(), finalModel.getProductClass());
    Assert.assertEquals(id.getTxAppProviderId(), finalModel.getAppProviderId());
    Assert.assertTrue(model.getNuPercRevenueShare().compareTo(finalModel.getPercRevenueShare()) == 0);
}

From source file:es.tid.fiware.rss.ws.RSSModelServiceTest.java

/**
 * /*from  www.j  a  v  a2s . c o m*/
 */
@PostConstruct
public void init() throws Exception {
    ValidatedToken validToken = new ValidatedToken();
    validToken.setEmail("mail@mail.com");
    oauth = Mockito.mock(OauthManager.class);
    Mockito.when(oauth.checkAuthenticationToken("authToken")).thenReturn(validToken);
    ReflectionTestUtils.setField(rssModelService, "oauthManager", oauth);
    // /
    /*
     * UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
     * Mockito.when(mockUriInfo.getBaseUri()).thenReturn(new URI("http://www.test.com/go"));
     * ReflectionTestUtils.setField(rssModelService, "ui", mockUriInfo);
     */
    //
    rssModelsManager = Mockito.mock(RSSModelsManager.class);
    ReflectionTestUtils.setField(rssModelService, "rssModelsManager", rssModelsManager);
    //
    rssModel = new RSSModel();
    rssModel.setAppProviderId("appProviderId");
    rssModel.setProductClass("productClass");
    rssModel.setPercRevenueShare(BigDecimal.valueOf(30));
}

From source file:com.trenako.entities.Money.java

/**
 * Returns the value part of the provided {@code Money}.
 *
 * @return the value//from  w w  w.  ja  va  2 s.  c om
 */
public static BigDecimal moneyValue(Money money) {
    int val = (money != null) ? money.getValue() : 0;
    return BigDecimal.valueOf(val).divide(Money.MONEY_VALUE_FACTOR);
}

From source file:com.smartystreets.spring.SmartyStreetsAPIDataTransformTest.java

@Test
public void canTransformAddressResponse() throws IOException {

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("address_response.json").getFile());

    ObjectMapper om = new ObjectMapper();
    AddressResponse addressResponse = om.readValue(file, AddressResponse[].class)[0];

    assertEquals(0, addressResponse.getInputIndex());
    assertEquals(0, addressResponse.getCandidateIndex());
    assertEquals("13936 Flay Ave N", addressResponse.getDeliveryLine1());
    assertEquals("Hugo MN 55038-6401", addressResponse.getLastLine());
    assertEquals("550386401369", addressResponse.getDeliveryPointBarcode());

    Components components = addressResponse.getComponents();
    assertEquals("13936", components.getPrimaryNumber());
    assertEquals("Flay", components.getStreetName());
    assertEquals("N", components.getStreetPostdirection());
    assertEquals("Ave", components.getStreetSuffix());
    assertEquals("Hugo", components.getCityName());
    assertEquals("MN", components.getStateAbbreviation());
    assertEquals("55038", components.getZipcode());
    assertEquals("6401", components.getPlus4Code());
    assertEquals("36", components.getDeliveryPoint());
    assertEquals("9", components.getDeliveryPointCheckDigit());

    Metadata metadata = addressResponse.getMetadata();
    assertEquals(RecordType.S, metadata.getRecordType());
    assertEquals(ZipType.Standard, metadata.getZipType());
    assertEquals("27163", metadata.getCountyFips());
    assertEquals("Washington", metadata.getCountyName());
    assertEquals("R009", metadata.getCarrierRoute());
    assertEquals("06", metadata.getCongressionalDistrict());
    assertEquals(ResidentialDeliveryIndicator.Residential, metadata.getRdi());
    assertEquals("0238", metadata.getElotSequence());
    assertEquals(ElotSortType.A, metadata.getElotSort());
    assertEquals(BigDecimal.valueOf(45.15118D), metadata.getLocation().getLatitude());
    assertEquals(BigDecimal.valueOf(-92.99295D), metadata.getLocation().getLongitude());
    assertEquals("Zip9", metadata.getLocation().getPrecision());
    assertEquals("Central", metadata.getTimeInfo().getTimeZone());
    assertEquals(BigDecimal.valueOf(-6), metadata.getTimeInfo().getUtcOffset());
    assertEquals(true, metadata.getTimeInfo().isDst());

    Analysis analysis = addressResponse.getAnalysis();
    assertEquals(DeliveryPointValidationType.Y, analysis.getDeliveryPointValidationType());
    assertEquals("AABB", analysis.getDpvFootnotes());
    assertEquals("N", analysis.getDpvCmra());
    assertEquals("N", analysis.getDpvVacant());
    assertEquals("Y", analysis.getActive());
    assertEquals("N#", analysis.getFootnotes());
}

From source file:net.eusashead.hateoas.hal.response.impl.HalResponseBuilderITCase.java

@Test
public void testGet() throws Exception {
    // Execute controller method
    MvcResult result = this.mockMvc
            .perform(get("http://localhost/order/123").contentType(HalHttpMessageConverter.HAL_JSON)
                    .accept(HalHttpMessageConverter.HAL_JSON))
            .andExpect(status().isOk()).andExpect(header().string("ETag", "W/\"123456789\""))
            .andExpect(//from w  w w  .j  a va2 s  .co  m
                    content().contentType(new MediaType("application", "hal+json", Charset.forName("UTF-8"))))
            .andReturn();

    // Check result
    ReadableRepresentation returned = new StandardRepresentationFactory()
            .readRepresentation(new StringReader(result.getResponse().getContentAsString()));
    Assert.assertNotNull(returned);
    Link linkByRel = returned.getLinkByRel("self");
    Assert.assertNotNull(linkByRel);
    Assert.assertEquals("/order/123", linkByRel.getHref());
    Object total = returned.getValue("total");
    Assert.assertEquals(BigDecimal.valueOf(12.34d).toString(), total);
}