Example usage for java.lang String format

List of usage examples for java.lang String format

Introduction

In this page you can find the example usage for java.lang String format.

Prototype

public static String format(String format, Object... args) 

Source Link

Document

Returns a formatted string using the specified format string and arguments.

Usage

From source file:cz.pichlik.goodsentiment.MockDataGenerator.java

public static void main(String args[]) throws IOException {
    String outputDirectory = args[0];
    LocalDate seedDate = LocalDate.of(2015, 9, 1);
    for (int i = 0; i < 100; i++) {
        LocalDate date = seedDate.plusDays(i);
        File outputDirectoryFile = new File(outputDirectory);
        outputDirectoryFile.mkdirs();/* w  w  w  .ja v a 2 s  .  c om*/
        File outputFile = new File(outputDirectoryFile, String.format("goodsentinment-data-%s.csv", date));
        generateFile(outputFile, date);
    }
}

From source file:name.ikysil.beanpathdsl.sandbox.describe.Main.java

/**
 * @param args the command line arguments
 *//*from  w w  w  .j  a  va2s .  c o  m*/
public static void main(String[] args) {
    PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
    Reflections reflections = new Reflections(TestBean.class, new SubTypesScanner(false));
    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    for (Class<?> clazz : classes) {
        System.out.println(String.format("Class name: %s", clazz.getName()));
        System.out.println(String.format("Class simple name: %s", clazz.getSimpleName()));
        System.out.println(String.format("Class canonical name: %s", clazz.getCanonicalName()));
        PropertyDescriptor[] pds = propertyUtilsBean.getPropertyDescriptors(clazz);
        for (PropertyDescriptor pd : pds) {
            System.out.println(String.format("    Property name: %s", pd.getName()));
            Class<?> pc = pd.getPropertyType();
            System.out.println(String.format("    Class name: %s", pc.getName()));
            System.out.println(String.format("    Class simple name: %s", pc.getSimpleName()));
            System.out.println(String.format("    Class canonical name: %s", pc.getCanonicalName()));
        }
    }
}

From source file:br.com.asisprojetos.mailreport.Main.java

