Example usage for java.lang String replaceAll

List of usage examples for java.lang String replaceAll

Introduction

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

Prototype

public String replaceAll(String regex, String replacement) 

Source Link

Document

Replaces each substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:info.usbo.skypetwitter.Run.java

public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    Properties props;//from w w w.  j av a2 s  .  c  o m
    props = (Properties) System.getProperties().clone();
    //loadProperties(props, "D:\\Data\\Java\\classpath\\twitter.props");
    work_dir = System.getProperty("user.dir");
    loadProperties(props, work_dir + "\\twitter.props");
    twitter_user_id = props.getProperty("twitter.user");
    twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout"));
    System.out.println("Twitter user: " + twitter_user_id);
    System.out.println("Twitter timeout: " + twitter_timeout);
    if ("".equals(twitter_user_id)) {
        return;
    }
    if (load_file() == 0) {
        System.out.println("File not found");
        return;
    }
    while (true) {
        bChanged = 0;
        /*
        create_id();
        Chat ch = Chat.getInstance(chat_group_id);
        ch.send("!");
        */
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime()));
        Chat ch = Chat.getInstance(chat_group_id);
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            List<Status> statuses;
            statuses = twitter.getUserTimeline(twitter_user_id);
            //System.out.println("Showing @" + twitter_user_id + "'s user timeline.");
            String sText;
            for (Status status : statuses) {
                //System.out.println(status.getId());
                Date d = status.getCreatedAt();
                //   ?
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                cal.add(Calendar.HOUR_OF_DAY, 7);
                d = cal.getTime();
                sText = "@" + status.getUser().getScreenName() + "  " + sdf.format(d)
                        + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n"
                        + status.getText() + "\r\n***";
                for (URLEntity e : status.getURLEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getExpandedURL());
                }
                for (MediaEntity e : status.getMediaEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getMediaURL());
                }
                if (twitter_ids.indexOf(status.getId()) == -1) {
                    System.out.println(sText);
                    ch.send(sText);
                    twitter_ids.add(status.getId());
                    bChanged = 1;
                }
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }

        // VK
        try {
            vk();
            for (VK v : vk) {
                if (vk_ids.indexOf(v.getId()) == -1) {
                    Date d = v.getDate();
                    //   ?
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(d);
                    cal.add(Calendar.HOUR_OF_DAY, 7);
                    d = cal.getTime();
                    String sText = "@Depersonilized (VK)  " + sdf.format(d)
                            + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n"
                            + v.getText();
                    if (!"".equals(v.getAttachment())) {
                        sText += "\r\n" + v.getAttachment();
                    }
                    sText += "\r\n***";
                    System.out.println(sText);
                    ch.send(sText);
                    vk_ids.add(v.getId());
                    bChanged = 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Failed to get vk: " + e.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }
        if (bChanged == 1) {
            save_file();
        }
        try {
            Thread.sleep(1000 * 60 * twitter_timeout);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            System.out.println("Failed to sleep: " + ex.getMessage());
        }
    }
}

From source file:hyperheuristics.main.comparisons.ComputeIndicators.java

public static void main(String[] args) throws IOException, InterruptedException {
    int[] numberOfObjectivesArray = new int[] { 2, 4 };

    String[] problems = new String[] { "OO_MyBatis", "OA_AJHsqldb", "OA_AJHotDraw", "OO_BCEL", "OO_JHotDraw",
            "OA_HealthWatcher",
            //                "OA_TollSystems",
            "OO_JBoss" };

    String[] heuristicFunctions = new String[] { LowLevelHeuristic.CHOICE_FUNCTION,
            LowLevelHeuristic.MULTI_ARMED_BANDIT, LowLevelHeuristic.RANDOM };

    String[] algorithms = new String[] { "NSGA-II",
            //            "SPEA2"
    };//w ww.  j  ava2  s .co m

    MetricsUtil metricsUtil = new MetricsUtil();
    DecimalFormat decimalFormatter = new DecimalFormat("0.00E0");
    Mean mean = new Mean();
    StandardDeviation standardDeviation = new StandardDeviation();

    InvertedGenerationalDistance igd = new InvertedGenerationalDistance();
    GenerationalDistance gd = new GenerationalDistance();
    Spread spread = new Spread();
    Coverage coverage = new Coverage();

    for (int objectives : numberOfObjectivesArray) {
        try (FileWriter IGDWriter = new FileWriter("experiment/IGD_" + objectives + ".tex");
                FileWriter spreadWriter = new FileWriter("experiment/SPREAD_" + objectives + ".tex");
                FileWriter GDWriter = new FileWriter("experiment/GD_" + objectives + ".tex");
                FileWriter coverageWriter = new FileWriter("experiment/COVERAGE_" + objectives + ".tex")) {

            StringBuilder latexTableBuilder = new StringBuilder();

            latexTableBuilder.append("\\documentclass{paper}\n").append("\n")
                    .append("\\usepackage[T1]{fontenc}\n").append("\\usepackage[latin1]{inputenc}\n")
                    .append("\\usepackage[hidelinks]{hyperref}\n").append("\\usepackage{tabulary}\n")
                    .append("\\usepackage{booktabs}\n").append("\\usepackage{multirow}\n")
                    .append("\\usepackage{amsmath}\n").append("\\usepackage{mathtools}\n")
                    .append("\\usepackage{graphicx}\n").append("\\usepackage{array}\n")
                    .append("\\usepackage[linesnumbered,ruled,inoutnumbered]{algorithm2e}\n")
                    .append("\\usepackage{subfigure}\n").append("\\usepackage[hypcap]{caption}\n")
                    .append("\\usepackage{pdflscape}\n").append("\n").append("\\begin{document}\n").append("\n")
                    .append("\\begin{landscape}\n").append("\n");

            pfKnown: {

                latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n")
                        .append("\t\\def\\arraystretch{1.5}\n")
                        //                        .append("\t\\setlength{\\tabcolsep}{10pt}\n")
                        //                        .append("\t\\fontsize{8pt}{10pt}\\selectfont\n")
                        .append("\t\\caption{INDICATOR found for $PF_{known}$ for ").append(objectives)
                        .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives)
                        .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c");

                for (String algorithm : algorithms) {
                    latexTableBuilder.append("c");
                    for (String heuristicFunction : heuristicFunctions) {
                        latexTableBuilder.append("c");
                    }
                }

                latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}");
                for (String algorithm : algorithms) {
                    latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}");
                    for (String heuristicFunction : heuristicFunctions) {
                        latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-")
                                .append(heuristicFunction).append("}");
                    }
                }
                latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n");

                for (String problem : problems) {

                    NonDominatedSolutionList trueFront = new NonDominatedSolutionList();
                    pfTrueComposing: {
                        for (String algorithm : algorithms) {
                            SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet(
                                    "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem
                                            + "_Comb_" + objectives + "obj/All_FUN_"
                                            + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem);
                            trueFront.addAll(mecbaFront);

                            for (String hyperHeuristic : heuristicFunctions) {
                                SolutionSet front = metricsUtil.readNonDominatedSolutionSet(
                                        "experiment/" + algorithm + "/" + objectives + "objectives/"
                                                + hyperHeuristic + "/" + problem + "/FUN.txt");
                                trueFront.addAll(front);
                            }
                        }
                    }
                    double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix();

                    HashMap<String, Double> igdMap = new HashMap<>();
                    HashMap<String, Double> gdMap = new HashMap<>();
                    HashMap<String, Double> spreadMap = new HashMap<>();
                    HashMap<String, Double> coverageMap = new HashMap<>();

                    for (String algorithm : algorithms) {
                        double[][] mecbaFront = metricsUtil
                                .readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/"
                                        + problem + "_Comb_" + objectives + "obj/All_FUN_"
                                        + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem);
                        igdMap.put(algorithm,
                                igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives));
                        gdMap.put(algorithm, gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives));
                        spreadMap.put(algorithm, spread.spread(mecbaFront, trueFrontMatrix, objectives));
                        coverageMap.put(algorithm, coverage.coverage(mecbaFront, trueFrontMatrix));
                        for (String heuristic : heuristicFunctions) {
                            double[][] heuristicFront = metricsUtil.readFront("experiment/" + algorithm + "/"
                                    + objectives + "objectives/" + heuristic + "/" + problem + "/FUN.txt");
                            igdMap.put(algorithm + "-" + heuristic, igd
                                    .invertedGenerationalDistance(heuristicFront, trueFrontMatrix, objectives));
                            gdMap.put(algorithm + "-" + heuristic,
                                    gd.generationalDistance(heuristicFront, trueFrontMatrix, objectives));
                            spreadMap.put(algorithm + "-" + heuristic,
                                    spread.spread(heuristicFront, trueFrontMatrix, objectives));
                            coverageMap.put(algorithm + "-" + heuristic,
                                    coverage.coverage(heuristicFront, trueFrontMatrix));
                        }
                    }

                    latexTableBuilder.append("\t\t").append(problem);

                    String latexTable = latexTableBuilder.toString();

                    latexTableBuilder = new StringBuilder();

                    latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF")
                            .replaceAll("MultiArmedBandit", "MAB");

                    IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD"));
                    spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread"));
                    GDWriter.write(latexTable.replaceAll("INDICATOR", "GD"));
                    coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage"));

                    String bestHeuristicIGD = "NULL";
                    String bestHeuristicGD = "NULL";
                    String bestHeuristicSpread = "NULL";
                    String bestHeuristicCoverage = "NULL";

                    getBest: {
                        double bestMeanIGD = Double.POSITIVE_INFINITY;
                        double bestMeanGD = Double.POSITIVE_INFINITY;
                        double bestMeanSpread = Double.NEGATIVE_INFINITY;
                        double bestMeanCoverage = Double.NEGATIVE_INFINITY;

                        for (String heuristic : igdMap.keySet()) {
                            double heuristicIGD = igdMap.get(heuristic);
                            double heuristicGD = gdMap.get(heuristic);
                            double heuristicSpread = spreadMap.get(heuristic);
                            double heuristicCoverage = coverageMap.get(heuristic);

                            if (heuristicIGD < bestMeanIGD) {
                                bestMeanIGD = heuristicIGD;
                                bestHeuristicIGD = heuristic;
                            }
                            if (heuristicGD < bestMeanGD) {
                                bestMeanGD = heuristicGD;
                                bestHeuristicGD = heuristic;
                            }
                            if (heuristicSpread > bestMeanSpread) {
                                bestMeanSpread = heuristicSpread;
                                bestHeuristicSpread = heuristic;
                            }
                            if (heuristicCoverage > bestMeanCoverage) {
                                bestMeanCoverage = heuristicCoverage;
                                bestHeuristicCoverage = heuristic;
                            }
                        }
                    }

                    StringBuilder igdBuilder = new StringBuilder();
                    StringBuilder gdBuilder = new StringBuilder();
                    StringBuilder spreadBuilder = new StringBuilder();
                    StringBuilder coverageBuilder = new StringBuilder();

                    String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length
                            + algorithms.length];
                    fulfillNewHeuristics: {
                        int i = 0;
                        for (String algorithm : algorithms) {
                            newHeuristicFunctions[i++] = algorithm;
                            for (String heuristicFunction : heuristicFunctions) {
                                newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction;
                            }
                        }
                    }

                    for (String heuristic : newHeuristicFunctions) {
                        igdBuilder.append(" & ");
                        boolean bold = heuristic.equals(bestHeuristicIGD)
                                || igdMap.get(heuristic).equals(igdMap.get(bestHeuristicIGD));
                        if (bold) {
                            igdBuilder.append("\\textbf{");
                        }
                        igdBuilder.append(decimalFormatter.format(igdMap.get(heuristic)));
                        if (bold) {
                            igdBuilder.append("}");
                        }

                        gdBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicGD)
                                || gdMap.get(heuristic).equals(gdMap.get(bestHeuristicGD));
                        if (bold) {
                            gdBuilder.append("\\textbf{");
                        }
                        gdBuilder.append(decimalFormatter.format(gdMap.get(heuristic)));
                        if (bold) {
                            gdBuilder.append("}");
                        }

                        spreadBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicSpread)
                                || spreadMap.get(heuristic).equals(spreadMap.get(bestHeuristicSpread));
                        if (bold) {
                            spreadBuilder.append("\\textbf{");
                        }
                        spreadBuilder.append(decimalFormatter.format(spreadMap.get(heuristic)));
                        if (bold) {
                            spreadBuilder.append("}");
                        }

                        coverageBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicCoverage)
                                || coverageMap.get(heuristic).equals(coverageMap.get(bestHeuristicCoverage));
                        if (bold) {
                            coverageBuilder.append("\\textbf{");
                        }
                        coverageBuilder.append(decimalFormatter.format(coverageMap.get(heuristic)));
                        if (bold) {
                            coverageBuilder.append("}");
                        }
                    }

                    IGDWriter.write(igdBuilder + "\\\\\n");
                    spreadWriter.write(spreadBuilder + "\\\\\n");
                    GDWriter.write(gdBuilder + "\\\\\n");
                    coverageWriter.write(coverageBuilder + "\\\\\n");
                }
                latexTableBuilder = new StringBuilder();

                latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n")
                        .append("\\end{table}\n\n");
            }

            averages: {

                latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n")
                        .append("\t\\def\\arraystretch{1.5}\n")
                        //                        .append("\t\\setlength{\\tabcolsep}{10pt}\n")
                        //                        .append("\t\\fontsize{8pt}{10pt}\\selectfont\n")
                        .append("\t\\caption{INDICATOR averages found for ").append(objectives)
                        .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives)
                        .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c");

                for (String algorithm : algorithms) {
                    latexTableBuilder.append("c");
                    for (String heuristicFunction : heuristicFunctions) {
                        latexTableBuilder.append("c");
                    }
                }

                latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}");
                for (String algorithm : algorithms) {
                    latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}");
                    for (String heuristicFunction : heuristicFunctions) {
                        latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-")
                                .append(heuristicFunction).append("}");
                    }
                }
                latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n");

                for (String problem : problems) {

                    NonDominatedSolutionList trueFront = new NonDominatedSolutionList();
                    pfTrueComposing: {
                        for (String algorithm : algorithms) {
                            SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet(
                                    "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem
                                            + "_Comb_" + objectives + "obj/All_FUN_"
                                            + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem);
                            trueFront.addAll(mecbaFront);

                            for (String hyperHeuristic : heuristicFunctions) {
                                SolutionSet front = metricsUtil.readNonDominatedSolutionSet(
                                        "experiment/" + algorithm + "/" + objectives + "objectives/"
                                                + hyperHeuristic + "/" + problem + "/FUN.txt");
                                trueFront.addAll(front);
                            }
                        }
                    }
                    double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix();

                    HashMap<String, double[]> igdMap = new HashMap<>();
                    HashMap<String, double[]> gdMap = new HashMap<>();
                    HashMap<String, double[]> spreadMap = new HashMap<>();
                    HashMap<String, double[]> coverageMap = new HashMap<>();

                    mocaito: {
                        for (String algorithm : algorithms) {
                            double[] mecbaIGDs = new double[EXECUTIONS];
                            double[] mecbaGDs = new double[EXECUTIONS];
                            double[] mecbaSpreads = new double[EXECUTIONS];
                            double[] mecbaCoverages = new double[EXECUTIONS];
                            for (int i = 0; i < EXECUTIONS; i++) {
                                double[][] mecbaFront = metricsUtil.readFront("resultado/"
                                        + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_"
                                        + objectives + "obj/FUN_" + algorithm.toLowerCase().replaceAll("-", "")
                                        + "-" + problem + "-" + i + ".NaoDominadas");

                                mecbaIGDs[i] = igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix,
                                        objectives);
                                mecbaGDs[i] = gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives);
                                mecbaSpreads[i] = spread.spread(mecbaFront, trueFrontMatrix, objectives);
                                mecbaCoverages[i] = coverage.coverage(mecbaFront, trueFrontMatrix);
                            }
                            igdMap.put(algorithm, mecbaIGDs);
                            gdMap.put(algorithm, mecbaGDs);
                            spreadMap.put(algorithm, mecbaSpreads);
                            coverageMap.put(algorithm, mecbaCoverages);
                        }
                    }

                    for (String algorithm : algorithms) {
                        for (String heuristic : heuristicFunctions) {
                            double[] hhIGDs = new double[EXECUTIONS];
                            double[] hhGDs = new double[EXECUTIONS];
                            double[] hhSpreads = new double[EXECUTIONS];
                            double[] hhCoverages = new double[EXECUTIONS];
                            for (int i = 0; i < EXECUTIONS; i++) {
                                double[][] hhFront = metricsUtil
                                        .readFront("experiment/" + algorithm + "/" + objectives + "objectives/"
                                                + heuristic + "/" + problem + "/EXECUTION_" + i + "/FUN.txt");

                                hhIGDs[i] = igd.invertedGenerationalDistance(hhFront, trueFrontMatrix,
                                        objectives);
                                hhGDs[i] = gd.generationalDistance(hhFront, trueFrontMatrix, objectives);
                                hhSpreads[i] = spread.spread(hhFront, trueFrontMatrix, objectives);
                                hhCoverages[i] = coverage.coverage(hhFront, trueFrontMatrix);
                            }
                            igdMap.put(algorithm + "-" + heuristic, hhIGDs);
                            gdMap.put(algorithm + "-" + heuristic, hhGDs);
                            spreadMap.put(algorithm + "-" + heuristic, hhSpreads);
                            coverageMap.put(algorithm + "-" + heuristic, hhCoverages);
                        }
                    }

                    HashMap<String, HashMap<String, Boolean>> igdResult = KruskalWallisTest.test(igdMap);
                    HashMap<String, HashMap<String, Boolean>> gdResult = KruskalWallisTest.test(gdMap);
                    HashMap<String, HashMap<String, Boolean>> spreadResult = KruskalWallisTest.test(spreadMap);
                    HashMap<String, HashMap<String, Boolean>> coverageResult = KruskalWallisTest
                            .test(coverageMap);

                    latexTableBuilder.append("\t\t").append(problem);

                    String latexTable = latexTableBuilder.toString();
                    latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF")
                            .replaceAll("MultiArmedBandit", "MAB");

                    IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD"));
                    spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread"));
                    GDWriter.write(latexTable.replaceAll("INDICATOR", "GD"));
                    coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage"));

                    latexTableBuilder = new StringBuilder();

                    String bestHeuristicIGD = "NULL";
                    String bestHeuristicGD = "NULL";
                    String bestHeuristicSpread = "NULL";
                    String bestHeuristicCoverage = "NULL";

                    getBest: {
                        double bestMeanIGD = Double.POSITIVE_INFINITY;
                        double bestMeanGD = Double.POSITIVE_INFINITY;
                        double bestMeanSpread = Double.NEGATIVE_INFINITY;
                        double bestMeanCoverage = Double.NEGATIVE_INFINITY;

                        for (String heuristic : igdMap.keySet()) {
                            double heuristicMeanIGD = mean.evaluate(igdMap.get(heuristic));
                            double heuristicMeanGD = mean.evaluate(gdMap.get(heuristic));
                            double heuristicMeanSpread = mean.evaluate(spreadMap.get(heuristic));
                            double heuristicMeanCoverage = mean.evaluate(coverageMap.get(heuristic));

                            if (heuristicMeanIGD < bestMeanIGD) {
                                bestMeanIGD = heuristicMeanIGD;
                                bestHeuristicIGD = heuristic;
                            }
                            if (heuristicMeanGD < bestMeanGD) {
                                bestMeanGD = heuristicMeanGD;
                                bestHeuristicGD = heuristic;
                            }
                            if (heuristicMeanSpread > bestMeanSpread) {
                                bestMeanSpread = heuristicMeanSpread;
                                bestHeuristicSpread = heuristic;
                            }
                            if (heuristicMeanCoverage > bestMeanCoverage) {
                                bestMeanCoverage = heuristicMeanCoverage;
                                bestHeuristicCoverage = heuristic;
                            }
                        }
                    }

                    StringBuilder igdBuilder = new StringBuilder();
                    StringBuilder gdBuilder = new StringBuilder();
                    StringBuilder spreadBuilder = new StringBuilder();
                    StringBuilder coverageBuilder = new StringBuilder();

                    String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length
                            + algorithms.length];
                    fulfillNewHeuristics: {
                        int i = 0;
                        for (String algorithm : algorithms) {
                            newHeuristicFunctions[i++] = algorithm;
                            for (String heuristicFunction : heuristicFunctions) {
                                newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction;
                            }
                        }
                    }

                    for (String heuristic : newHeuristicFunctions) {
                        igdBuilder.append(" & ");
                        boolean bold = heuristic.equals(bestHeuristicIGD)
                                || !igdResult.get(heuristic).get(bestHeuristicIGD);
                        if (bold) {
                            igdBuilder.append("\\textbf{");
                        }
                        igdBuilder.append(decimalFormatter.format(mean.evaluate(igdMap.get(heuristic))) + " ("
                                + decimalFormatter.format(standardDeviation.evaluate(igdMap.get(heuristic)))
                                + ")");
                        if (bold) {
                            igdBuilder.append("}");
                        }

                        gdBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicGD)
                                || !gdResult.get(heuristic).get(bestHeuristicGD);
                        if (bold) {
                            gdBuilder.append("\\textbf{");
                        }
                        gdBuilder.append(decimalFormatter.format(mean.evaluate(gdMap.get(heuristic))) + " ("
                                + decimalFormatter.format(standardDeviation.evaluate(gdMap.get(heuristic)))
                                + ")");
                        if (bold) {
                            gdBuilder.append("}");
                        }

                        spreadBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicSpread)
                                || !spreadResult.get(heuristic).get(bestHeuristicSpread);
                        if (bold) {
                            spreadBuilder.append("\\textbf{");
                        }
                        spreadBuilder.append(decimalFormatter.format(mean.evaluate(spreadMap.get(heuristic)))
                                + " ("
                                + decimalFormatter.format(standardDeviation.evaluate(spreadMap.get(heuristic)))
                                + ")");
                        if (bold) {
                            spreadBuilder.append("}");
                        }

                        coverageBuilder.append(" & ");
                        bold = heuristic.equals(bestHeuristicCoverage)
                                || !coverageResult.get(heuristic).get(bestHeuristicCoverage);
                        if (bold) {
                            coverageBuilder.append("\\textbf{");
                        }
                        coverageBuilder
                                .append(decimalFormatter.format(mean.evaluate(coverageMap.get(heuristic))))
                                .append(" (")
                                .append(decimalFormatter
                                        .format(standardDeviation.evaluate(coverageMap.get(heuristic))))
                                .append(")");
                        if (bold) {
                            coverageBuilder.append("}");
                        }
                    }

                    IGDWriter.write(igdBuilder + "\\\\\n");
                    spreadWriter.write(spreadBuilder + "\\\\\n");
                    GDWriter.write(gdBuilder + "\\\\\n");
                    coverageWriter.write(coverageBuilder + "\\\\\n");
                }
                latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n")
                        .append("\\end{table}\n\n");
            }

            latexTableBuilder.append("\\end{landscape}\n\n").append("\\end{document}");

            String latexTable = latexTableBuilder.toString();

            IGDWriter.write(latexTable);
            spreadWriter.write(latexTable);
            GDWriter.write(latexTable);
            coverageWriter.write(latexTable);
        }
    }
}

