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) throws IOException 

Source Link

Document

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

Usage

From source file:hmock.http.impl.DefaultServiceSpec.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ResponseDetail detail = _responseSpec.generateResponse(request);

    response.setStatus(detail.status());
    injectHeaders(response, detail.headers());

    InputStream body = null;//from  w  w w  .  j a va 2 s  .  com
    try {
        body = detail.body();
        IOUtils.copy(body, response.getOutputStream());
    } finally {
        if (body != null) {
            body.close();
        }
    }

}

From source file:hudson.jbpm.ProcessClassLoaderCache.java

public synchronized ClassLoader getClassLoader(ProcessDefinition def) throws IOException {
    ClassLoader cl = cache.get(def.getId());
    if (cl == null) {
        File pdCache = new File(cacheRoot, Long.toString(def.getId()));
        if (!pdCache.exists()) {
            FileDefinition fd = def.getFileDefinition();
            for (Map.Entry<String, byte[]> entry : ((Map<String, byte[]>) fd.getBytesMap()).entrySet()) {
                File f = new File(pdCache, entry.getKey());
                f.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(f);
                IOUtils.copy(new ByteArrayInputStream(entry.getValue()), fos);
                fos.close();/*www  .j  a va  2  s .co  m*/
            }
        }
        cl = new URLClassLoader(new URL[] { new URL(pdCache.toURI().toURL(), "classes/") },
                Hudson.getInstance().getPluginManager().uberClassLoader) {

            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                System.out.println(name);
                return super.loadClass(name);
            }

        };
        cache.put(def.getId(), cl);
    }
    return cl;
}

From source file:com.ettrema.http.caldav.SchedulingCustomPostHandler.java