public static void main(String args[]) {

    logger.debug("Testando debug");

    if (args.length < 2) {
        logger.error("Erro : Numero de parametros errados.");
        System.exit(1);//ww w.  j ava2 s . c  om
    }

    String dataIniProc = String.format("%s 00:00:00", args[0]);
    String dataFimProc = String.format("%s 23:59:59", args[1]);

    logger.debug("Data Inicial: {} , Data Final: {}", dataIniProc, dataFimProc);

    String mes = String.format("%s/%s", args[0].substring(5, 7), args[0].substring(0, 4));

    ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Datasource.xml");

    TBRelatorioEmailDAO tbRelatorioEmailDAO = (TBRelatorioEmailDAO) context.getBean("TBRelatorioEmailDAO");

    List<TBRelatorioEmail> listaRelatorioEmail = tbRelatorioEmailDAO.getAll();

    for (TBRelatorioEmail tbRelatorioEmail : listaRelatorioEmail) {

        logger.debug(" CodContrato: {}, CodProduto: {}", tbRelatorioEmail.getCodContrato(),
                tbRelatorioEmail.getCodProduto());

        List<String> listaEmails = tbRelatorioEmailDAO.getListaEmails(tbRelatorioEmail.getCodContrato());

        if (!listaEmails.isEmpty()) {

            logger.debug("Lista de Emails obtida : [{}] ", listaEmails);

            //List<String> listaCodProduto = Arrays.asList( StringUtils.split(tbRelatorioEmail.getCodProduto(), ';') ) ;
            List<String> listaCodProduto = new ArrayList<String>();
            listaCodProduto.add("1");//Sped Fiscal

            logger.debug("Gerando Relatorio Geral de Consumo por Produto...");

            List<String> fileNames = new ArrayList<String>();
            String fileName;

            BarChartDemo barChartDemo = (BarChartDemo) context.getBean("BarChartDemo");
            //fileName = barChartDemo.generateBarChartGraph(tbRelatorioEmail.getCodContrato());
            //fileNames.add(fileName);
            fileNames = barChartDemo.generateBarChartGraph2(tbRelatorioEmail.getCodContrato());

            String templateFile = null;

            for (String codProduto : listaCodProduto) {

                if (codProduto.equals(Produto.SPED_FISCAL.getCodProduto())) {

                    logger.debug("Produto Codigo : {} ", codProduto);
                    templateFile = "index6.html";

                    //grafico de diagnostico
                    fileName = barChartDemo.generateDiagnosticGraph(tbRelatorioEmail.getCodContrato(),
                            dataIniProc, dataFimProc);
                    fileNames.add(fileName);

                    //grafico de auditoria recorrente
                    fileName = barChartDemo.generateRecurrentGraph(tbRelatorioEmail.getCodContrato(),
                            dataIniProc, dataFimProc);
                    fileNames.add(fileName);

                } else {
                    logger.debug("Produto Codigo : {} no aceito para gerar grafico ", codProduto);
                }

                logger.debug("Enviando Email.............Produto Codigo : {}", codProduto);

                SendEmail sendEmail = (SendEmail) context.getBean("SendEmail");
                sendEmail.enviar(listaEmails.toArray(new String[listaEmails.size()]),
                        "Relatrio Mensal de Riscos Fiscais", templateFile, fileNames, mes,
                        tbRelatorioEmail.getCodContrato());

                //sendEmail.enviar( new String[]{"leandro.prates@asisprojetos.com.br","leandro.prates@gmail.com"}  , 
                //        "Relatrio Mensal de Riscos Fiscais", templateFile, fileNames, mes, tbRelatorioEmail.getCodContrato() );

            }

            //Remover todos os arquivos png gerado para o cliente

            Config config = (Config) context.getBean("Config");

            for (String f : fileNames) {

                try {
                    File file = new File(String.format("%s/%s", config.getOutDirectory(), f));
                    if (file.delete()) {
                        logger.debug("Arquivo: [{}/{}] deletado com sucesso.", config.getOutDirectory(), f);
                    } else {
                        logger.error("Erro ao deletar o arquivo: [{}/{}]", config.getOutDirectory(), f);
                    }

                } catch (Exception ex) {
                    logger.error("Erro ao deletar o arquivo: [{}/{}] . Message {}", config.getOutDirectory(), f,
                            ex);
                }

            }

        }

    }

}

From source file:org.envirocar.harvest.TrackHarvesterExecution.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    String consumerUrl = null;//www  .j a  v a2  s  .  c om
    if (args != null && args.length > 0) {
        consumerUrl = args[0].trim();
    } else {
        throw new IllegalArgumentException("consumerUrl needs to be provided");
    }

    ProgressListener l = new ProgressListener() {

        @Override
        public void onProgressUpdate(float progressPercent) {
            System.out.println(String.format("%f percent finished", progressPercent));
        }

    };
    new TrackHarvester(consumerUrl, l).harvestTracks();
}

From source file:com.hotinno.feedmonitor.batch.Main.java

public static void main(String[] args) throws Throwable {
    try {//from w  ww . j a  va  2  s. co  m
        log.error("Entering batch...");

        String env = System.getenv("VCAP_SERVICES");
        log.error("************************************************************************");
        log.error("VCAP_SERVICES is: " + env);
        log.error("************************************************************************");

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
                BuffaloBatchConfiguration.class);

        org.apache.commons.dbcp.BasicDataSource ds = (org.apache.commons.dbcp.BasicDataSource) applicationContext
                .getBean("myDataSource");

        log.error(String.format("URL: %s", ds.getUrl()));
        log.error(String.format("Username: %s", ds.getUsername()));
        log.error(String.format("Password: %s", ds.getPassword()));

        applicationContext.start();

        log.error("Running...");
    } catch (Throwable t) {
        System.err.println(t);
        t.printStackTrace();
        log.error("Error occurred.", t);
    }
}