From source file:de.prozesskraft.pkraft.Startinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file//from  w ww.j a va  2 s . com
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/"
            + "../etc/pkraft-startinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option obasedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[optional, default .] base directory where instance shourd run.")
            //            .isRequired()
            .create("basedir");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[optional] definition file of the process you want to start an instance from.")
            //            .isRequired()
            .create("definition");

    Option onostart = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] oppresses the start of the instance. (only create the process-instance)")
            //            .isRequired()
            .create("nostart");

    Option opdomain = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] domain of the process (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pdomain");

    Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pname");

    Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pversion");

    Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg()
            .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.")
            //            .isRequired()
            .create("commitfile");

    Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg()
            .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE")
            //            .isRequired()
            .create("commitvariable");

    Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription(
            "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitfiledummy");

    Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription(
            "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitvariabledummy");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(obasedir);
    options.addOption(odefinition);
    options.addOption(onostart);
    options.addOption(opname);
    options.addOption(opversion);
    options.addOption(ocommitfile);
    options.addOption(ocommitvariable);
    options.addOption(ocommitfiledummy);
    options.addOption(ocommitvariabledummy);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("startinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition")) && (!(commandline.hasOption("pname"))
            || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion"))
            || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) {
        System.err.println("you must not use option -definition with -pversion or -pname or -pdomain");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process p1 = new Process();
    String pathToDefinition = "";

    if (commandline.hasOption("definition")) {
        pathToDefinition = commandline.getOptionValue("definition");
    } else if (commandline.hasOption("pname") && commandline.hasOption("pversion")
            && commandline.hasOption("pdomain")) {
        pathToDefinition.replaceAll("/+$", "");
        pathToDefinition = ini.get("process", "domain-installation-directory") + "/"
                + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/"
                + commandline.getOptionValue("pversion") + "/process.xml";
    } else {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert
    java.io.File xmlDefinition = new java.io.File(pathToDefinition);
    if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) {
        System.err.println("process definition does not exist: " + pathToDefinition);
        exiter();
    }

    p1.setInfilexml(xmlDefinition.getCanonicalPath());
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e1) {
        System.err.println(e1.getMessage());
    }

    // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will
    // root-verzeichnis erstellen
    if (commandline.hasOption("basedir")) {
        p2.setBaseDir(commandline.getOptionValue("basedir"));
    }

    p2.makeRootdir();

    // den pfad fuers binary setzen
    p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    // step, an den die commits gehen, soll 'root' sein.
    Step stepRoot = p2.getRootStep();

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfile")) {
        for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) {
            String[] parts = actOptionCommitfile.split("=");
            File userFile = new File();

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfile " + actOptionCommitfile);
                exiter();
            }

            // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
            // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
            for (Commit actCommit : stepRoot.getCommit()) {
                // alle files des aktuellen commits
                for (File actFile : actCommit.getFile()) {
                    if (actFile.getKey().equals(userFile.getKey())) {
                        // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                        if (actFile.getGlob() != null) {
                            // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                            if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) {
                                File newFile = actFile.clone();
                                newFile.setGlob(userFile.getGlob());
                                System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                        + newFile.getKey() + "=" + newFile.getGlob() + ")");
                                actCommit.addFile(newFile);
                                break;
                            } else {
                                System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " "
                                        + actFile.getKey() + "-files into commit " + actCommit.getName());
                                exiter();
                            }
                        }
                        // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                        else {
                            actFile.setGlob(userFile.getGlob());
                            actFile.setGlobdir(p2.getBaseDir());
                            System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                    + actFile.getKey() + "=" + actFile.getGlob() + ")");
                            break;
                        }
                    }
                }
            }
        }
    }

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfiledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitFiledummy = new Commit();
        commitFiledummy.setName("fileDummy");
        stepRoot.addCommit(commitFiledummy);

        for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) {
            String[] parts = actOptionCommitfiledummy.split("=");
            File userFile = new File();
            commitFiledummy.addFile(userFile);

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy);
                exiter();
            }
            userFile.setGlobdir(p2.getBaseDir());
            System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' ("
                    + userFile.getKey() + "=" + userFile.getGlob() + ")");
        }
    }

    if (commandline.hasOption("commitvariable")) {
        for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) {
            if (actOptionCommitvariable.matches(".+=.+")) {
                String[] parts = actOptionCommitvariable.split("=");
                Variable userVariable = new Variable();

                if (parts.length == 1) {
                    userVariable.setKey("default");
                    userVariable.setValue(parts[0]);
                } else if (parts.length == 2) {
                    userVariable.setKey(parts[0]);
                    userVariable.setValue(parts[1]);
                } else {
                    System.err.println("error in option -commitvariable");
                    exiter();
                }
                //                  commit.addVariable(variable);

                // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
                // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
                for (Commit actCommit : stepRoot.getCommit()) {
                    // alle files des aktuellen commits
                    for (Variable actVariable : actCommit.getVariable()) {
                        if (actVariable.getKey().equals(userVariable.getKey())) {
                            // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                            if (actVariable.getGlob() != null) {
                                // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                                if (actCommit.getVariable(actVariable.getKey()).size() < actVariable
                                        .getMaxoccur()) {
                                    Variable newVariable = actVariable.clone();
                                    newVariable.setValue(userVariable.getValue());
                                    System.err.println("entering variable into commit '" + actCommit.getName()
                                            + "' (" + newVariable.getKey() + "=" + newVariable.getValue()
                                            + ")");
                                    actCommit.addVariable(newVariable);
                                    break;
                                } else {
                                    System.err.println("fatal: you only may commit " + actVariable.getMaxoccur()
                                            + " " + actVariable.getKey() + "-variable(s) into commit "
                                            + actCommit.getName());
                                    exiter();
                                }
                            }
                            // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                            else {
                                actVariable.setValue(userVariable.getValue());
                                System.err.println("entering variable into commit '" + actCommit.getName()
                                        + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")");
                                break;
                            }
                        }
                    }
                }
            } else {
                System.err.println("-commitvariable " + actOptionCommitvariable
                        + " does not match pattern \"NAME=VALUE\".");
                exiter();
            }

        }
    }

    if (commandline.hasOption("commitvariabledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitVariabledummy = new Commit();
        commitVariabledummy.setName("variableDummy");
        stepRoot.addCommit(commitVariabledummy);

        for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) {
            String[] parts = actOptionCommitvariabledummy.split("=");
            Variable userVariable = new Variable();
            commitVariabledummy.addVariable(userVariable);

            if (parts.length == 1) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[0]);
            } else if (parts.length == 2) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[1]);
            } else {
                System.err.println("error in option -commitvariabledummy");
                exiter();
            }

            System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' ("
                    + userVariable.getKey() + "=" + userVariable.getValue() + ")");
        }
    }

    //      if (commandline.hasOption("basedir"))
    //      {
    //         p2.setBaseDir(commandline.getOptionValue("basedir"));
    //      }

    //         commit.doIt();
    stepRoot.commit();

    // root-verzeichnis erstellen
    p2.makeRootdir();

    // den pfad fuers binary setzen
    //      p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    try {
        Thread.sleep(1500, 0);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //         Runtime.getRuntime().exec("process-manager -help");

    // starten nur, falls es nicht abgewaehlt wurde
    if (!commandline.hasOption("nostart")) {
        System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary());
        String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary();
        System.err.println("calling: " + aufrufString);

        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(aufrufString.split(" ")));

        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        //      ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary());
        //      Map<String,String> env = pb.environment();
        //      String path = env.get("PATH");
        //      System.out.println("PATH: "+path);
        //      
        java.lang.Process p = pb.start();
        System.err.println("pid: " + p.hashCode());
    } else {
        System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary());
    }

}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitivePrimitive.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];//from   w w  w  .  jav  a2 s .  c o  m
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[3];
    //Class name (no packages) of the Key class Ex. String
    String K = args[4];
    //Class name (no packages) of the value class Ex. Integer
    String V = args[5];

    String kCls = K;
    String vCls = V;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }
    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = kCls + vCls + "Map"; //Default
    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/JavaLangBasedMapTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#VCLS#", vCls);

        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorWritableKeyPrimitiveValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];/*from   w  w  w . j a  va  2  s  .  c  o m*/
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[3];
    //Class name (no packages) of the Key class Ex. String
    String K = args[4];
    //Class name (no packages) of the value class Ex. Integer
    String V = args[5];
    String kCls = K;
    String vCls = V;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }
    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = kCls + vCls + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(new File(
                root.getAbsolutePath() + "/src/main/resources/WritableKeyPrimitiveValueMapTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#VCLS#", vCls);

        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorWritableKeyWritableValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];// ww  w  . j  ava2 s . c om
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[3];
    //Class name (no packages) of the Key class Ex. String
    String K = args[4];
    //Class name (no packages) of the value class Ex. Integer
    String V = args[5];
    String kCls = K;
    String vCls = V;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }
    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = kCls + vCls + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(new File(
                root.getAbsolutePath() + "/src/main/resources/WritableKeyWritableValueMapTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#VCLS#", vCls);

        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveKeyWritableValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];//from w  ww  .j ava2 s. co  m
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[3];
    //Class name (no packages) of the Key class Ex. String
    String K = args[4];
    //Class name (no packages) of the value class Ex. Integer
    String V = args[5];
    String vWritableCls = args[6];
    String kCls = K;
    String vCls = V;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }
    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = kCls + vCls + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(new File(
                root.getAbsolutePath() + "/src/main/resources/PrimitiveKeyWritableValueMapTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#VCLS#", vCls);
        program = program.replaceAll("#VWRITABLECLS#", vWritableCls);
        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveKeyKryoValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];//ww  w .  j a  va  2 s .c  om
    //Class name (no packages) of the Key class Ex. String
    //Class name (no packages) of the value class Ex. Integer
    String K = args[3];
    //Specify if you are using a KryoTemplate to generate your classes
    //If true the template used to generate the class is KryoBasedMapTemplte, if false the JavaLangBasedMapTemplate is used
    //You can customize the name of the class generated
    String kCls = K;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }

    String CLASS_NAME = kCls + "KryoV" + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }
        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/PrimitiveKeyKryoValueMapTemplate.java"));
        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorKryoKPrimitiveValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[2];/*from ww  w.j a  v a2s  . c o m*/
    //Class name (no packages) of the Key class Ex. String
    //Class name (no packages) of the value class Ex. Integer
    String V = args[3];
    //Specify if you are using a KryoTemplate to generate your classes
    //If true the template used to generate the class is KryoBasedMapTemplte, if false the JavaLangBasedMapTemplate is used
    //You can customize the name of the class generated
    String vCls = V;

    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = "KryoK" + vCls + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }
        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/KryoKeyPrimitiveValueMapTemplate.java"));
        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);

        program = program.replaceAll("#VCLS#", vCls);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:json_to_xml_1.java

