Example usage for java.math BigDecimal BigDecimal

List of usage examples for java.math BigDecimal BigDecimal

Introduction

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

Prototype

public BigDecimal(long val) 

Source Link

Document

Translates a long into a BigDecimal .

Usage

From source file:TaxReturn.java

public static void main(String[] pArgs) throws Exception {
    TaxReturn return1 = new TaxReturn("012-68-3242", 1998, "O'Brien", new BigDecimal(43000.00));
    TaxReturn return2 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(45000.00));
    TaxReturn return3 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(53222.00));

    System.out.println("return1 equals return2: " + return1.equals(return2));
    System.out.println("return2 equals return3: " + return2.equals(return3));

}

From source file:TaxReturn.java

public static void main(String[] pArgs) throws Exception {
    TaxReturn return1 = new TaxReturn("012-68-3242", 1998, "O'Brien", new BigDecimal(43000.00));
    TaxReturn return2 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(45000.00));
    TaxReturn return3 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(53222.00));

    System.out.println("HashCodeBuilder: " + return2.hashCode());
    Set set = new HashSet();
    set.add(return1);
    set.add(return2);
    set.add(return3);
    System.out.println(set);/*w ww  .j av  a2s. c  om*/
}

From source file:TaxReturn.java

public static void main(String[] pArgs) throws Exception {
    TaxReturn return1 = new TaxReturn("012-68-3242", 1998, "O'Brien", new BigDecimal(43000.00));
    TaxReturn return2 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(45000.00));
    TaxReturn return3 = new TaxReturn("012-68-3242", 1999, "O'Brien", new BigDecimal(53222.00));
    System.out.println("ToStringBuilder: " + return1.toString());
}

From source file:ObjectStreams.java

public static void main(String[] args) throws IOException, ClassNotFoundException {

    ObjectOutputStream out = null;
    try {/*from w  ww  .jav  a 2  s .  co  m*/
        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

        out.writeObject(Calendar.getInstance());
        for (int i = 0; i < prices.length; i++) {
            out.writeObject(prices[i]);
            out.writeInt(units[i]);
            out.writeUTF(descs[i]);
        }
    } finally {
        out.close();
    }

    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

        Calendar date = null;
        BigDecimal price;
        int unit;
        String desc;
        BigDecimal total = new BigDecimal(0);

        date = (Calendar) in.readObject();

        System.out.format("On %tA, %<tB %<te, %<tY:%n", date);

        try {
            while (true) {
                price = (BigDecimal) in.readObject();
                unit = in.readInt();
                desc = in.readUTF();
                System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price);
                total = total.add(price.multiply(new BigDecimal(unit)));
            }
        } catch (EOFException e) {
        }
        System.out.format("For a TOTAL of: $%.2f%n", total);
    } finally {
        in.close();
    }
}

From source file:net.sourceforge.happybank.facade.BankTest.java

/**
 * Test method./*from   w ww .  j  a  v a  2 s  .co  m*/
 * 
 * @param args command line arguments
 */
public static void main(final String[] args) {

    try {
        // get context and facade
        ApplicationContext ctx = new FileSystemXmlApplicationContext("build/applicationContext.xml");
        BankingFacade bank = (BankingFacade) ctx.getBean("bankManager");

        // get all customers
        List<Customer> customers = bank.getCustomers();
        Iterator<Customer> custIter = customers.iterator();
        Customer cust = null;
        while (custIter.hasNext()) {
            cust = custIter.next();
            String cid = cust.getId();
            Customer customer = bank.getCustomer(cid);
            System.out.println(customer.toString());

            // get customers accounts
            List<Account> accounts = bank.getAccounts(cid);
            Iterator<Account> accIter = accounts.iterator();
            Account acc = null;
            while (accIter.hasNext()) {
                acc = accIter.next();
                String aid = acc.getId();
                Account account = bank.getAccount(aid);
                System.out.println("\t> " + account.toString());

                // get account transactions
                List<TransRecord> transactions = bank.getTransactions(aid);
                Iterator<TransRecord> transIter = transactions.iterator();
                TransRecord tr = null;
                while (transIter.hasNext()) {
                    tr = transIter.next();
                    System.out.println("\t\t>" + tr.toString());
                }
            }
        }

        // test creation, deletion and withdrawal
        bank.addCustomer("999", "Mr", "First", "Last");
        bank.addAccount("999-99", "999", "Checking");
        bank.deposit("999-99", new BigDecimal(1000.0));
        bank.withdraw("999-99", new BigDecimal(500.0));
        bank.deleteAccount("999-99");
        bank.deleteCustomer("999");

    } catch (BankException ex) {
        ex.printStackTrace();
    }
}