From source file:invoice.GetInvoice.java

/**
 * @param args the command line arguments
 *///  ww w . j a  v a 2 s. c  o  m
public static void main(String[] args) {

    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    nf.setRoundingMode(RoundingMode.HALF_UP);

    try {
        JSONObject arg_json = new JSONObject(args[0]);
    } catch (JSONException ex) {
        Logger.getLogger(GetInvoice.class.getName()).log(Level.SEVERE, null, ex);
    }
    HashMap<String, Object> hm = new HashMap<>();
    hm.put("duplicate", "");
    hm.put("distributor", "//oshan" + "\n" + "//kapuhempala" + "\n\nArea: " + "//galle");
    hm.put("customer", "//owner" + "\n" + "//Agro" + "\n" + "//Agro add" + "\n" + "//0771894851");
    hm.put("invNo", "GSLTS" + String.format("%04d", Integer.parseInt("//100")));
    hm.put("invDate", "2014-01-10");
    hm.put("invCode", "300");

    double invoiceTotal = 500000;
    if (5 > 0) {//ShopDiscount
        double discountprice = (invoiceTotal * 99) / 100;//getShopDiscount()
        hm.put("invoiceDiscount", nf.format((invoiceTotal) * 99 / 100));//getRetail_discount()

    } else {
        hm.put("invoiceDiscount", "");
    }
    hm.put("gross_total", nf.format(invoiceTotal));
    hm.put("invoiceTotal", nf.format(((invoiceTotal) * (100 - 99) / 100)));//getRetail_discount()
    hm.put("salesPersonName", "rep");
    hm.put("salesPersonContactNo", "0772189584");

    JTable jTable1 = new JTable();
    jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {},
            new String[] { "ITEMCODE", "DESCRIPTION", "QTY", "FREEQTY", "PRICE", "AMOUNT" }));
    String reportSource = "./ireports/invoice.jrxml";
    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
    try {
        JasperReport jr = JasperCompileManager.compileReport(reportSource);
        JasperPrint jp = JasperFillManager.fillReport(jr, hm, new JRTableModelDataSource(dtm));
        JasperPrintManager.printReport(jp, false);
    } catch (JRException ex) {
        Logger.getLogger(GetInvoice.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("1");
}

From source file:org.n52.iceland.statistics.api.utils.KibanaExporter.java

public static void main(String args[]) throws Exception {
    if (args.length != 2) {
        System.out.printf("Usage: java KibanaExporter.jar %s %s\n", "localhost:9300", "my-cluster-name");
        System.exit(0);//from w  ww .ja v a  2s .  c o m
    }
    if (!args[0].contains(":")) {
        throw new IllegalArgumentException(
                String.format("%s not a valid format. Expected <hostname>:<port>.", args[0]));
    }

    // set ES address
    String split[] = args[0].split(":");
    InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(split[0]),
            Integer.parseInt(split[1], 10));

    // set cluster name
    Builder tcSettings = Settings.settingsBuilder();
    tcSettings.put("cluster.name", args[1]);
    System.out.println("Connection to " + args[1]);

    client = TransportClient.builder().settings(tcSettings).build();
    client.addTransportAddress(address);

    // search index pattern for needle
    searchIndexPattern();

    KibanaConfigHolderDto holder = new KibanaConfigHolderDto();
    System.out.println("Reading .kibana index");

    SearchResponse resp = client.prepareSearch(".kibana").setSize(1000).get();
    Arrays.asList(resp.getHits().getHits()).stream().map(KibanaExporter::parseSearchHit).forEach(holder::add);
    System.out.println("Reading finished");

    ObjectMapper mapper = new ObjectMapper();
    // we love pretty things
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    File f = new File("kibana_config.json");

    try (FileOutputStream out = new FileOutputStream(f, false)) {
        mapper.writeValue(out, holder);
    }

    System.out.println("File outputted to: " + f.getAbsolutePath());

    client.close();

}

