Example usage for java.io StringWriter toString

List of usage examples for java.io StringWriter toString

Introduction

In this page you can find the example usage for java.io StringWriter toString.

Prototype

public String toString() 

Source Link

Document

Return the buffer's current value as a string.

Usage

From source file:Anaphora_Resolution.ParseAllXMLDocuments.java

public static void main(String[] args)
        throws IOException, SAXException, ParserConfigurationException, TransformerException {
    //      File dataFolder = new File("DataToPort");
    //      File[] documents;
    String grammar = "grammar/englishPCFG.ser.gz";
    String[] options = { "-maxLength", "100", "-retainTmpSubcategories" };
    //LexicalizedParser lp =  new LexicalizedParser(grammar, options);
    LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz");
    ////w ww.jav a2  s .c o m
    //      if (dataFolder.isDirectory()) {
    //          documents = dataFolder.listFiles();
    //      } else {
    //          documents = new File[] {dataFolder};
    //      }
    //      int currfile = 0;
    //      int totfiles = documents.length;
    //      for (File paper : documents) {
    //          currfile++;
    //          if (paper.getName().equals(".DS_Store")||paper.getName().equals(".xml")) {
    //              currfile--;
    //              totfiles--;
    //              continue;
    //          }
    //          System.out.println("Working on "+paper.getName()+" (file "+currfile+" out of "+totfiles+").");
    //
    //          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // This is for XML
    //          DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    //          Document doc = docBuilder.parse(paper.getAbsolutePath());
    //
    //          NodeList textlist = doc.getElementsByTagName("text");
    //          for(int i=0; i < textlist.getLength(); i++) {
    //              Node currentnode = textlist.item(i);
    //              String wholetext = textlist.item(i).getTextContent();
    String wholetext = "How about other changes for example the ways of doing the work and \n" + "\n"
            + "Iwould say security has , there 's more pressure put on people now than there used to be because obviously , especially after Locherbie , they tightened up on security and there 's a lot more pressure now especially from the ETR and stuff like that \n"
            + "People do n't feel valued any more , they feel  I do n't know I think they feel that nobody cares about them really anyway \n";

    //System.out.println(wholetext);
    //Iterable<List<? extends HasWord>> sentences;

    ArrayList<Tree> parseTrees = new ArrayList<Tree>();
    String asd = "";
    int j = 0;
    StringReader stringreader = new StringReader(wholetext);
    DocumentPreprocessor dp = new DocumentPreprocessor(stringreader);
    @SuppressWarnings("rawtypes")
    ArrayList<List> sentences = preprocess(dp);
    for (List sentence : sentences) {
        parseTrees.add(lp.apply(sentence)); // Parsing a new sentence and adding it to the parsed tree
        ArrayList<Tree> PronounsList = findPronouns(parseTrees.get(j)); // Locating all pronouns to resolve in the sentence
        Tree corefedTree;
        for (Tree pronounTree : PronounsList) {
            parseTrees.set(parseTrees.size() - 1, HobbsResolve(pronounTree, parseTrees)); // Resolving the coref and modifying the tree for each pronoun
        }
        StringWriter strwr = new StringWriter();
        PrintWriter prwr = new PrintWriter(strwr);
        TreePrint tp = new TreePrint("penn");
        tp.printTree(parseTrees.get(j), prwr);
        prwr.flush();
        asd += strwr.toString();
        j++;
    }
    String armando = "";
    for (Tree sentence : parseTrees) {
        for (Tree leaf : Trees.leaves(sentence))
            armando += leaf + " ";
    }
    System.out.println(wholetext);

    System.out.println();
    System.out.println("......");
    System.out.println(armando);
    System.out.println("All done.");
    //              currentnode.setTextContent(asd);
    //          }
    //          TransformerFactory transformerFactory = TransformerFactory.newInstance();
    //          Transformer transformer = transformerFactory.newTransformer();
    //          DOMSource source = new DOMSource(doc);
    //          StreamResult result = new StreamResult(paper);
    //          transformer.transform(source, result);
    //
    //          System.out.println("Done");
    //      }
}

