Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.statistics.StatisticsTableCreator.java

public static void saveTableToCsv(Table<String, String, Long> table, OutputStream outputStream) {
    PrintWriter pw = new PrintWriter(outputStream);
    pw.write(";");
    for (String columnKey : table.columnKeySet()) {
        pw.printf("%s;", columnKey);
    }//from w  ww.jav  a  2s. co  m
    pw.println();

    for (String rowKey : table.rowKeySet()) {
        pw.printf("%s;", rowKey);
        for (String columnKey : table.columnKeySet()) {
            Long value = table.get(rowKey, columnKey);
            pw.printf("%d;", value != null ? value : 0);
        }
        pw.println();
    }

    IOUtils.closeQuietly(pw);
}

From source file:biz.wolschon.finance.jgnucash.helper.HttpFetcher.java

/**
 * Fetch the given URL with http-basic-auth.
 * @param url the URL/*from   www . j  ava 2 s .  c  om*/
 * @param username username
 * @param password password
 * @return the page-content or null
 */
public static String fetchURL(final URL url, final String username, final String password) {
    StringWriter sw = new StringWriter();

    try {
        PrintWriter pw = new PrintWriter(sw);
        InputStream content = fetchURLStream(url, username, password);
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = in.readLine()) != null) {
            pw.println(line);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        LOGGER.error("cannot fetch malformed URL " + url, e);
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("cannot fetch URL " + url, e);
        return null;
    }
    return sw.toString();
}

From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }/*from   ww  w . j a  v a  2 s .  c  o m*/

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        //         String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);
        //         
        //         LOGGER.info("Start loading the package");
        //         Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        //         EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);
        //         
        //         Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        //          metamodelResource.getContents().add(_package);
        //          LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        ISpecimenConfiguration config = new DagMetamodelConfig(range, seed);
        IGenerator generator = new DagGenerator(config, config.getSeed());

        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(DEGREE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        //         for (Resource rsc : resourceSet.getResources()) {
        //            if (rsc.getContents().get(0) instanceof DAG) {
        //               
        //            }
        //               
        //         }

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:de.alpharogroup.exception.ExceptionExtensions.java

/**
 * Gets the stacktrace as string.//ww w . ja v  a  2s  .  c  o m
 *
 * @param throwable
 *            the throwable
 * @return the stacktrace as string.
 */
public static String getStackTrace(final Throwable throwable) {
    if (null == throwable) {
        return null;
    }
    StringWriter sw = null;
    PrintWriter pw = null;
    String stacktrace = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        stacktrace = sw.toString();
    } finally {
        StreamExtensions.closeWriter(sw);
        StreamExtensions.closeWriter(pw);
    }
    return stacktrace;
}

From source file:com.mymita.vaadlets.demo.AddonDemoApplication.java

private static VerticalLayout createStackTraceLabel(final Exception e) {
    final VerticalLayout vl = new VerticalLayout();
    vl.setMargin(true);/*from  www.  j a v  a 2 s. c  o  m*/
    vl.addComponent(new Label("<h1>Error</h1>", Label.CONTENT_XHTML));
    final StringWriter buf = new StringWriter();
    e.printStackTrace(new PrintWriter(buf));
    vl.addComponent(new Label(buf.toString(), Label.CONTENT_PREFORMATTED));
    return vl;
}

From source file:csiro.pidsvc.helper.Http.java

/**
 * Return specific HTTP response code and add a message to HTTP header.
 * /* w  ww  .j a  v a2s .c  om*/
 * @param response HttpServletResponse object.
 * @param httpResponseCode HTTP response code.
 * @param exception Exception object.
 */
public static void returnErrorCode(HttpServletResponse response, int httpResponseCode, Exception exception) {
    try {
        String message = (exception.getMessage() == null ? "" : exception.getMessage())
                + (exception.getCause() == null ? "" : "\n" + exception.getCause().getMessage());

        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));

        response.addHeader(PID_SERVICE_ERROR_HTTP_HEADER, message);
        response.addHeader(PID_SERVICE_MSG_HTTP_HEADER, sw.toString());
        response.sendError(httpResponseCode, exception.getMessage());
    } catch (IOException e) {
        _logger.debug(e);
    }
}

From source file:Main.java

public static String toString(Element element) {
    if (element == null)
        return "null";

    Source source = new DOMSource(element);

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    Result result = new StreamResult(printWriter);

    try {/*from   ww w. ja  v a 2s .co  m*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException("couldn't write element '" + element.getTagName() + "' to string", e);
    }

    printWriter.close();

    return stringWriter.toString();
}

From source file:Main.java

private static void renderErrorMessage(Exception e, Writer out) {
    PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out);
    pw.print("<u>");
    pw.print(e.getMessage());//from   w  ww  .j av a 2 s  . co m
    pw.print("</u> <pre>");
    e.printStackTrace(pw);
    pw.print("</pre>");
}

From source file:com.gsinnovations.howdah.CommandLineUtil.java

/**
 * Print the options supported by <code>GenericOptionsParser</code>.
 * In addition to the options supported by the job, passed in as the
 * group parameter.// w  w w. j a  v a  2  s .co m
 *
 * @param group job-specific command-line options.
 */
public static void printHelpWithGenericOptions(Group group) {
    org.apache.commons.cli.Options ops = new org.apache.commons.cli.Options();
    new GenericOptionsParser(new Configuration(), ops, new String[0]);
    org.apache.commons.cli.HelpFormatter fmt = new org.apache.commons.cli.HelpFormatter();
    fmt.printHelp("<command> [Generic Options] [Job-Specific Options]", "Generic Options:", ops, "");

    PrintWriter pw = new PrintWriter(System.out);
    HelpFormatter formatter = new HelpFormatter();
    formatter.setGroup(group);
    formatter.setPrintWriter(pw);
    formatter.printHelp();
    pw.flush();
}

From source file:com.granita.contacticloudsync.log.ExternalFileLogger.java

public ExternalFileLogger(Context context, String fileName, boolean verbose) throws IOException {
    this.verbose = verbose;

    File dir = getDirectory(context);
    if (dir == null)
        throw new IOException("External media not available for log creation");

    name = StringUtils.remove(StringUtils.remove(fileName, File.pathSeparatorChar), File.separatorChar);

    File log = new File(dir, name);
    writer = new PrintWriter(log);
}