From source file:isc_415_practica_1.ISC_415_Practica_1.java

/**
 * @param args the command line arguments
 *//*from   w  ww.  ja  va2s  .  com*/
public static void main(String[] args) {
    String urlString;
    Scanner input = new Scanner(System.in);
    Document doc;

    try {
        urlString = input.next();
        if (urlString.equals("servlet")) {
            urlString = "http://localhost:8084/ISC_415_Practica1_Servlet/client";
        }
        urlString = urlString.contains("http://") || urlString.contains("https://") ? urlString
                : "http://" + urlString;
        doc = Jsoup.connect(urlString).get();
    } catch (Exception ex) {
        System.out.println("El URL ingresado no es valido.");
        return;
    }

    ArrayList<NameValuePair> formInputParams;
    formInputParams = new ArrayList<>();
    String[] plainTextDoc = new TextNode(doc.html(), "").getWholeText().split("\n");
    System.out.println(String.format("Nmero de lineas del documento: %d", plainTextDoc.length));
    System.out.println(String.format("Nmero de p tags: %d", doc.select("p").size()));
    System.out.println(String.format("Nmero de img tags: %d", doc.select("img").size()));
    System.out.println(String.format("Nmero de form tags: %d", doc.select("form").size()));

    Integer index = 1;

    ArrayList<NameValuePair> urlParameters = new ArrayList<>();
    for (Element e : doc.select("form")) {
        System.out.println(String.format("Form %d: Nmero de Input tags %d", index, e.select("input").size()));
        System.out.println(e.select("input"));

        for (Element formInput : e.select("input")) {
            if (formInput.attr("id") != null && formInput.attr("id") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("id"), "PRACTICA1"));
            } else if (formInput.attr("name") != null && formInput.attr("name") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("name"), "PRACTICA1"));
            }
        }

        index++;
    }

    if (!urlParameters.isEmpty()) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, Consts.UTF_8);
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
        } catch (IOException ex) {
            Logger.getLogger(ISC_415_Practica_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:cz.hobrasoft.pdfmu.jackson.SchemaGenerator.java

public static void main(String[] args) throws JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting

    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

    Map<String, Type> types = new HashMap<>();
    types.put("RpcResponse", RpcResponse.class);
    types.put("result/inspect", Inspect.class);
    types.put("result/version set", VersionSet.class);
    types.put("result/signature add", SignatureAdd.class);
    types.put("result/empty", EmptyResult.class);

    for (Map.Entry<String, Type> e : types.entrySet()) {
        String name = e.getKey();
        String filename = String.format("schema/%s.json", name);
        Type type = e.getValue();
        mapper.acceptJsonFormatVisitor(mapper.constructType(type), visitor);
        JsonSchema jsonSchema = visitor.finalSchema();
        mapper.writeValue(new File(filename), jsonSchema);
    }//from w w  w .j  a  va 2s  . c  om
}

From source file:com.chiralBehaviors.autoconfigure.debug.TemplateDebugger.java

public static void main(String[] argv) throws JsonParseException, JsonMappingException, IOException {
    if (argv.length == 0) {
        System.out.println("Usage: TemplateDebugger <scenario file>+");
        System.exit(1);/*from   w  w  w.  ja v  a 2  s  .  c  o  m*/
    }
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    for (String fileName : argv) {
        FileInputStream yaml = new FileInputStream(fileName);
        TemplateDebugger debugger = mapper.readValue(yaml, TemplateDebugger.class);
        System.out.println("======================================");
        System.out.println(String.format("Rendered output of %s", yaml));
        System.out.println("======================================");
        System.out.println();
        System.out.println(debugger.render());
        System.out.println();
        System.out.println("======================================");
        System.out.println();
        System.out.println();
    }
}