Example usage for java.lang StringBuilder append

List of usage examples for java.lang StringBuilder append

Introduction

In this page you can find the example usage for java.lang StringBuilder append.

Prototype

@Override
    public StringBuilder append(double d) 

Source Link

Usage

From source file:fr.eo.util.dumper.Dumper.java

/**
 * @param args//w w  w.j  av  a  2  s .  co  m
 */
public static void main(String[] args) {

    String appName = args[0];

    System.out.println("Starting dumper ...");

    Statement stmt = null;

    try {
        System.out.println("Getting database connection ...");
        Connection conn = getJtdsConnection();

        List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName);

        assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/";

        for (RequestDefinitionBean request : requests) {
            int currentFileSize = 0, cpt = 1;
            stmt = conn.createStatement();
            System.out.println("Dumping " + request.name + "...");
            ResultSet rs = stmt.executeQuery(request.sql);
            BufferedWriter bw = getWriter(request.name, cpt);
            bw.append(COPYRIGHTS);
            currentFileSize += COPYRIGHTS.length();
            bw.append("--" + request.name + "\n");
            while (rs.next()) {
                StringBuilder sb = new StringBuilder();
                sb.append("INSERT INTO ");
                sb.append(request.table).append(" VALUES (");
                int pos = 0;
                for (String fieldName : request.fields) {
                    String str = getFieldValue(request, pos, rs, fieldName);
                    sb.append(str);
                    pos++;
                    if (pos < request.fields.size()) {
                        sb.append(",");
                    }
                }
                sb.append(");\n");
                currentFileSize += sb.length();
                bw.append(sb.toString());
                bw.flush();

                if (currentFileSize > MAX_FILE_SIZE) {
                    bw.close();

                    bw = getWriter(request.name, ++cpt);
                    bw.append(COPYRIGHTS);
                    bw.append("--" + request.name + "\n");
                    currentFileSize = COPYRIGHTS.length();
                }
            }
            bw.flush();
            bw.close();
        }

        System.out.println("done.");

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    DumpFilesDescriptor descriptor = new DumpFilesDescriptor();
    descriptor.lineNumbers = getDumpLinesNumber();
    descriptor.dumpFileNames = dumpFileNames;
    writeDescriptorFile(descriptor);

    System.out.println("nb :" + descriptor.lineNumbers);
}

From source file:icevaluation.BingAPIAccess.java