@Override
public void process(Resource resource, Request request, Response response) {
    log.trace("process");
    try {/*from  ww  w.jav  a  2  s .c  o m*/
        SchedulingOutboxResource outbox = (SchedulingOutboxResource) resource;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        IOUtils.copy(request.getInputStream(), bout);
        String iCalText = bout.toString("UTF-8");
        log.trace(iCalText);
        List<SchedulingResponseItem> respItems = outbox.queryFreeBusy(iCalText);

        String xml = schedulingHelper.generateXml(respItems);

        response.setStatus(Response.Status.SC_OK);
        response.setDateHeader(new Date());
        response.setContentTypeHeader("application/xml; charset=\"utf-8\"");
        response.setContentLengthHeader((long) xml.length());
        response.setEntity(new StringEntity(xml));
        // TODO: THIS IS NOT CALLED WITHIN THE STANDARDFILTER? DO WE NEED TO FLUSH HERE AGAIN?
        //response.close();

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.webpagebytes.cms.engine.LocalCloudFileContentBuilder.java

public void serveFile(HttpServletRequest request, HttpServletResponse response, String uri)
        throws WPBIOException {
    if (!uri.startsWith(LOCAL_FILE_SERVE_URL)) {
        return;/*from  ww  w . j  ava2 s. c  o  m*/
    }
    String fullFilePath = uri.substring(LOCAL_FILE_SERVE_URL.length());
    int pos = fullFilePath.indexOf('/');
    String bucket = fullFilePath.substring(0, pos);
    String file = fullFilePath.substring(pos + 1);
    file = new String(CmsBase64Utility.fromSafePathBase64(file), Charset.forName("UTF-8"));
    WPBFilePath cloudFile = new WPBFilePath(bucket, file);
    InputStream is = null;
    try {
        is = cloudFileStorage.getFileContent(cloudFile);
        IOUtils.copy(is, response.getOutputStream());
        WPBFileInfo fileInfo = cloudFileStorage.getFileInfo(cloudFile);
        response.setContentType(fileInfo.getContentType());

        // do not close the response outputstream here
    } catch (Exception e) {
        throw new WPBIOException("cannot serve file", e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.netflix.hollow.example.producer.infrastructure.FilesystemPublisher.java

private void copyFile(File sourceFile, File destFile) {
    try (InputStream is = new FileInputStream(sourceFile); OutputStream os = new FileOutputStream(destFile);) {
        IOUtils.copy(is, os);
    } catch (IOException e) {
        throw new RuntimeException("Unable to publish file!", e);
    }/*from   w ww. ja v a2 s  .  c  om*/
}

From source file:com.googlecode.t7mp.steps.WebappsDeploymentStep.java

@Override
protected void deployArtifacts(List<AbstractArtifact> artifactList) {
    for (AbstractArtifact artifact : artifactList) {
        final WebappArtifact webappArtifact = (WebappArtifact) artifact;
        if (webappArtifact.isUnpack() || webappArtifact.getTestContextFile() != null) {
            unzipWebappArtifact(webappArtifact);
            if (webappArtifact.getTestContextFile() != null) {
                File metaInfDirectory = new File(createTargetFileName(webappArtifact) + "/META-INF");
                metaInfDirectory.mkdirs();
                try {
                    IOUtils.copy(new FileInputStream(webappArtifact.getTestContextFile()),
                            new FileOutputStream(new File(metaInfDirectory, "context.xml")));
                } catch (FileNotFoundException e) {
                    throw new TomcatSetupException(e.getMessage(), e);
                } catch (IOException e) {
                    throw new TomcatSetupException(e.getMessage(), e);
                }/*from  w  w w  .j  a v  a 2s  .c o m*/
            }
        } else {
            try {
                String targetFileName = createTargetFileName(artifact);
                File sourceFile = artifact.getFile();
                File targetFile = new File(this.context.getConfiguration().getCatalinaBase(),
                        "/webapps/" + targetFileName);
                this.context.getLog().debug("Copy artifact from " + sourceFile.getAbsolutePath() + " to "
                        + targetFile.getAbsolutePath());
                this.setupUtil.copy(new FileInputStream(sourceFile), new FileOutputStream(targetFile));
            } catch (IOException e) {
                throw new TomcatSetupException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.googlecode.t7mp.steps.deployment.WebappsDeploymentStep.java

@Override
protected void deployArtifacts(List<AbstractArtifact> artifactList) {
    for (AbstractArtifact artifact : artifactList) {
        final WebappArtifact webappArtifact = (WebappArtifact) artifact;
        if (webappArtifact.isUnpack() || webappArtifact.getTestContextFile() != null) {
            unzipWebappArtifact(webappArtifact);
            if (webappArtifact.getTestContextFile() != null) {
                File metaInfDirectory = new File(createTargetFileName(webappArtifact) + "/META-INF");
                metaInfDirectory.mkdirs();
                try {
                    IOUtils.copy(new FileInputStream(webappArtifact.getTestContextFile()),
                            new FileOutputStream(new File(metaInfDirectory, "context.xml")));
                } catch (FileNotFoundException e) {
                    throw new TomcatSetupException(e.getMessage(), e);
                } catch (IOException e) {
                    throw new TomcatSetupException(e.getMessage(), e);
                }// ww  w . j  av a 2  s . com
            }
        } else {
            try {
                String targetFileName = createTargetFileName(artifact);
                File sourceFile = artifact.getArtifact().getFile();
                File targetFile = new File(this.context.getMojo().getCatalinaBase(),
                        "/webapps/" + targetFileName);
                this.context.getLog().debug("Copy artifact from " + sourceFile.getAbsolutePath() + " to "
                        + targetFile.getAbsolutePath());
                this.setupUtil.copy(new FileInputStream(sourceFile), new FileOutputStream(targetFile));
            } catch (IOException e) {
                throw new TomcatSetupException(e.getMessage(), e);
            }
        }
    }
}

From source file:br.com.thiagomoreira.liferay.plugins.portalpropertiesprettier.PortalPropertiesPrettierPortlet.java

public void serveResource(ResourceRequest request, ResourceResponse response)
        throws IOException, PortletException {

    String prettyProperties = prettify(request);

    OutputStream out = response.getPortletOutputStream();
    IOUtils.copy(new StringReader(prettyProperties), out);
    IOUtils.closeQuietly(out);//from  w  w  w  . ja va  2  s.  c  o  m
}

From source file:de.iritgo.aktario.client.gui.UserLoginHelper.java

/**
 *///from   w  w  w  .j a  v  a  2s  . com
public static boolean login(final UserLoginPane loginPane, final String server, final String username,
        final String password, final boolean remember, final boolean autoLogin) {
    AppContext.instance().setServerIP(server);

    connectAndGo(username, password, loginPane);

    final FlowControl flowControl = Engine.instance().getFlowControl();

    flowControl.add(new FrameworkFlowRule("UserLogin", null, null) {
        @Override
        public void success() {
            flowControl.clear();

            AktarioGUI gui = (AktarioGUI) Client.instance().getClientGUI();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStream input = new URL("http://" + server + "/autoupdate.jar").openStream();
                        String workingDirPath = Engine.instance().getSystemDir();

                        IOUtils.copy(input, FileUtils.openOutputStream(new File(
                                workingDirPath + System.getProperty("file.separator") + "autoupdate.jar")));
                    } catch (Exception x) {
                    }
                };
            }).start();

            gui.show();
            gui.setStatusUser(username + "@" + server);
            Engine.instance().getSystemProperties().setProperty("lastlogin", username + "@" + server);

            if (loginPane != null) {
                if (remember) {
                    loginPane.rememberAccount();
                } else {
                    loginPane.removeAccount();
                }

                if (autoLogin) {
                    loginPane.rememberAutoLogin();
                }
            }
        }

        @Override
        public void failure(Object arg) {
            int failure = ((Integer) arg).intValue();

            Client.instance().getNetworkService().closeAllChannels();

            if (failure == UserLoginFailureAction.USER_ALREADY_ONLINE) {
                setCompleteState(false);
                Properties props = new Properties();
                props.put("failure", arg);
                Command cmd = new ShowDialog("AktarioUserLoginFailureDialog");
                cmd.setProperties(props);
                CommandTools.performSimple(cmd);
                try {
                    Thread.sleep(10000);
                } catch (Exception x) {
                }
                connectAndGo(username, password, loginPane);
                return;
            }

            if (failure == UserLoginFailureAction.LOGIN_NOT_ALLOWED) {
                setCompleteState(false);
                Properties props = new Properties();
                props.put("failure", arg);
                Command cmd = new ShowDialog("AktarioUserLoginFailureDialog");
                cmd.setProperties(props);
                CommandTools.performSimple(cmd);
                return;
            }

            if (failure == UserLoginFailureAction.BAD_USERNAME_OR_PASSWORD) {
                setCompleteState(false);
                Properties props = new Properties();
                props.put("failure", arg);
                Command cmd = new ShowDialog("AktarioUserLoginFailureDialog");
                cmd.setProperties(props);
                CommandTools.performSimple(cmd);
                return;
            }
        }
    });

    flowControl.add(new FrameworkFlowRule("WrongVersion", null, null) {
        @Override
        public void success() {
            flowControl.clear();
            Client.instance().getNetworkService().closeAllChannels();

            JOptionPane.showMessageDialog(loginPane != null ? loginPane.getPanel() : null,
                    Engine.instance().getResourceService().getStringWithoutException("wrongClientVersion"),
                    Engine.instance().getResourceService().getStringWithoutException("systemMessage"),
                    JOptionPane.OK_OPTION);

            try {
                String workingDirPath = Engine.instance().getSystemDir();

                if (workingDirPath.endsWith("\\")) {
                    workingDirPath = workingDirPath.substring(0, workingDirPath.length() - 1);
                }

                @SuppressWarnings("unused")
                Process proc = Runtime.getRuntime()
                        .exec("java" + " -jar \"" + workingDirPath + Engine.instance().getFileSeparator()
                                + "autoupdate.jar\" http://" + AppContext.instance().getServerIP()
                                + "/update.jar" + " \"" + workingDirPath + "\"");
            } catch (Exception x) {
                JOptionPane.showMessageDialog(loginPane != null ? loginPane.getPanel() : null, x.toString(),
                        "Iritgo", JOptionPane.OK_OPTION);
            }

            System.exit(0);
        }
    });

    return false;
}

From source file:edu.jhu.hlt.concrete.serialization.TarGzCompactCommunicationSerializer.java

@Override
public void toTarGz(Collection<Communication> commColl, Path outPath) throws ConcreteException {
    try (OutputStream os = Files.newOutputStream(outPath);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(bos);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos);) {
        for (Communication c : commColl) {
            TarArchiveEntry entry = new TarArchiveEntry(c.getId() + ".concrete");
            byte[] cbytes = this.toBytes(c);
            entry.setSize(cbytes.length);
            tos.putArchiveEntry(entry);/*from  w  w  w  .java 2s.  c o  m*/
            try (ByteArrayInputStream bis = new ByteArrayInputStream(cbytes)) {
                IOUtils.copy(bis, tos);
                tos.closeArchiveEntry();
            }
        }

    } catch (IOException e) {
        throw new ConcreteException(e);
    }
}