public static void main(String args[]) {
    System.out.print("json_to_xml_1 workflow Copyright (C) 2016 Stephan Kreutzer\n"
            + "This program comes with ABSOLUTELY NO WARRANTY.\n"
            + "This is free software, and you are welcome to redistribute it\n"
            + "under certain conditions. See the GNU Affero General Public License 3\n"
            + "or any later version for details. Also, see the source code repository\n"
            + "https://github.com/publishing-systems/digital_publishing_workflow_tools/ and\n"
            + "the project website http://www.publishing-systems.org.\n\n");

    json_to_xml_1 converter = json_to_xml_1.getInstance();

    converter.getInfoMessages().clear();

    try {//from ww  w .ja va  2  s  .  c om
        converter.execute(args);
    } catch (ProgramTerminationException ex) {
        converter.handleTermination(ex);
    }

    if (converter.resultInfoFile != null) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(converter.resultInfoFile), "UTF-8"));

            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write(
                    "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n");
            writer.write("<json-to-xml-1-result-information>\n");

            if (converter.getInfoMessages().size() <= 0) {
                writer.write("  <success/>\n");
            } else {
                writer.write("  <success>\n");
                writer.write("    <info-messages>\n");

                for (int i = 0, max = converter.getInfoMessages().size(); i < max; i++) {
                    InfoMessage infoMessage = converter.getInfoMessages().get(i);

                    writer.write("      <info-message number=\"" + i + "\">\n");
                    writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                    String infoMessageText = infoMessage.getMessage();
                    String infoMessageId = infoMessage.getId();
                    String infoMessageBundle = infoMessage.getBundle();
                    Object[] infoMessageArguments = infoMessage.getArguments();

                    if (infoMessageBundle != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                        infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                        infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                        writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                    }

                    if (infoMessageId != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                        infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                        infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                        writer.write("        <id>" + infoMessageId + "</id>\n");
                    }

                    if (infoMessageText != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                        infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                        infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                        writer.write("        <message>" + infoMessageText + "</message>\n");
                    }

                    if (infoMessageArguments != null) {
                        writer.write("        <arguments>\n");

                        int argumentCount = infoMessageArguments.length;

                        for (int j = 0; j < argumentCount; j++) {
                            if (infoMessageArguments[j] == null) {
                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class></class>\n");
                                writer.write("            <value>null</value>\n");
                                writer.write("          </argument>\n");

                                continue;
                            }

                            String className = infoMessageArguments[j].getClass().getName();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            className = className.replaceAll("&", "&amp;");
                            className = className.replaceAll("<", "&lt;");
                            className = className.replaceAll(">", "&gt;");

                            String value = infoMessageArguments[j].toString();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            value = value.replaceAll("&", "&amp;");
                            value = value.replaceAll("<", "&lt;");
                            value = value.replaceAll(">", "&gt;");

                            writer.write("          <argument number=\"" + j + "\">\n");
                            writer.write("            <class>" + className + "</class>\n");
                            writer.write("            <value>" + value + "</value>\n");
                            writer.write("          </argument>\n");
                        }

                        writer.write("        </arguments>\n");
                    }

                    Exception exception = infoMessage.getException();

                    if (exception != null) {
                        writer.write("        <exception>\n");

                        String className = exception.getClass().getName();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        className = className.replaceAll("&", "&amp;");
                        className = className.replaceAll("<", "&lt;");
                        className = className.replaceAll(">", "&gt;");

                        writer.write("          <class>" + className + "</class>\n");

                        StringWriter stringWriter = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(stringWriter);
                        exception.printStackTrace(printWriter);
                        String stackTrace = stringWriter.toString();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        stackTrace = stackTrace.replaceAll("&", "&amp;");
                        stackTrace = stackTrace.replaceAll("<", "&lt;");
                        stackTrace = stackTrace.replaceAll(">", "&gt;");

                        writer.write("          <stack-trace>" + stackTrace + "</stack-trace>\n");
                        writer.write("        </exception>\n");
                    }

                    writer.write("      </info-message>\n");
                }

                writer.write("    </info-messages>\n");
                writer.write("  </success>\n");
            }

            writer.write("</json-to-xml-1-result-information>\n");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    converter.getInfoMessages().clear();
    converter.resultInfoFile = null;
}