From source file:model.experiments.stickyprices.StickyPricesCSVPrinter.java

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
    //set defaults
    //create directory
    Files.createDirectories(Paths.get("runs", "rawdata"));

    System.out.println("SELLERS");
    System.out.println("figure 1 to 5");
    simpleSellerRuns();/*from  w ww  . ja va 2 s  .  c  o m*/
    System.out.println("figure 6-7");
    simpleDelaySweep(50, 50, 50, 5);

    System.out.println("ONE SECTOR");
    System.out.println("figure 8");
    sampleMonopolistRunLearned(0, 101, 1, 1, 14, .1f, .1f, "sampleMonopolist.csv");
    System.out.println("figure 9");

    sampleCompetitiveRunLearned(0, 101, 1, 1, 14, .1f, .1f, "sampleCompetitive.csv");

    System.out.println("figure 10");

    woodMonopolistSweep(new BigDecimal("0.00"), new BigDecimal("3"), new BigDecimal("0.00"),
            new BigDecimal("3"), new BigDecimal(".01"), 1);

    System.out.println("SUPPLY CHAIN");
    System.out.println("figure 11");
    badlyOptimizedNoInventorySupplyChain(0, 0f, 2f, 0,
            Paths.get("runs", "rawdata", "badlyOptimized.csv").toFile(), false);
    System.out.println("figure 12");
    badlyOptimizedNoInventorySupplyChain(0, 0f, .2f, 0,
            Paths.get("runs", "rawdata", "timidBadlyOptimized.csv").toFile(), false);
    System.out.println("figure 13");
    badlyOptimizedNoInventorySupplyChain(0, 0f, .2f, 100,
            Paths.get("runs", "rawdata", "stickyBadlyOptimized.csv").toFile(), false);

    System.out.println("figure 14");
    woodMonopolistSupplyChainSweep();

    System.out.println("Market Structure");
    System.out.println("figure 15-16-17");

    oneHundredAllLearnedRuns(Paths.get("runs", "rawdata", "learnedInventoryChain100.csv").toFile(), null, null);
    oneHundredAllLearnedCompetitiveRuns(
            Paths.get("runs", "rawdata", "learnedCompetitiveInventoryChain100.csv").toFile());
    oneHundredAllLearnedFoodRuns(Paths.get("runs", "rawdata", "learnedInventoryFoodChain100.csv").toFile());

    System.out.println("figure 18-19");
    oneHundredLearningMonopolist(Paths.get("runs", "rawdata", "100Monopolists.csv").toFile());
    oneHundredLearningCompetitive(Paths.get("runs", "rawdata", "100Competitive.csv").toFile());

    System.out.println("figure 20-21-22");
    oneHundredAllLearningRuns(Paths.get("runs", "rawdata", "learningInventoryChain100.csv").toFile(), null,
            null);
    oneHundredAllLearningCompetitiveRuns(
            Paths.get("runs", "rawdata", "learningCompetitiveInventoryChain100.csv").toFile());
    oneHundredAllLearningFoodRuns(Paths.get("runs", "rawdata", "learningInventoryFoodChain100.csv").toFile());

    System.out.println("figure 23");
    badlyOptimizedNoInventorySupplyChain(1, 0f, 0.2f, 0,
            Paths.get("runs", "rawdata", "tuningTrial.csv").toFile(), true);

}

From source file:examples.KafkaStreamsDemo.java