From source file:de.uni.bremen.monty.moco.Main.java

public static void main(String[] args) throws IOException, InterruptedException {
    Namespace ns = parseArgs(args);

    if (ns == null) {
        return;/* w w w .ja va2s  . c o m*/
    }

    String inputFileName = ns.get("file");
    String outputFileName = ns.get("outputFile");
    boolean emitAssembly = ns.get("emitAssembly");
    boolean compileOnly = ns.get("compileOnly");
    boolean stopOnFirstError = ns.get("stopOnFirstError");
    boolean printAST = ns.get("printAST");
    boolean debugParseTree = ns.get("debugParseTree");

    if (debugParseTree) {
        debugParseTree(inputFileName);
        return;
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(Main.class.getResourceAsStream("/std_llvm_include.ll"), writer);

    Package ast = buildPackage(inputFileName);

    if (!visitVisitors(ast, stopOnFirstError, writer.getBuffer())) {
        return;
    }

    if (printAST) {
        (new PrintVisitor()).visitDoubleDispatched(ast);
    }

    if (emitAssembly) {
        writeAssembly(outputFileName, inputFileName, writer.toString());
        return;
    }

    File executable = buildExecutable(outputFileName, inputFileName, compileOnly, writer.toString());
    if (!compileOnly) {
        runExecutable(executable);
    }
}

From source file:com.yahoo.labs.samoa.topology.impl.StormTopologySubmitter.java

public static void main(String[] args) throws IOException {
    Properties props = StormSamoaUtils.getProperties();

    String uploadedJarLocation = props.getProperty(StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
    if (uploadedJarLocation == null) {
        logger.error("Invalid properties file. It must have key {}",
                StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
        return;//from w w  w. j a  v  a  2 s.co m
    }

    List<String> tmpArgs = new ArrayList<String>(Arrays.asList(args));
    int numWorkers = StormSamoaUtils.numWorkers(tmpArgs);

    args = tmpArgs.toArray(new String[0]);
    StormTopology stormTopo = StormSamoaUtils.argsToTopology(args);

    Config conf = new Config();
    conf.putAll(Utils.readStormConfig());
    conf.putAll(Utils.readCommandLineOpts());
    conf.setDebug(false);
    conf.setNumWorkers(numWorkers);

    String profilerOption = props.getProperty(StormTopologySubmitter.YJP_OPTIONS_KEY);
    if (profilerOption != null) {
        String topoWorkerChildOpts = (String) conf.get(Config.TOPOLOGY_WORKER_CHILDOPTS);
        StringBuilder optionBuilder = new StringBuilder();
        if (topoWorkerChildOpts != null) {
            optionBuilder.append(topoWorkerChildOpts);
            optionBuilder.append(' ');
        }
        optionBuilder.append(profilerOption);
        conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, optionBuilder.toString());
    }

    Map<String, Object> myConfigMap = new HashMap<String, Object>(conf);
    StringWriter out = new StringWriter();

    try {
        JSONValue.writeJSONString(myConfigMap, out);
    } catch (IOException e) {
        System.out.println("Error in writing JSONString");
        e.printStackTrace();
        return;
    }

    Config config = new Config();
    config.putAll(Utils.readStormConfig());

    String nimbusHost = (String) config.get(Config.NIMBUS_HOST);

    NimbusClient nc = new NimbusClient(nimbusHost);
    String topologyName = stormTopo.getTopologyName();
    try {
        System.out.println("Submitting topology with name: " + topologyName);
        nc.getClient().submitTopology(topologyName, uploadedJarLocation, out.toString(),
                stormTopo.getStormBuilder().createTopology());
        System.out.println(topologyName + " is successfully submitted");

    } catch (AlreadyAliveException aae) {
        System.out.println("Fail to submit " + topologyName + "\nError message: " + aae.get_msg());
    } catch (InvalidTopologyException ite) {
        System.out.println("Invalid topology for " + topologyName);
        ite.printStackTrace();
    } catch (TException te) {
        System.out.println("Texception for " + topologyName);
        te.printStackTrace();
    }
}

From source file:com.virtualparadigm.packman.processor.JPackageManagerBU.java

public static void main(String[] args) {
    //       StringTemplate templ = new StringTemplate("foo $fo$bo$r$ yo");
    //       templ.setAttribute("success", "foobar");
    //       templ.setAttribute("bo", "oba");
    //        System.out.println(templ.toString());

    try {//from  w  w w.j a v a2  s  .co  m
        //           StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        String firstTemplate = "firstTemplate";
        String content = "this should ${foobar} ${foo:bar.0.1}";
        String updatedContent = "this should ${foobar} #{foo:bar.0.1}";
        //           String content = "this should ${foo:bar}";

        //           System.out.println(content.matches("\\$\\{.*\\:.*\\}"));

        //           System.out.println(content.replaceAll("\\$\\{.*\\:.*\\}", "hahaha"));
        //           System.out.println(content.replaceAll("(\\$\\{.*)(\\:)(.*\\})", "$1-$3"));
        //           System.out.println(content.replaceAll("(\\$\\{.*)(\\:)(.*\\})", "$1-$3"));
        //           System.out.println(content.replaceAll("(\\$)(\\{.*)(\\:)(.*\\})", "#$2$3$4"));
        System.out.println(updatedContent.replaceAll("(#)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})", "\\$$2$3$4$5$6"));
        System.out.println(content.replaceAll("(\\$)(\\{)(.*)(\\:)(.*)(\\})", "--$2$3$4$5$6--"));
        System.out.println(content.replaceAll("(\\$)(\\{\\w*\\:\\w*\\})", "#$2"));

        //           stringTemplateLoader.putTemplate(firstTemplate, "this should ${foobar} ${foo:bar}");
        //           
        //            freemarker.template.Configuration freeMarkerConfiguration = new freemarker.template.Configuration();
        //            freeMarkerConfiguration.setTemplateLoader(stringTemplateLoader);
        //           Template template = freeMarkerConfiguration.getTemplate(firstTemplate);           
        //            Map<String, Object> valueMap = new HashMap<String, Object>();
        //            valueMap.put("foobar", "helloworld");
        //            
        //            Writer out = new OutputStreamWriter(System.out);
        //            template.process(valueMap, out);
        //            out.flush();
        //            
        //            freeMarkerConfiguration.clearTemplateCache();

    } catch (Exception e) {
        e.printStackTrace();
    }

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

    VelocityEngine velocityEngine = new VelocityEngine();
    Properties vProps = new Properties();
    //      vProps.put("file.resource.loader.path", "");
    vProps.setProperty("resource.loader", "string");
    vProps.setProperty("string.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    velocityEngine.init(vProps);
    Template template = null;
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("bo", "oba");
    velocityContext.put("foobar", "be replaced");

    try {
        StringResourceRepository repository = StringResourceLoader.getRepository();
        repository.putStringResource("template", FileUtils.readFileToString(
                new File("c:/dev/workbench/paradigm_workspace/jpackage-manager/template.xml")));
        StringWriter writer = new StringWriter();
        template = velocityEngine.getTemplate("template");
        template.merge(velocityContext, writer);
        System.out.println(writer.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:Service.java

public static void main(String[] args) {

    StringWriter sw = new StringWriter();
    try {//ww  w.  ja  va  2 s .c  o m
        JsonGenerator g = factory.createGenerator(sw);
        g.writeStartObject();
        g.writeNumberField("code", 200);
        g.writeArrayFieldStart("languages");
        for (Language l : Languages.get()) {
            g.writeStartObject();
            g.writeStringField("name", l.getName());
            g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString());
            g.writeEndObject();
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String languagesResponse = sw.toString();

    String errorResponse = codeResponse(500);
    String okResponse = codeResponse(200);

    Scanner sc = new Scanner(System.in);
    while (sc.hasNextLine()) {
        try {
            String line = sc.nextLine();
            JsonParser p = factory.createParser(line);
            String cmd = "";
            String text = "";
            String language = "";
            while (p.nextToken() != JsonToken.END_OBJECT) {
                String name = p.getCurrentName();
                if ("command".equals(name)) {
                    p.nextToken();
                    cmd = p.getText();
                }
                if ("text".equals(name)) {
                    p.nextToken();
                    text = p.getText();
                }
                if ("language".equals(name)) {
                    p.nextToken();
                    language = p.getText();
                }
            }
            p.close();

            if ("check".equals(cmd)) {
                sw = new StringWriter();
                JsonGenerator g = factory.createGenerator(sw);
                g.writeStartObject();
                g.writeNumberField("code", 200);
                g.writeArrayFieldStart("matches");
                for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language))
                        .check(text)) {
                    g.writeStartObject();

                    g.writeNumberField("offset", match.getFromPos());

                    g.writeNumberField("length", match.getToPos() - match.getFromPos());

                    g.writeStringField("message", substituteSuggestion(match.getMessage()));

                    if (match.getShortMessage() != null) {
                        g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage()));
                    }

                    g.writeArrayFieldStart("replacements");
                    for (String replacement : match.getSuggestedReplacements()) {
                        g.writeString(replacement);
                    }
                    g.writeEndArray();

                    Rule rule = match.getRule();

                    g.writeStringField("ruleId", rule.getId());

                    if (rule instanceof AbstractPatternRule) {
                        String subId = ((AbstractPatternRule) rule).getSubId();
                        if (subId != null) {
                            g.writeStringField("ruleSubId", subId);
                        }
                    }

                    g.writeStringField("ruleDescription", rule.getDescription());

                    g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString());

                    if (rule.getUrl() != null) {
                        g.writeArrayFieldStart("ruleUrls");
                        g.writeString(rule.getUrl().toString());
                        g.writeEndArray();
                    }

                    Category category = rule.getCategory();
                    CategoryId catId = category.getId();
                    if (catId != null) {
                        g.writeStringField("ruleCategoryId", catId.toString());

                        g.writeStringField("ruleCategoryName", category.getName());
                    }

                    g.writeEndObject();
                }
                g.writeEndArray();
                g.writeEndObject();
                g.flush();
                System.out.println(sw.toString());
            } else if ("languages".equals(cmd)) {
                System.out.println(languagesResponse);
            } else if ("quit".equals(cmd)) {
                System.out.println(okResponse);
                return;
            } else {
                System.out.println(errorResponse);
            }
        } catch (Exception e) {
            System.out.println(errorResponse);
        }
    }
}

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 {/* w  ww  . j  a  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;
}

From source file:gobblin.runtime.util.JobStateToJsonConverter.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    Option sysConfigOption = Option.builder("sc").argName("system configuration file")
            .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build();
    Option storeUrlOption = Option.builder("u").argName("gobblin state store URL")
            .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build();
    Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name")
            .longOpt("name").hasArgs().required().build();
    Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id")
            .hasArgs().build();//from  w w w  .  j  a v a 2s .c  o  m
    Option convertAllOption = Option.builder("a")
            .desc("Whether to convert all past job states of the given job").longOpt("all").build();
    Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties")
            .longOpt("keepConfig").build();
    Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name")
            .longOpt("toFile").hasArgs().build();

    Options options = new Options();
    options.addOption(sysConfigOption);
    options.addOption(storeUrlOption);
    options.addOption(jobNameOption);
    options.addOption(jobIdOption);
    options.addOption(convertAllOption);
    options.addOption(keepConfigOption);
    options.addOption(outputToFile);

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    Properties sysConfig = new Properties();
    if (cmd.hasOption(sysConfigOption.getLongOpt())) {
        sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt()));
    }

    JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'),
            cmd.hasOption("kc"));
    StringWriter stringWriter = new StringWriter();
    if (cmd.hasOption('i')) {
        converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter);
    } else {
        if (cmd.hasOption('a')) {
            converter.convertAll(cmd.getOptionValue('n'), stringWriter);
        } else {
            converter.convert(cmd.getOptionValue('n'), stringWriter);
        }
    }

    if (cmd.hasOption('t')) {
        Closer closer = Closer.create();
        try {
            FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t')));
            OutputStreamWriter outputStreamWriter = closer.register(
                    new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
            BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter));
            bufferedWriter.write(stringWriter.toString());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } else {
        System.out.println(stringWriter.toString());
    }
}

From source file:ModifyModelSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);//from   w w w  .j av  a 2  s  . c  o m
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    contentPane.add(scrollPane1, BorderLayout.WEST);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane2 = new JScrollPane(textArea);
    contentPane.add(scrollPane2, BorderLayout.CENTER);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                pw.print("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                pw.print("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                pw.print("Type: Interval Removed");
                break;
            }
            pw.print(", Index0: " + listDataEvent.getIndex0());
            pw.print(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            Enumeration elements = theModel.elements();
            pw.print(", Elements: ");
            while (elements.hasMoreElements()) {
                pw.print(elements.nextElement());
                pw.print(",");
            }
            pw.println();
            textArea.append(sw.toString());
        }
    };

    model.addListDataListener(listDataListener);

    // Setup buttons
    JPanel jp = new JPanel(new GridLayout(2, 1));
    JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    jp.add(jp1);
    jp.add(jp2);
    JButton jb = new JButton("add F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    jb = new JButton("addElement L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("Last");
        }
    });
    jb = new JButton("insertElementAt M");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
        }
    });
    jb = new JButton("set F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.set(0, "New First");
        }
    });
    jb = new JButton("setElementAt L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.setElementAt("New Last", size - 1);
        }
    });
    jb = new JButton("load 10");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            for (int i = 0, n = labels.length; i < n; i++) {
                model.addElement(labels[i]);
            }
        }
    });
    jb = new JButton("clear");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.clear();
        }
    });
    jb = new JButton("remove F");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.remove(0);
        }
    });
    jb = new JButton("removeAllElements");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeAllElements();
        }
    });
    jb = new JButton("removeElement 'Last'");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeElement("Last");
        }
    });
    jb = new JButton("removeElementAt M");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeElementAt(size / 2);
        }
    });
    jb = new JButton("removeRange FM");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeRange(0, size / 2);
        }
    });
    contentPane.add(jp, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:com.google.dart.java2dart.engine.MainEngine.java

public static void main(String[] args) throws Exception {
    if (args.length != 2 && args.length != 3) {
        System.out.println("Usage: java2dart <target-src-folder> <target-test-folder> [src-package]");
        System.exit(0);/*  w  w w .ja  v  a  2 s .  c o  m*/
    }
    String targetFolder = args[0];
    String targetTestFolder = args[1];
    if (args.length == 3) {
        System.out.println("Overrriding default src package to: " + src_package);
        src_package = args[2];
    }
    System.out.println("Generating files into " + targetFolder);
    new File(targetFolder).mkdirs();
    //
    engineFolder = new File("../../../tools/plugins/com.google.dart.engine/src");
    engineTestFolder = new File("../../../tools/plugins/com.google.dart.engine_test/src");
    engineFolder2 = new File("src");
    engineFolder = engineFolder.getCanonicalFile();
    // configure Context
    context.addClasspathFile(new File("../../../../third_party/guava/r13/guava-13.0.1.jar"));
    context.addClasspathFile(new File("../../../../third_party/junit/v4_8_2/junit.jar"));
    context.addSourceFolder(engineFolder);
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/instrumentation"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/sdk"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/sdk"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/source"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/source/LineInfo.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/source/SourceRange.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/dart/ParameterKind.java"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/ast/visitor"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/constant"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/element"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/error"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/ast/visitor"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/scanner"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/resolver"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/scanner"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/type"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/builder"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/cache"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/constant"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/element"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/error"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/resolver"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/scope"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/type"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/verifier"));
    context.addSourceFile(
            new File(engineFolder2, "com/google/dart/java2dart/util/ToFormattedSourceVisitor.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/AnalysisEngine.java"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/logging"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/context"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/context"));
    // Tests
    context.addSourceFile(
            new File(engineTestFolder, "com/google/dart/engine/utilities/io/FileUtilities2.java"));
    context.addSourceFile(new File(engineTestFolder, "com/google/dart/engine/EngineTestCase.java"));
    context.addSourceFile(
            new File(engineTestFolder, "com/google/dart/engine/error/GatheringErrorListener.java"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/scanner"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/parser"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/ast"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/element"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/element"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/type"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/resolver"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/resolver"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/scope"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/context"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/context"));
    // configure renames
    context.addRename("Lcom/google/dart/engine/ast/IndexExpression;.(Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;)", "forTarget");
    context.addRename("Lcom/google/dart/engine/ast/IndexExpression;.(Lcom/google/dart/engine/scanner/Token;"
            + "Lcom/google/dart/engine/scanner/Token;Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;)", "forCascade");
    context.addRename(
            "Lcom/google/dart/engine/html/ast/XmlTagNode;.becomeParentOf<T:Lcom/google/dart/engine/html/ast/XmlNode;>(Ljava/util/List<TT;>;Ljava/util/List<TT;>;)",
            "becomeParentOfEmpty");
    // translate into single CompilationUnit
    dartUnit = context.translate();
    // run processors
    {
        List<SemanticProcessor> PROCESSORS = ImmutableList.of(new ConstructorSemanticProcessor(context),
                new ObjectSemanticProcessor(context), new CollectionSemanticProcessor(context),
                new IOSemanticProcessor(context), new PropertySemanticProcessor(context),
                new GuavaSemanticProcessor(context), new JUnitSemanticProcessor(context),
                new BeautifySemanticProcessor(context), new EngineSemanticProcessor(context));
        for (SemanticProcessor processor : PROCESSORS) {
            processor.process(dartUnit);
        }
    }
    // run this again, because we may introduce conflicts when convert methods to getters/setters
    context.ensureUniqueClassMemberNames(dartUnit);
    context.ensureNoVariableNameReferenceFromInitializer(dartUnit);
    context.ensureMethodParameterDoesNotHide(dartUnit);
    // handle reflection
    EngineSemanticProcessor.rewriteReflectionFieldsWithDirect(context, dartUnit);
    // dump as several libraries
    Files.copy(new File("resources/java_core.dart"), new File(targetFolder + "/java_core.dart"));
    Files.copy(new File("resources/java_io.dart"), new File(targetFolder + "/java_io.dart"));
    Files.copy(new File("resources/java_junit.dart"), new File(targetFolder + "/java_junit.dart"));
    Files.copy(new File("resources/java_engine.dart"), new File(targetFolder + "/java_engine.dart"));
    Files.copy(new File("resources/java_engine_io.dart"), new File(targetFolder + "/java_engine_io.dart"));
    Files.copy(new File("resources/all_test.dart"), new File(targetTestFolder + "/all_test.dart"));
    {
        CompilationUnit library = buildInstrumentationLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/instrumentation.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSourceLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/source.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSourceIoLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/source_io.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildErrorLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/error.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildScannerLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/scanner.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildHtmlLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/html.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildUtilitiesDartLibrary();
        File astFile = new File(targetFolder + "/utilities_dart.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildAstLibrary();
        File astFile = new File(targetFolder + "/ast.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
        Files.append(Files.toString(new File("resources/ast_include.dart"), Charsets.UTF_8), astFile,
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildParserLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/parser.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSdkLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/sdk.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSdkIoLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/sdk_io.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildConstantLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/constant.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildElementLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/element.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildResolverLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/resolver.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildEngineLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/engine.dart"), Charsets.UTF_8);
    }
    // Tests
    {
        CompilationUnit library = buildTestSupportLibrary();
        File testSupportFile = new File(targetTestFolder + "/test_support.dart");
        Files.write(getFormattedSource(library), testSupportFile, Charsets.UTF_8);
        Files.append(Files.toString(new File("resources/test_support_include.dart"), Charsets.UTF_8),
                testSupportFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildScannerTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/scanner_test.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildParserTestLibrary();
        // replace reflection methods
        StringWriter methodWriter = new StringWriter();
        EngineSemanticProcessor.replaceReflectionMethods(context, new PrintWriter(methodWriter), dartUnit);
        // write to file
        File libraryFile = new File(targetTestFolder + "/parser_test.dart");
        Files.write(getFormattedSource(library), libraryFile, Charsets.UTF_8);
        Files.append(methodWriter.toString(), libraryFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildAstTestLibrary();
        File astFile = new File(targetTestFolder + "/ast_test.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildElementTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/element_test.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildResolverTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/resolver_test.dart"),
                Charsets.UTF_8);
    }
    System.out.println("Translation complete");
}

From source file:com.netscape.cmstools.CRMFPopClient.java

public static void main(String args[]) throws Exception {

    Options options = createOptions();//from   w ww  .  j  a  v  a2 s. c  o m
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);

    } catch (Exception e) {
        printError(e.getMessage());
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String tokenPassword = cmd.getOptionValue("p");
    String tokenName = cmd.getOptionValue("h");

    String algorithm = cmd.getOptionValue("a", "rsa");
    int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048"));

    String profileID = cmd.getOptionValue("f");
    String subjectDN = cmd.getOptionValue("n");
    boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false"));

    // if transportCertFilename is not specified then assume no key archival
    String transportCertFilename = cmd.getOptionValue("b");

    String popOption = cmd.getOptionValue("q", "POP_SUCCESS");

    String curve = cmd.getOptionValue("c", "nistp256");
    boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false"));
    boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true"));
    int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1"));
    int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1"));

    boolean self_sign = cmd.hasOption("y");

    // get the keywrap algorithm
    KeyWrapAlgorithm keyWrapAlgorithm = null;
    String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString();
    if (cmd.hasOption("w")) {
        kwAlg = cmd.getOptionValue("w");
    } else {
        String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM");
        if (alg != null) {
            kwAlg = alg;
        }
    }

    String output = cmd.getOptionValue("o");

    String hostPort = cmd.getOptionValue("m");
    String username = cmd.getOptionValue("u");
    String requestor = cmd.getOptionValue("r");

    if (hostPort != null) {
        if (cmd.hasOption("w")) {
            printError("Any value specified for the key wrap parameter (-w) "
                    + "will be overriden.  CRMFPopClient will contact the "
                    + "CA to determine the supported algorithm when " + "hostport is specified");
        }
    }

    if (subjectDN == null) {
        printError("Missing subject DN");
        System.exit(1);
    }

    if (tokenPassword == null) {
        printError("Missing token password");
        System.exit(1);
    }

    if (algorithm.equals("rsa")) {
        if (cmd.hasOption("c")) {
            printError("Illegal parameter for RSA: -c");
            System.exit(1);
        }

        if (cmd.hasOption("t")) {
            printError("Illegal parameter for RSA: -t");
            System.exit(1);
        }

        if (cmd.hasOption("s")) {
            printError("Illegal parameter for RSA: -s");
            System.exit(1);
        }

        if (cmd.hasOption("e")) {
            printError("Illegal parameter for RSA: -e");
            System.exit(1);
        }

        if (cmd.hasOption("x")) {
            printError("Illegal parameter for RSA: -x");
            System.exit(1);
        }

    } else if (algorithm.equals("ec")) {
        if (cmd.hasOption("l")) {
            printError("Illegal parameter for ECC: -l");
            System.exit(1);
        }

        if (sensitive != 0 && sensitive != 1 && sensitive != -1) {
            printError("Illegal input parameters for -s: " + sensitive);
            System.exit(1);
        }

        if (extractable != 0 && extractable != 1 && extractable != -1) {
            printError("Illegal input parameters for -e: " + extractable);
            System.exit(1);
        }

    } else {
        printError("Invalid algorithm: " + algorithm);
        System.exit(1);
    }

    if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) {
        printError("Invalid POP option: " + popOption);
        System.exit(1);
    }

    if (profileID == null) {
        if (algorithm.equals("rsa")) {
            profileID = "caEncUserCert";

        } else if (algorithm.equals("ec")) {
            profileID = "caEncECUserCert";

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }
    }

    try {
        if (verbose)
            System.out.println("Initializing security database: " + databaseDir);
        CryptoManager.initialize(databaseDir);

        CryptoManager manager = CryptoManager.getInstance();

        CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);
        tokenName = token.getName();
        manager.setThreadToken(token);

        Password password = new Password(tokenPassword.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            throw new Exception("Unable to login: " + e, e);
        }

        CRMFPopClient client = new CRMFPopClient();
        client.setVerbose(verbose);

        String encoded = null;
        X509Certificate transportCert = null;
        if (transportCertFilename != null) {
            if (verbose)
                System.out.println("archival option enabled");
            if (verbose)
                System.out.println("Loading transport certificate");
            encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename)));
            byte[] transportCertData = Cert.parseCertificate(encoded);
            transportCert = manager.importCACertPackage(transportCertData);
        } else {
            if (verbose)
                System.out.println("archival option not enabled");
        }

        if (verbose)
            System.out.println("Parsing subject DN");
        Name subject = client.createName(subjectDN, encodingEnabled);

        if (subject == null) {
            subject = new Name();
            subject.addCommonName("Me");
            subject.addCountryName("US");
            subject.addElement(
                    new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
        }

        if (verbose)
            System.out.println("Generating key pair");
        KeyPair keyPair;
        if (algorithm.equals("rsa")) {
            keyPair = CryptoUtil.generateRSAKeyPair(token, keySize);
        } else if (algorithm.equals("ec")) {
            keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable);

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }

        // print out keyid to be used in cmc decryptPOP
        PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();
        @SuppressWarnings("deprecation")
        byte id[] = privateKey.getUniqueID();
        String kid = CryptoUtil.encodeKeyID(id);
        System.out.println("Keypair private key id: " + kid);

        if ((transportCert != null) && (hostPort != null)) {
            // check the CA for the required key wrap algorithm
            // if found, override whatever has been set by the command line
            // options for the key wrap algorithm

            ClientConfig config = new ClientConfig();
            String host = hostPort.substring(0, hostPort.indexOf(':'));
            int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1));
            config.setServerURL("http", host, port);

            PKIClient pkiclient = new PKIClient(config);
            kwAlg = getKeyWrapAlgotihm(pkiclient);
        }

        if (verbose && (transportCert != null))
            System.out.println("Using key wrap algorithm: " + kwAlg);
        if (transportCert != null) {
            keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg);
        }

        if (verbose)
            System.out.println("Creating certificate request");
        CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair,
                subject, keyWrapAlgorithm);

        ProofOfPossession pop = null;

        if (!popOption.equals("POP_NONE")) {

            if (verbose)
                System.out.println("Creating signer");
            Signature signer = client.createSigner(token, algorithm, keyPair);

            if (popOption.equals("POP_SUCCESS")) {

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                certRequest.encode(bo);
                signer.update(bo.toByteArray());

            } else if (popOption.equals("POP_FAIL")) {

                byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };

                signer.update(data);
            }

            byte[] signature = signer.sign();

            if (verbose)
                System.out.println("Creating POP");
            pop = client.createPop(algorithm, signature);
        }

        if (verbose)
            System.out.println("Creating CRMF request");
        String request = client.createCRMFRequest(certRequest, pop);

        StringWriter sw = new StringWriter();
        try (PrintWriter out = new PrintWriter(sw)) {
            out.println(Cert.REQUEST_HEADER);
            out.print(request);
            out.println(Cert.REQUEST_FOOTER);
        }
        String csr = sw.toString();

        if (hostPort != null) {
            System.out.println("Submitting CRMF request to " + hostPort);
            client.submitRequest(request, hostPort, username, profileID, requestor);

        } else if (output != null) {
            System.out.println("Storing CRMF request into " + output);
            try (FileWriter out = new FileWriter(output)) {
                out.write(csr);
            }

        } else {
            System.out.println(csr);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e.getMessage());
        System.exit(1);
    }
}