Example usage for org.apache.commons.io IOUtils copy

List of usage examples for org.apache.commons.io IOUtils copy

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils copy.

Prototype

public static void copy(Reader input, OutputStream output, String encoding) throws IOException 

Source Link

Document

Copy chars from a Reader to bytes on an OutputStream using the specified character encoding, and calling flush.

Usage

From source file:com.theatlantic.highcharts.export.SVGRenderer.java

@Override
public void render() {
    if (getChartOptions() == null) {
        throw (new RuntimeException("chartOptions must not be null"));
    }/* ww w  .jav  a2 s  . co  m*/

    ByteArrayInputStream byteStream = null;
    try {
        final String svg = internal.getSVG(getChartOptions());
        if (svg == null) {
            throw (new RuntimeException("cannot generate svg"));
        }
        byteStream = new ByteArrayInputStream(svg.getBytes());
        InputStreamReader reader = new InputStreamReader(byteStream);
        IOUtils.copy(reader, getOutputStream(), "UTF-8");
    } catch (IOException e) {
        throw (new RuntimeException(e));
    } finally {
        IOUtils.closeQuietly(byteStream);
    }
}

From source file:com.axelor.web.service.HtmlToPdf.java

@GET
public File htmlToPdf(@QueryParam("html") String html, @QueryParam("fileName") String fileName,
        @QueryParam("printPageNo") String printPageNo) {
    try {//from   w ww.  ja  v a2s. c  om
        InputStream io = this.getClass().getClassLoader().getResourceAsStream("css/studio.css");
        StringWriter writer = new StringWriter();
        IOUtils.copy(io, writer, "utf-8");

        String css = writer.toString();
        html = "<div class=\"content\">" + html + "</div>";
        if (printPageNo != null) {
            html = "<div class=\"pageno\"> <span id=\"pagenumber\"></span> / <span id=\"pagecount\"></span></div>"
                    + html;
        }
        html = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><style type=\"text/css\">"
                + css + "</style></head><body>" + html + "</body></html>";

        html = formatHtml(html);
        File htmlfile = File.createTempFile(fileName, ".html");
        FileWriterWithEncoding fw = new FileWriterWithEncoding(htmlfile, "utf-8");
        fw.write(html);
        fw.close();

        File pdfFile = File.createTempFile(fileName, "");
        PDFRenderer.renderToPDF(htmlfile, pdfFile.getAbsolutePath());
        return pdfFile;
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.genericworkflownodes.knime.nodegeneration.templates.Template.java

/**
 * reads in the template from input stream.
 * /*from  w  w  w . ja v  a 2  s.co  m*/
 * @param in
 *            input stream
 * @throws IOException
 */
public Template(InputStream inputStream) throws IOException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    data = writer.toString();
}

From source file:hdfsIO.fileInteractions.java

public List<String> readLines(Path location, Configuration conf) throws Exception {
    FileSystem fileSystem = FileSystem.get(location.toUri(), conf);
    CompressionCodecFactory factory = new CompressionCodecFactory(conf);
    FileStatus[] items = fileSystem.listStatus(location);
    if (items == null) {
        return new ArrayList<String>();
    }//from w  w w.ja  v  a2s.  co  m
    List<String> results = new ArrayList<String>();
    for (FileStatus item : items) {

        // ignoring files like _SUCCESS
        if (item.getPath().getName().startsWith("_")) {
            continue;
        }

        CompressionCodec codec = factory.getCodec(item.getPath());
        InputStream stream = null;

        // check if we have a compression codec we need to use
        if (codec != null) {
            stream = codec.createInputStream(fileSystem.open(item.getPath()));
        } else {
            stream = fileSystem.open(item.getPath());
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(stream, writer, "UTF-8");
        String raw = writer.toString();
        String[] resulting = raw.split("\n");
        for (String str : raw.split("\n")) {
            results.add(str);
        }
    }
    return results;
}

From source file:com.rest4j.TextResource.java

@Override
public void write(OutputStream os) throws IOException {
    IOUtils.copy(reader, os, "UTF-8");
}

From source file:com.econcept.pingconnectionutility.utility.PingConnectionUtility.java

private static void httpPingable(String targetURI) throws IOException, URISyntaxException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet();
    httpGet.setURI(new URI(targetURI));
    CloseableHttpResponse response = httpClient.execute(httpGet);

    int currentCode = response.getStatusLine().getStatusCode();
    try {/*from  w  w w  .  j a v a 2s .co m*/

        if (currentCode >= 200 && currentCode < 300) {
            HttpEntity entity = response.getEntity();

            InputStream responseStream = entity.getContent();

            StringWriter writer = new StringWriter();

            IOUtils.copy(responseStream, writer, "UTF-8");

            System.out.println("Target Server are ok: " + currentCode);
            System.out.println(writer.toString());

            EntityUtils.consume(entity);
        } // if
        else {
            System.out.println("Target Server are not ok: " + currentCode);
        } // else
    } // try
    finally {
        response.close();
    } // finally

}

From source file:com.nfl.dm.clubsites.cms.articles.subapp.articleeditor.layouteditor.components.ParagraphTitleLabel.java

public ParagraphTitleLabel(String value) {
    try {//from   ww  w  .  ja v  a  2 s.  c  o  m
        StringWriter writer = new StringWriter();
        IOUtils.copy(getClass().getResourceAsStream(
                "/com/nfl/poc/subapp/articleeditor/layouteditor/templates/paragraph_title_template.html"),
                writer, null);
        paragraphTitleTemplate = writer.toString();
        setValue(value);
    } catch (IOException e) {
        e.printStackTrace();
    }

    setContentMode(ContentMode.HTML);
}

From source file:io.codeclou.jenkins.githubwebhookbuildtriggerplugin.GithubWebhookBuildTriggerAction.java

@RequirePOST
public HttpResponse doReceive(HttpServletRequest request, StaplerRequest staplerRequest)
        throws IOException, ServletException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(request.getInputStream(), writer, "UTF-8");
    String requestBody = writer.toString();
    Gson gson = new Gson();
    GithubWebhookPayload githubWebhookPayload = gson.fromJson(requestBody, GithubWebhookPayload.class);
    StringBuilder info = new StringBuilder();
    if (githubWebhookPayload == null) {
        return HttpResponses.error(500, this
                .getTextEnvelopedInBanner("   ERROR: payload json is empty at least requestBody is empty!"));
    }/*from   ww  w . j a va 2s  . com*/
    try {
        //
        // WEBHOOK SECRET
        //
        String githubSignature = request.getHeader("x-hub-signature");
        String webhookSecretAsConfiguredByUser = GithubWebhookBuildTriggerPluginBuilder.DescriptorImpl
                .getDescriptor().getWebhookSecret();
        String webhookSecretMessage = "validating webhook payload against wevhook secret.";
        info.append(">> webhook secret validation").append("\n");
        if (webhookSecretAsConfiguredByUser == null || webhookSecretAsConfiguredByUser.isEmpty()) {
            webhookSecretMessage = "   skipping validation since no webhook secret is configured in \n"
                    + "   'Jenkins' -> 'Configure' tab under 'Github Webhook Build Trigger' section.";
        } else {
            Boolean isValid = GitHubWebhookUtility.verifySignature(requestBody, githubSignature,
                    webhookSecretAsConfiguredByUser);
            if (!isValid) {
                info.append(webhookSecretMessage).append("\n");
                return HttpResponses.error(500, this.getTextEnvelopedInBanner(info.toString()
                        + "   ERROR: github webhook secret signature check failed. Check your webhook secret."));
            }
            webhookSecretMessage = "   ok. Webhook secret validates against " + githubSignature + "\n";
        }
        info.append(webhookSecretMessage).append("\n\n");

        //
        // CHECK IF INITIAL REQUEST (see test-webhook-init-payload.json)
        // See: https://developer.github.com/webhooks/#ping-event
        //
        if (githubWebhookPayload.getHook_id() != null) {
            info.append(">> ping request received: your webhook with ID ");
            info.append(githubWebhookPayload.getHook_id());
            info.append(" is working :)\n");
            return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
        }

        //
        // PAYLOAD TO ENVVARS
        //
        EnvironmentContributionAction environmentContributionAction = new EnvironmentContributionAction(
                githubWebhookPayload);

        //
        // TRIGGER JOBS
        //
        String jobNamePrefix = this.normalizeRepoFullName(githubWebhookPayload.getRepository().getFull_name());
        StringBuilder jobsTriggered = new StringBuilder();
        ArrayList<String> jobsAlreadyTriggered = new ArrayList<>();
        StringBuilder causeNote = new StringBuilder();
        causeNote.append("github-webhook-build-trigger-plugin:\n");
        causeNote.append(githubWebhookPayload.getAfter()).append("\n");
        causeNote.append(githubWebhookPayload.getRef()).append("\n");
        causeNote.append(githubWebhookPayload.getRepository().getClone_url());
        Cause cause = new Cause.RemoteCause("github.com", causeNote.toString());
        Collection<Job> jobs = Jenkins.getInstance().getAllItems(Job.class);
        if (jobs.isEmpty()) {
            jobsTriggered.append("   WARNING NO JOBS FOUND!\n");
            jobsTriggered.append("      You either have no jobs or if you are using matrix-based security,\n");
            jobsTriggered.append("      please give the following rights to 'Anonymous':\n");
            jobsTriggered.append("      'Job' -> build, discover, read.\n");
        }
        for (Job job : jobs) {
            if (job.getName().startsWith(jobNamePrefix) && !jobsAlreadyTriggered.contains(job.getName())) {
                jobsAlreadyTriggered.add(job.getName());
                if (job instanceof WorkflowJob) {
                    WorkflowJob wjob = (WorkflowJob) job;
                    if (wjob.isBuildable()) {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName()).append(" TRIGGERED\n");
                        wjob.scheduleBuild2(0, environmentContributionAction.transform(),
                                new CauseAction(cause));
                    } else {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                } else {
                    AbstractProject projectScheduable = (AbstractProject) job;
                    if (job.isBuildable()) {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName()).append(" TRIGGERED\n");
                        projectScheduable.scheduleBuild(0, cause, environmentContributionAction);
                    } else {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                }
            }
        }
        //
        // WRITE ADDITONAL INFO
        //
        info.append(">> webhook content to env vars").append("\n");
        info.append(environmentContributionAction.getEnvVarInfo());
        info.append("\n");
        info.append(">> jobs triggered with name matching '").append(jobNamePrefix).append("*'").append("\n");
        info.append(jobsTriggered.toString());
        return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
    } catch (JsonSyntaxException ex) {
        return HttpResponses.error(500,
                this.getTextEnvelopedInBanner(info.toString() + "   ERROR: github webhook json invalid"));
    }
}