public static void main(String[] args) {
    String searchText = "arts site:wikipedia.org";
    searchText = searchText.replaceAll(" ", "%20");
    // String accountKey="jTRIJt9d8DR2QT/Z3BJCAvY1BfoXj0zRYgSZ8deqHHo";
    String accountKey = "JfeJSA3x6CtsyVai0+KEP0A6CYEUBT8VWhZmm9CS738";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    URL url;/*from  w w  w . ja v a  2 s.c om*/
    try {
        url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27"
                + searchText + "%27&$format=JSON");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        System.out.println("Output from Server .... \n");
        //write json to string sb
        int c = 0;
        if ((output = br.readLine()) != null) {
            System.out.println("Output is: " + output);
            sb.append(output);
            c++;
            //System.out.println("C:"+c);

        }

        conn.disconnect();
        //find webtotal among output      
        int find = sb.indexOf("\"WebTotal\":\"");
        int startindex = find + 12;
        System.out.println("Find: " + find);

        int lastindex = sb.indexOf("\",\"WebOffset\"");

        System.out.println(sb.substring(startindex, lastindex));

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:com.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {//from w w w  . j a  v  a2  s. co  m
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

From source file:com.gzj.tulip.jade.statement.SystemInterpreter.java

public static void main(String[] args) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("table", "my_table_name");
    parameters.put("id", "my_id");
    parameters.put(":1", "first_param");

    final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

    String sql = "select form ##(:table) {name} where {id}='{1}'";

    StringBuilder sb = new StringBuilder(sql.length() + 200);
    Matcher matcher = PATTERN.matcher(sql);
    int start = 0;
    while (matcher.find(start)) {
        sb.append(sql.substring(start, matcher.start()));
        String group = matcher.group();
        String key = null;/* w  w  w  . ja va2s  .  c  o m*/
        if (group.startsWith("{")) {
            key = matcher.group(1);
        } else if (group.startsWith("##(")) {
            key = matcher.group(2);
        }
        System.out.println(key);
        if (key == null || key.length() == 0) {
            continue;
        }
        Object value = parameters.get(key); // {paramName}?{:1}?
        if (value == null) {
            if (key.startsWith(":") || key.startsWith("$")) {
                value = parameters.get(key.substring(1)); // {:paramName}
            } else {
                char ch = key.charAt(0);
                if (ch >= '0' && ch <= '9') {
                    value = parameters.get(":" + key); // {1}?
                }
            }
        }
        if (value == null) {
            value = parameters.get(key); // ?
        }
        if (value != null) {
            sb.append(value);
        } else {
            sb.append(group);
        }
        start = matcher.end();
    }
    sb.append(sql.substring(start));
    System.out.println(sb);

}

From source file:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java

/**
 * Main entry point - for use outside the interactive shell.
 * @param args//w w  w.j ava 2 s. c  o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String brmsPackageName = "SRAMPPackage"; //$NON-NLS-1$
    String tag = "LATEST"; //$NON-NLS-1$
    String brmsBaseUrl = "http://localhost:8080/drools-guvnor"; //$NON-NLS-1$
    String brmsUserId = "admin"; //$NON-NLS-1$
    String brmsPassword = "admin"; //$NON-NLS-1$
    if (args.length > 0)
        brmsPackageName = args[0];
    if (args.length > 1)
        tag = args[1];
    if (args.length > 2)
        brmsBaseUrl = args[2];
    if (args.length > 3)
        brmsUserId = args[3];
    if (args.length > 4)
        brmsPassword = args[4];
    StringBuilder argLine = new StringBuilder();
    argLine.append(brmsPackageName).append(" ").append(tag) //$NON-NLS-1$
            .append(" ").append(brmsBaseUrl) //$NON-NLS-1$
            .append(" ").append(brmsUserId) //$NON-NLS-1$
            .append(" ").append(brmsPassword); //$NON-NLS-1$

    SrampAtomApiClient client = new SrampAtomApiClient("http://localhost:8080/s-ramp-server"); //$NON-NLS-1$
    QName clientVarName = new QName("s-ramp", "client"); //$NON-NLS-1$ //$NON-NLS-2$
    Pkg2SrampCommand cmd = new Pkg2SrampCommand();
    ShellContext context = new SimpleShellContext();
    context.setVariable(clientVarName, client);
    cmd.setArguments(new Arguments(argLine.toString()));
    cmd.setContext(context);
    cmd.execute();
}

From source file:de.uniko.west.winter.test.basics.JenaTests.java

public static void main(String[] args) {

    Model newModel = ModelFactory.createDefaultModel();
    //      // w  w w .  j  a  va 2s.co  m
    Model newModel2 = ModelFactory.createModelForGraph(ModelFactory.createMemModelMaker().getGraphMaker()
            .createGraph("http://www.defaultgraph.de/graph1"));
    StringBuilder updateString = new StringBuilder();
    updateString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    updateString.append("PREFIX xsd: <http://bla.org/dc/elements/1.1/>");
    updateString.append("INSERT { ");
    updateString.append(
            "<http://example/egbook1> dc:title  <http://example/egbook1/#Title1>, <http://example/egbook1/#Title2>. ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.1\". ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.2\". ");
    updateString.append("<http://example/egbook21> dc:title  \"Title2\"; ");
    updateString.append("dc:title  \"2.0\"^^xsd:double. ");
    updateString.append("<http://example/egbook3> dc:title  \"Title3\". ");
    updateString.append("<http://example/egbook4> dc:title  \"Title4\". ");
    updateString.append("<http://example/egbook5> dc:title  \"Title5\". ");
    updateString.append("<http://example/egbook6> dc:title  \"Title6\" ");
    updateString.append("}");

    UpdateRequest update = UpdateFactory.create(updateString.toString());
    UpdateAction.execute(update, newModel);

    StmtIterator iter = newModel.listStatements();
    System.out.println("After add");
    while (iter.hasNext()) {
        System.out.println(iter.next().toString());

    }

    StringBuilder constructQueryString = new StringBuilder();
    constructQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    constructQueryString.append("CONSTRUCT {?sub dc:title <http://example/egbook1/#Title1>}");
    constructQueryString.append("WHERE {");
    constructQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    constructQueryString.append("}");

    StringBuilder askQueryString = new StringBuilder();
    askQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    askQueryString.append("ASK {");
    askQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    askQueryString.append("}");

    StringBuilder selectQueryString = new StringBuilder();
    selectQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    selectQueryString.append("SELECT * ");
    selectQueryString.append("WHERE {");
    selectQueryString.append("?sub ?pred ?obj");
    selectQueryString.append("}");

    Query cquery = QueryFactory.create(constructQueryString.toString());
    System.out.println(cquery.getQueryType());
    Query aquery = QueryFactory.create(askQueryString.toString());
    System.out.println(aquery.getQueryType());
    Query query = QueryFactory.create(selectQueryString.toString());
    System.out.println(query.getQueryType());
    QueryExecution queryExecution = QueryExecutionFactory.create(query, newModel);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    URI test = null;
    try {
        test = new URI("http://bla.org/dc/elements/1.1/double");
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println(test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1));
    System.out.println("java.lang."
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(0, 1)
                    .toUpperCase()
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(1));

    String typ = "java.lang.Boolean";
    String val = "true";

    try {
        Object typedLiteral = Class.forName(typ, true, ClassLoader.getSystemClassLoader())
                .getConstructor(String.class).newInstance(val);

        System.out.println("Type: " + typedLiteral.getClass().getName() + " Value: " + typedLiteral);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        System.out.println("Query...");
        com.hp.hpl.jena.query.ResultSet results = queryExecution.execSelect();
        System.out.println("RESULT:");
        ResultSetFormatter.output(System.out, results, ResultSetFormat.syntaxJSON);
        //         
        //         
        //         ResultSetFormatter.outputAsJSON(baos, results);
        //         System.out.println(baos.toString());
        //         System.out.println("JsonTest: ");
        //         JSONObject result = new JSONObject(baos.toString("ISO-8859-1"));
        //         for (Iterator key = result.keys(); result.keys().hasNext(); ){
        //            System.out.println(key.next());
        //            
        //            for (Iterator key2 = ((JSONObject)result.getJSONObject("head")).keys(); key2.hasNext(); ){
        //               System.out.println(key2.next());
        //            }
        //         }

        //         Model results = queryExecution.execConstruct();

        //         results.write(System.out, "TURTLE");
        //         for ( ; results.hasNext() ; ){
        //            QuerySolution soln = results.nextSolution() ;
        //            RDFNode x = soln.get("sub") ;   
        //            System.out.println("result: "+soln.get("sub")+" hasTitle "+soln.get("obj"));
        //             Resource r = soln.getResource("VarR") ; 
        //             Literal l = soln.getLiteral("VarL") ; 
        //
        //         }

    } catch (Exception e) {
        // TODO: handle exception
    }

    //      StringBuilder updateString2 = new StringBuilder();
    //      updateString2.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString2.append("DELETE DATA { ");
    //      updateString2.append("<http://example/egbook3> dc:title  \"Title3\" ");
    //      updateString2.append("}");
    //
    //      UpdateAction.parseExecute(updateString2.toString(), newModel);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After delete");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
    //      
    //      StringBuilder updateString3 = new StringBuilder();
    //      updateString3.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString3.append("DELETE DATA { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"Title6\" ");
    //      updateString3.append("}");
    //      updateString3.append("INSERT { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"New Title6\" ");
    //      updateString3.append("}");
    //   
    //      UpdateAction.parseExecute(updateString3.toString(), newModel);

    //      UpdateAction.parseExecute(   "prefix exp: <http://www.example.de>"+
    //                           "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+
    //                           "INSERT { graph <http://www.defaultgraph.de/graph1> {"+
    //                           "   <http://www.test.de#substructure1> <exp:has_relation3> <http://www.test.de#substructure2> ."+ 
    //                           "   <http://www.test.de#substructure1> <rdf:type> <http://www.test.de#substructuretype1> ."+ 
    //                           "   <http://www.test.de#substructure2> <rdf:type> <http://www.test.de#substructuretype2> ."+
    //                           "}}", newModel2);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After update");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
}

From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//from   ww w .  j  a  va  2s .  c  o  m
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            int length;
            while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                stringBuilder.append(new String(CHAR_BUFFER, 0, length));
            }
        }
        String query = stringBuilder.toString();
        httpPost.setEntity(new StringEntity(query));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.W2VDatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *//* w w  w  .j a  va  2  s  .  co m*/
public static void main(String[] args) {
    CommandLine cmd = ESADatalessAnnotator.getCMDOpts(args);

    ResourceManager rm;

    try {
        String configFile = cmd.getOptionValue("config", "config/project.properties");
        ResourceManager nonDefaultRm = new ResourceManager(configFile);

        rm = new W2VDatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new W2VDatalessConfigurator().getDefaultConfig();
    }

    String testFile = cmd.getOptionValue("testFile", "data/graphicsTestDocument.txt");

    StringBuilder sb = new StringBuilder();

    String line;

    try (BufferedReader br = new BufferedReader(new FileReader(new File(testFile)))) {
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(" ");
        }

        String text = sb.toString().trim();

        TokenizerTextAnnotationBuilder taBuilder = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
        TextAnnotation ta = taBuilder.createTextAnnotation(text);

        W2VDatalessAnnotator datalessAnnotator = new W2VDatalessAnnotator(rm);
        datalessAnnotator.addView(ta);

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_W2V).getConstituents();

        System.out.println("Predicted LabelIDs:");

        for (Constituent annot : annots) {
            System.out.println(annot.getLabel());
        }

        Map<String, String> labelNameMap = DatalessAnnotatorUtils
                .getLabelNameMap(rm.getString(DatalessConfigurator.LabelName_Path.key));

        System.out.println("Predicted Labels:");

        for (Constituent annot : annots) {
            System.out.println(labelNameMap.get(annot.getLabel()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("Test File not found at " + testFile + " ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    }
}

From source file:appmain.AppMain.java

public static void main(String[] args) {

    try {//w w  w.  j a v a  2s  .c  o  m
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        UIManager.put("OptionPane.yesButtonText", "Igen");
        UIManager.put("OptionPane.noButtonText", "Nem");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {

        AppMain app = new AppMain();
        app.init();

        File importFolder = new File(DEFAULT_IMPORT_FOLDER);
        if (!importFolder.isDirectory() || !importFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az IMPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        File exportFolder = new File(DEFAULT_EXPORT_FOLDER);
        if (!exportFolder.isDirectory() || !exportFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az EXPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + exportFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        List<File> xmlFiles = app.getXMLFiles(importFolder);
        if (xmlFiles == null || xmlFiles.isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder fileList = new StringBuilder();
        xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName()));
        int ret = JOptionPane.showConfirmDialog(null,
                "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?",
                "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (ret == JOptionPane.OK_OPTION) {
            String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis()
                    + ".csv";
            File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName);
            app.writeCSV(csv, Arrays.asList(app.getHeaderLine()));
            xmlFiles.stream().forEach(xml -> {
                List<String> lines = app.readXMLData(xml);
                if (lines != null)
                    app.writeCSV(csv, lines);
            });
            if (csv.isFile() && csv.exists()) {
                JOptionPane.showMessageDialog(null,
                        "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(),
                        "Informci", JOptionPane.INFORMATION_MESSAGE);
                app.openFile(csv);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci",
                    JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:baldrickv.s3streamingtool.S3StreamingTool.java

public static void main(String args[]) throws Exception {
    BasicParser p = new BasicParser();

    Options o = getOptions();//from  ww  w.j a  v a 2  s  .  co m

    CommandLine cl = p.parse(o, args);

    if (cl.hasOption('h')) {
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(80);

        StringBuilder sb = new StringBuilder();

        sb.append("\n");
        sb.append("Upload:\n");
        sb.append("    -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download:\n");
        sb.append("    -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Upload encrypted:\n");
        sb.append("    -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download encrypted:\n");
        sb.append("    -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Cleanup in-progress multipart uploads\n");
        sb.append("    -c -r creds -b my_bucket\n");
        System.out.println(sb.toString());

        hf.printHelp("See above", o);

        return;
    }

    int n = 0;
    if (cl.hasOption('d'))
        n++;
    if (cl.hasOption('u'))
        n++;
    if (cl.hasOption('c'))
        n++;
    if (cl.hasOption('m'))
        n++;

    if (n != 1) {
        System.err.println("Must specify at exactly one of -d, -u, -c or -m");
        System.exit(-1);
    }

    if (cl.hasOption('m')) {
        //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2);
        InputStream in = System.in;
        System.out.println(TreeHashGenerator.calculateTreeHash(in));
        return;
    }

    require(cl, 'b');

    if (cl.hasOption('d') || cl.hasOption('u')) {
        require(cl, 'f');
    }
    if (cl.hasOption('z')) {
        require(cl, 'k');
    }

    AWSCredentials creds = null;

    if (cl.hasOption('r')) {
        creds = Utils.loadAWSCredentails(cl.getOptionValue('r'));
    } else {
        if (cl.hasOption('i') && cl.hasOption('e')) {
            creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e'));
        } else {

            System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)");
            System.exit(-1);
        }
    }

    S3StreamConfig config = new S3StreamConfig();
    config.setEncryption(false);
    if (cl.hasOption('z')) {
        config.setEncryption(true);
        config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k")));
    }

    if (cl.hasOption("encryption-mode")) {
        config.setEncryptionMode(cl.getOptionValue("encryption-mode"));
    }
    config.setS3Bucket(cl.getOptionValue("bucket"));
    if (cl.hasOption("file")) {
        config.setS3File(cl.getOptionValue("file"));
    }

    if (cl.hasOption("threads")) {
        config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads")));
    }

    if (cl.hasOption("blocksize")) {
        String s = cl.getOptionValue("blocksize");
        s = s.toUpperCase();
        int multi = 1;

        int end = 0;
        while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) {
            end++;
        }
        int size = Integer.parseInt(s.substring(0, end));

        if (end < s.length()) {
            String m = s.substring(end);
            if (m.equals("K"))
                multi = 1024;
            else if (m.equals("M"))
                multi = 1048576;
            else if (m.equals("G"))
                multi = 1024 * 1024 * 1024;
            else if (m.equals("KB"))
                multi = 1024;
            else if (m.equals("MB"))
                multi = 1048576;
            else if (m.equals("GB"))
                multi = 1024 * 1024 * 1024;
            else {
                System.out.println("Unknown suffix on block size.  Only K,M and G understood.");
                System.exit(-1);
            }

        }
        size *= multi;
        config.setBlockSize(size);
    }

    Logger.getLogger("").setLevel(Level.FINE);

    S3StreamingDownload.log.setLevel(Level.FINE);
    S3StreamingUpload.log.setLevel(Level.FINE);

    config.setS3Client(new AmazonS3Client(creds));
    config.setGlacierClient(new AmazonGlacierClient(creds));
    config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com");

    if (cl.hasOption("glacier")) {
        config.setGlacier(true);
        config.setStorageInterface(new StorageGlacier(config.getGlacierClient()));
    } else {
        config.setStorageInterface(new StorageS3(config.getS3Client()));
    }
    if (cl.hasOption("bwlimit")) {
        config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit")));

    }

    if (cl.hasOption('c')) {
        if (config.getGlacier()) {
            GlacierCleanupMultipart.cleanup(config);
        } else {
            S3CleanupMultipart.cleanup(config);
        }
        return;
    }
    if (cl.hasOption('d')) {
        config.setOutputStream(System.out);
        S3StreamingDownload.download(config);
        return;
    }
    if (cl.hasOption('u')) {
        config.setInputStream(System.in);
        S3StreamingUpload.upload(config);
        return;
    }

}