public static void main(String[] args) throws InterruptedException, SQLException {
    /**// w ww . ja va2s .co  m
     * The example assumes the following SQL schema
     *
     *    DROP DATABASE IF EXISTS beer_sample_sql;
     *    CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci;
     *    USE beer_sample_sql;
     *
     *    CREATE TABLE breweries (
     *       id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       description TEXT,
     *       country VARCHAR(256),
     *       city VARCHAR(256),
     *       state VARCHAR(256),
     *       phone VARCHAR(40),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     *
     *
     *    CREATE TABLE beers (
     *       id VARCHAR(256) NOT NULL,
     *       brewery_id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       category VARCHAR(256),
     *       style VARCHAR(256),
     *       description TEXT,
     *       abv DECIMAL(10,2),
     *       ibu DECIMAL(10,2),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     */
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.err.println("Failed to load MySQL JDBC driver");
    }
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root",
            "secret");
    final PreparedStatement insertBrewery = connection.prepareStatement(
            "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " name=VALUES(name), description=VALUES(description), country=VALUES(country),"
                    + " country=VALUES(country), city=VALUES(city), state=VALUES(state),"
                    + " phone=VALUES(phone), updated_at=VALUES(updated_at)");
    final PreparedStatement insertBeer = connection.prepareStatement(
            "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description),"
                    + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv),"
                    + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)");

    String schemaRegistryUrl = "http://localhost:8081";

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class);

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample");

    KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() {
        @Override
        public JsonNode apply(GenericRecord value) {
            ByteBuffer buf = (ByteBuffer) value.get("content");
            try {
                JsonNode doc = MAPPER.readTree(buf.array());
                return doc;
            } catch (IOException e) {
                return null;
            }
        }
    }).branch(new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name")
                    && value.has("description") && value.has("category") && value.has("style")
                    && value.has("abv") && value.has("ibu") && value.has("updated");
        }
    }, new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description")
                    && value.has("country") && value.has("city") && value.has("state") && value.has("phone")
                    && value.has("updated");
        }
    });
    documents[0].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBeer.setString(1, key);
                insertBeer.setString(2, value.get("brewery_id").asText());
                insertBeer.setString(3, value.get("name").asText());
                insertBeer.setString(4, value.get("description").asText());
                insertBeer.setString(5, value.get("category").asText());
                insertBeer.setString(6, value.get("style").asText());
                insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText()));
                insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText()));
                insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBeer.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });
    documents[1].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBrewery.setString(1, key);
                insertBrewery.setString(2, value.get("name").asText());
                insertBrewery.setString(3, value.get("description").asText());
                insertBrewery.setString(4, value.get("country").asText());
                insertBrewery.setString(5, value.get("city").asText());
                insertBrewery.setString(6, value.get("state").asText());
                insertBrewery.setString(7, value.get("phone").asText());
                insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBrewery.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });

    final KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            streams.close();
        }
    }));
}

From source file:com.test.demo.ccbpay.XLSX2CSV.java

public static void main(String[] args) throws Exception {
    File f = new File(
            "C:\\Users\\dmall\\Desktop\\???\\1493142812All2018-05-15_2018-05-20.csv");
    InputStreamReader reader = new InputStreamReader(new FileInputStream(f), "GBK");
    CSVReader csvReader = new CSVReader(reader);
    String[] csvRow = null; // row
    long csvDataSize = 0;
    long pay0515 = 0L;
    long re0515 = 0L;
    long cost0515 = 0L;
    while ((csvRow = csvReader.readNext()) != null) {
        if (csvRow.length != 24) {
            continue;
        }/*  ww w.  j  a  v  a 2 s .co m*/

        csvDataSize += 1;
        if (csvDataSize > 1) {
            if (csvRow[0].contains("2018-05-17")) {
                pay0515 += BigDecimal.valueOf(Double.valueOf(csvRow[12].substring(1, csvRow[12].length())))
                        .multiply(new BigDecimal(100)).longValue();
                re0515 += BigDecimal.valueOf(Double.valueOf(csvRow[16].substring(1, csvRow[16].length())))
                        .multiply(new BigDecimal(100)).longValue();
                cost0515 += BigDecimal.valueOf(Double.valueOf(csvRow[22].substring(1, csvRow[22].length())))
                        .multiply(new BigDecimal(100)).longValue();
            }
        }

    }

    System.out.println(pay0515);
    System.out.println(re0515);
    System.out.println(cost0515);
    System.out.println(pay0515 - re0515 - cost0515);
}

From source file:com.labs64.netlicensing.demo.NetLicensingClientDemo.java