From source file:cleaner.ExternalHtmlCleaner.java

@Override
public String CleanText(String html, String encoding) {
    try {//from  w  ww.ja  va  2 s. c  om
        File tempIn = File.createTempFile("ExternalParserInput", ".tmp");
        String tempInName = tempIn.getCanonicalPath();
        File tempOut = File.createTempFile("ExternalParserOutput", ".tmp");
        String tempOutName = tempOut.getCanonicalPath();

        FileUtils.writeStringToFile(tempIn, html, encoding);

        String cmd = extScript + " " + tempInName + " " + tempOutName;
        System.out.println("Executing: " + cmd);
        Process proc = Runtime.getRuntime().exec(cmd);

        if (proc == null) {
            System.err.println("Cannot execute command: " + extScript);
            return null;
        }

        StringWriter err = new StringWriter();
        IOUtils.copy(proc.getErrorStream(), err, encoding);

        String ErrStr = err.toString();

        if (!ErrStr.isEmpty()) {
            System.err.println("External script " + extScript + " returned errors:");
            System.err.println(ErrStr);

            throw new Exception("External script " + extScript + " returned errors");
        }

        String out = FileUtils.readFileToString(tempOut);

        tempIn.delete();
        tempOut.delete();

        return LeoCleanerUtil.CollapseSpaces(out);
    } catch (Exception e) {
        System.err.println("Failed to run the script " + extScript + " Error: " + e);
        System.exit(1);
    }
    return null;
}

From source file:de.kurashigegollub.dev.gcatest.Utils.java

public static String readFileAsStringFromBundle(String filename) throws IOException {
    InputStream is = Utils.class.getResourceAsStream(("/" + filename).replace('/', File.separatorChar));
    if (is == null) {
        throw new IOException(String.format("Could not find %s", filename));
    }// ww w.jav  a 2s. co  m
    StringWriter sw = new StringWriter();
    IOUtils.copy(is, sw, "utf-8"); //this uses Apache commons io
    return sw.toString();
}