public static void main(final String[] args) {

    // configure J.U.L. to Slf4j bridge for Jersey
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();/*from  w w w.j  a  va  2  s . c o m*/

    final Context context = new Context();
    context.setBaseUrl("https://go.netlicensing.io/core/v2/rest");
    context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
    context.setUsername("demo");
    context.setPassword("demo");

    final String randomNumber = RandomStringUtils.randomAlphanumeric(8);
    final String productNumber = numberWithPrefix("P", randomNumber);
    final String productModuleNumber = numberWithPrefix("PM", randomNumber);
    final String licenseTemplateNumber = numberWithPrefix("LT", randomNumber);
    final String licenseeNumber = numberWithPrefix("L", randomNumber);
    final String licenseNumber = numberWithPrefix("LC", randomNumber);
    final String licenseeName = numberWithPrefix("Licensee ", RandomStringUtils.randomAlphanumeric(8));

    final ConsoleWriter out = new ConsoleWriter();

    int exitCode = CODE_OK;
    try {

        // region ********* Lists

        final Page<String> licenseTypes = UtilityService.listLicenseTypes(context);
        out.writePage("License Types:", licenseTypes);

        final Page<String> licensingModels = UtilityService.listLicensingModels(context);
        out.writePage("Licensing Models:", licensingModels);

        final Page<Country> countries = UtilityService.listCountries(context, null);
        out.writePage("Countries:", countries);

        // endregion

        // region ********* Product

        final Product newProduct = new ProductImpl();
        newProduct.setNumber(productNumber);
        newProduct.setName("Demo product");
        Product product = ProductService.create(context, newProduct);
        out.writeObject("Added product:", product);

        product = ProductService.get(context, productNumber);
        out.writeObject("Got product:", product);

        Page<Product> products = ProductService.list(context, null);
        out.writePage("Got the following products:", products);

        final Product updateProduct = new ProductImpl();
        updateProduct.addProperty("Updated property name", "Updated value");
        updateProduct.addProperty(Constants.Product.PROP_LICENSEE_SECRET_MODE,
                LicenseeSecretMode.PREDEFINED.toString());
        product = ProductService.update(context, productNumber, updateProduct);
        out.writeObject("Updated product:", product);

        ProductService.delete(context, productNumber, true);
        out.writeMessage("Deleted Product!");

        products = ProductService.list(context, null);
        out.writePage("Got the following Products:", products);

        product = ProductService.create(context, newProduct);
        out.writeObject("Added product again:", product);

        products = ProductService.list(context, null);
        out.writePage("Got the following Products:", products);

        // endregion

        // region ********* ProductModule

        final ProductModule newProductModule = new ProductModuleImpl();
        newProductModule.setNumber(productModuleNumber);
        newProductModule.setName("Demo product module");
        newProductModule.setLicensingModel(Constants.LicensingModel.TryAndBuy.NAME);
        ProductModule productModule = ProductModuleService.create(context, productNumber, newProductModule);
        out.writeObject("Added product module:", productModule);

        productModule = ProductModuleService.get(context, productModuleNumber);
        out.writeObject("Got product module:", productModule);

        Page<ProductModule> productModules = ProductModuleService.list(context, null);
        out.writePage("Got the following product modules:", productModules);

        final ProductModule updateProductModule = new ProductModuleImpl();
        updateProductModule.addProperty("Updated property name", "Updated property value");
        productModule = ProductModuleService.update(context, productModuleNumber, updateProductModule);
        out.writeObject("Updated product module:", productModule);

        ProductModuleService.delete(context, productModuleNumber, true);
        out.writeMessage("Deleted product module!");

        productModules = ProductModuleService.list(context, null);
        out.writePage("Got the following product modules:", productModules);

        productModule = ProductModuleService.create(context, productNumber, newProductModule);
        out.writeObject("Added product module again:", productModule);

        productModules = ProductModuleService.list(context, null);
        out.writePage("Got the following product modules:", productModules);

        // endregion

        // region ********* LicenseTemplate

        final LicenseTemplate newLicenseTemplate = new LicenseTemplateImpl();
        newLicenseTemplate.setNumber(licenseTemplateNumber);
        newLicenseTemplate.setName("Demo Evaluation Period");
        newLicenseTemplate.setLicenseType(LicenseType.FEATURE);
        newLicenseTemplate.setPrice(new BigDecimal(12.5));
        newLicenseTemplate.setCurrency(Currency.EUR);
        newLicenseTemplate.setAutomatic(false);
        newLicenseTemplate.setHidden(false);
        out.writeObject("Adding license template:", newLicenseTemplate);
        LicenseTemplate licenseTemplate = LicenseTemplateService.create(context, productModuleNumber,
                newLicenseTemplate);
        out.writeObject("Added license template:", licenseTemplate);

        licenseTemplate = LicenseTemplateService.get(context, licenseTemplateNumber);
        out.writeObject("Got licenseTemplate:", licenseTemplate);

        Page<LicenseTemplate> licenseTemplates = LicenseTemplateService.list(context, null);
        out.writePage("Got the following license templates:", licenseTemplates);

        final LicenseTemplate updateLicenseTemplate = new LicenseTemplateImpl();
        updateLicenseTemplate.addProperty("Updated property name", "Updated value");
        licenseTemplate = LicenseTemplateService.update(context, licenseTemplateNumber, updateLicenseTemplate);
        out.writeObject("Updated license template:", licenseTemplate);

        LicenseTemplateService.delete(context, licenseTemplateNumber, true);
        out.writeMessage("Deleted license template!");

        licenseTemplates = LicenseTemplateService.list(context, null);
        out.writePage("Got the following license templates:", licenseTemplates);

        licenseTemplate = LicenseTemplateService.create(context, productModuleNumber, newLicenseTemplate);
        out.writeObject("Added license template again:", licenseTemplate);

        licenseTemplates = LicenseTemplateService.list(context, null);
        out.writePage("Got the following license templates:", licenseTemplates);

        // endregion

        // region ********* Licensee

        final Licensee newLicensee = new LicenseeImpl();
        newLicensee.setNumber(licenseeNumber);
        Licensee licensee = LicenseeService.create(context, productNumber, newLicensee);
        out.writeObject("Added licensee:", licensee);

        Page<Licensee> licensees = LicenseeService.list(context, null);
        out.writePage("Got the following licensees:", licensees);

        LicenseeService.delete(context, licenseeNumber, true);
        out.writeMessage("Deleted licensee!");

        licensees = LicenseeService.list(context, null);
        out.writePage("Got the following licensees after delete:", licensees);

        licensee = LicenseeService.create(context, productNumber, newLicensee);
        out.writeObject("Added licensee again:", licensee);

        licensee = LicenseeService.get(context, licenseeNumber);
        out.writeObject("Got licensee:", licensee);

        final Licensee updateLicensee = new LicenseeImpl();
        updateLicensee.addProperty("Updated property name", "Updated value");
        updateLicensee.addProperty(Constants.Licensee.PROP_LICENSEE_SECRET, randomLicenseeSecret);

        licensee = LicenseeService.update(context, licenseeNumber, updateLicensee);
        out.writeObject("Updated licensee:", licensee);

        licensees = LicenseeService.list(context, null);
        out.writePage("Got the following licensees:", licensees);

        // endregion

        // region ********* License

        final License newLicense = new LicenseImpl();
        newLicense.setNumber(licenseNumber);
        License license = LicenseService.create(context, licenseeNumber, licenseTemplateNumber, null,
                newLicense);
        out.writeObject("Added license:", license);

        Page<License> licenses = LicenseService.list(context, null);
        out.writePage("Got the following licenses:", licenses);

        LicenseService.delete(context, licenseNumber, true);
        out.writeMessage("Deleted license!");

        licenses = LicenseService.list(context, null);
        out.writePage("Got the following licenses:", licenses);

        license = LicenseService.create(context, licenseeNumber, licenseTemplateNumber, null, newLicense);
        out.writeObject("Added license again:", license);

        license = LicenseService.get(context, licenseNumber);
        out.writeObject("Got license:", license);

        final License updateLicense = new LicenseImpl();
        updateLicense.addProperty("Updated property name", "Updated value");
        license = LicenseService.update(context, licenseNumber, null, updateLicense);
        out.writeObject("Updated license:", license);

        // endregion

        // region ********* PaymentMethod

        final Page<PaymentMethod> paymentMethods = PaymentMethodService.list(context, null);
        out.writePage("Got the following payment methods:", paymentMethods);

        // endregion

        // region ********* Token

        final Token newToken = new TokenImpl();
        newToken.setTokenType(TokenType.APIKEY);
        final Token apiKey = TokenService.create(context, newToken);
        out.writeObject("Created APIKey:", apiKey);

        context.setApiKey(apiKey.getNumber());
        newToken.setTokenType(TokenType.SHOP);
        newToken.addProperty(Constants.Licensee.LICENSEE_NUMBER, licenseeNumber);
        context.setSecurityMode(SecurityMode.APIKEY_IDENTIFICATION);
        final Token shopToken = TokenService.create(context, newToken);
        context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
        out.writeObject("Got the following shop token:", shopToken);

        final String filter = Constants.Token.TOKEN_TYPE + "=" + TokenType.SHOP.name();
        Page<Token> tokens = TokenService.list(context, filter);
        out.writePage("Got the following shop tokens:", tokens);

        TokenService.delete(context, shopToken.getNumber());
        out.writeMessage("Deleted shop token!");

        tokens = TokenService.list(context, filter);
        out.writePage("Got the following shop tokens after delete:", tokens);

        // endregion

        // region ********* Validate

        final ValidationParameters validationParameters = new ValidationParameters();
        validationParameters.put(productModuleNumber, "paramKey", "paramValue");
        validationParameters.setLicenseeSecret(randomLicenseeSecret);
        validationParameters.setLicenseeName(licenseeName);
        validationParameters.setProductNumber(productNumber);
        ValidationResult validationResult = LicenseeService.validate(context, licenseeNumber,
                validationParameters);
        out.writeObject("Validation result for created licensee:", validationResult);

        context.setSecurityMode(SecurityMode.APIKEY_IDENTIFICATION);
        validationResult = LicenseeService.validate(context, licenseeNumber, validationParameters);
        context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
        out.writeObject("Validation repeated with APIKey:", validationResult);

        // endregion

        // region ********* Transfer
        Licensee transferLicensee = new LicenseeImpl();
        transferLicensee.setNumber("TR" + licenseeNumber);
        transferLicensee.getProperties().put(Constants.Licensee.PROP_MARKED_FOR_TRANSFER,
                Boolean.toString(true));
        transferLicensee = LicenseeService.create(context, productNumber, transferLicensee);
        out.writeObject("Added transfer licensee:", transferLicensee);

        final License transferLicense = new LicenseImpl();
        transferLicense.setNumber("LTR" + licenseNumber);
        final License newTransferLicense = LicenseService.create(context, transferLicensee.getNumber(),
                licenseTemplateNumber, null, transferLicense);
        out.writeObject("Added license for transfer:", newTransferLicense);

        LicenseeService.transfer(context, licensee.getNumber(), transferLicensee.getNumber());

        licenses = LicenseService.list(context, "licenseeNumber=" + licensee.getNumber());
        out.writePage("Got the following licenses after transfer:", licenses);

        Licensee transferLicenseeWithApiKey = new LicenseeImpl();
        transferLicenseeWithApiKey.setNumber("Key" + licenseeNumber);
        transferLicenseeWithApiKey.getProperties().put(Constants.Licensee.PROP_MARKED_FOR_TRANSFER,
                Boolean.toString(true));
        transferLicenseeWithApiKey = LicenseeService.create(context, productNumber, transferLicenseeWithApiKey);

        final License transferLicenseWithApiKey = new LicenseImpl();
        transferLicenseWithApiKey.setNumber("Key" + licenseNumber);
        LicenseService.create(context, transferLicenseeWithApiKey.getNumber(), licenseTemplateNumber, null,
                transferLicenseWithApiKey);

        context.setSecurityMode(SecurityMode.APIKEY_IDENTIFICATION);
        LicenseeService.transfer(context, licensee.getNumber(), transferLicenseeWithApiKey.getNumber());
        context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);

        licenses = LicenseService.list(context, "licenseeNumber=" + licensee.getNumber());
        out.writePage("Got the following licenses after transfer:", licenses);
        // endregion

        // region ********* Transactions
        Page<Transaction> transactions = TransactionService.list(context,
                Constants.Transaction.SOURCE_SHOP_ONLY + "=" + Boolean.TRUE.toString());
        out.writePage("Got the following transactions shop only:", transactions);

        transactions = TransactionService.list(context, null);
        out.writePage("Got the following transactions after transfer:", transactions);
        // endregion

        out.writeMessage("All done.");

    } catch (final NetLicensingException e) {
        out.writeException("Got NetLicensing exception:", e);
        exitCode = CODE_ERROR;
    } catch (final Exception e) {
        out.writeException("Got exception:", e);
        exitCode = CODE_ERROR;
    } finally {
        // Cleanup
        try {
            // delete APIKey in case it was used (exists)
            if (StringUtils.isNotBlank(context.getApiKey())) {
                TokenService.delete(context, context.getApiKey());
                context.setApiKey(null);
            }

            // delete test product with all its related items
            ProductService.delete(context, productNumber, true);

        } catch (final NetLicensingException e) {
            out.writeException("Got NetLicensing exception during cleanup:", e);
            exitCode = CODE_ERROR;
        } catch (final Exception e) {
            out.writeException("Got exception during cleanup:", e);
            exitCode = CODE_ERROR;
        }
    }

    if (exitCode == CODE_ERROR) {
        System.exit(exitCode);
    }
}

From source file:Main.java

public static String quzheng(float d) {
    return new BigDecimal(d).setScale(0, BigDecimal.ROUND_HALF_UP) + "";
}