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

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

Introduction

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

Prototype

public static void copy(String input, Writer output) throws IOException 

Source Link

Document

Copy chars from a String to a Writer.

Usage

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("inputfile1.zip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);

    byte[] byteArr = baos.toByteArray();
    fis.close();/*ww  w .  j  a  v a 2  s.  c om*/

    fis = new FileInputStream("inputfile2.zip");
    baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);

    byteArr = baos.toByteArray();
    fis.close();

    //      if (args.length < 2) {
    //         System.err.println("Usage: " +
    //               ZipFileAggregator.class.getName() +
    //               " <output file> <file1, file2...>");
    //         System.exit(1);
    //      }
    //
    //      ZipFileAggregator agg=null;
    //      try {
    //         agg=new ZipFileAggregator(new FileOutputStream(args[0]));
    //         for (int i = 1; i < args.length; ++i) {
    //            File inputFile = new File(args[i]);
    //            System.out.println("Adding " + args[i]);
    //            try {
    //               agg.addFile(args[i], inputFile);
    //            } catch (ZipFileAggregator.BadInputZipFileException e) {
    //               System.out.println("Recoverable exception: " + e);
    //               System.out.println("Continuing...");
    //            }
    //         }
    //      } finally {
    //         if (agg != null) agg.close();
    //      }
    //      System.out.println("Done!");
}

From source file:com.discursive.jccook.io.CopyExample.java

public void start() {
    try {//from  w  w w. j  a  va 2 s . c  o  m
        Writer writer = new FileWriter("test.dat");
        InputStream inputStream = getClass().getResourceAsStream("./test.resource");
        CopyUtils.copy(inputStream, writer);
        writer.close();
        inputStream.close();
    } catch (IOException e) {
        System.out.println("Error copying data");
    }

}

From source file:com.cyclopsgroup.waterview.core.ResourceView.java

/**
 * Override or implement method of parent class or interface
 *
 * @see com.cyclopsgroup.waterview.View#render(com.cyclopsgroup.waterview.PageRuntime, com.cyclopsgroup.clib.lang.Context)
 *///from www .ja v a  2  s  .c om
public void render(PageRuntime runtime, Context viewContext) throws Exception {
    CopyUtils.copy(resource.openStream(), runtime.getOutput());
}

From source file:cn.edu.zju.acm.onlinejudge.util.ProblemManager.java

public static ProblemPackage importProblem(InputStream in, ActionMessages messages) {

    Map<String, byte[]> files = new HashMap<String, byte[]>();
    ZipInputStream zis = null;/*w  ww .  j  a  va 2 s .  com*/
    try {

        zis = new ZipInputStream(new BufferedInputStream(in));
        // zis = new ZipInputStream(new BufferedInputStream(new FileInputStream("d:/100.zip")));
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {

                // TODO the file may be too big. > 100M
                /*
                 * byte data[] = new byte[(int) entry.getSize()]; int l = 0; while (l < data.length) { int ll =
                 * zis.read(data, l, data.length - l); if (ll < 0) { break; } l += ll; }
                 */
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                CopyUtils.copy(zis, buf);
                files.put(entry.getName(), buf.toByteArray());

            }
            entry = zis.getNextEntry();
        }

    } catch (IOException ioe) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.invalidzip"));
        return null;
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
    /*
     * files.clear(); files.put("problems.csv", "3,a\n2,b,true,1,2,3,4,a,b,c\n1,c".getBytes());
     * files.put("1\\checker", "checker".getBytes()); files.put("1\\input", "input".getBytes());
     * files.put("1\\output", "output".getBytes()); files.put("3\\checker", "checker3".getBytes());
     * files.put("3\\input", "input3".getBytes()); files.put("3\\output", "output3".getBytes());
     * files.put("images\\1.jpg", "1".getBytes()); files.put("images\\2\\2.jpg", "2".getBytes());
     */
    if (!files.containsKey(ProblemManager.PROBLEM_CSV_FILE)) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.missingproblemscsv"));
        return null;
    }
    ProblemPackage problemPackage = ProblemManager.parse(files, messages);
    if (messages.size() > 0) {
        return null;
    }
    return problemPackage;
}

From source file:edu.umd.cs.buildServer.util.IO.java

/**
 * Read file from HTTP response body into a file.
 *
 * @param file/*from w ww.  j  a v  a 2 s  .  c  o m*/
 *            a File in the filesystem where the file should be stored
 * @param method
 *            the HttpMethod representing the request and response
 * @throws IOException
 *             if the complete file couldn't be downloaded
 */
public static void download(File file, HttpMethod method) throws IOException {
    InputStream in = null;
    OutputStream out = null;

    try {
        in = new BufferedInputStream(method.getResponseBodyAsStream());
        out = new BufferedOutputStream(new FileOutputStream(file));

        CopyUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:gov.nih.nci.cabio.portal.portlet.RESTProxyServletController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {/*from  w w w .ja  va2  s. c o m*/
        String relativeURL = request.getParameter("relativeURL");
        if (relativeURL == null) {
            log.error("Null relativeURL parameter");
            return null;
        }

        String qs = request.getQueryString();
        if (qs == null) {
            qs = "";
        }

        qs = qs.replaceFirst("relativeURL=(.*?)&", "");
        qs = URLDecoder.decode(qs, "UTF-8");

        String url = caBIORestURL + relativeURL + "?" + qs;
        log.info("Proxying URL: " + url);

        URI uri = new URI(url, false);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod();
        method.setURI(uri);
        client.executeMethod(method);

        response.setContentType(method.getResponseHeader("Content-Type").getValue());

        CopyUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    } catch (Exception e) {
        throw new ServletException("Unable to connect to caBIO", e);
    }

    return null;
}

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

private void addFileFromInputStream(String dirName, long time, InputStream inputStream) throws IOException {
    // Prepend directory name
    String name = dirName + "/nonzipfile";

    // Create output entry
    ZipEntry outputEntry = new ZipEntry(name);
    if (time > 0L)
        outputEntry.setTime(time); // only add valid times
    zipOutput.putNextEntry(outputEntry);

    // Copy zip input to output
    CopyUtils.copy(inputStream, zipOutput);

    zipOutput.closeEntry();/*from  w  w  w  .  j  av  a  2 s.co m*/
}

From source file:edu.umd.cs.marmoset.utilities.DirectSubmissionUpload.java

private static String submit(File file, String courseName, String semester, Connection conn)
        throws IOException, SQLException {
    String filename = file.getName();
    String[] tokens = filename.split("\\.");
    String projectNumber = tokens[0];
    String classAccount = tokens[1];
    long commitCvstag = Long.parseLong(tokens[2]);
    // cvsTagTimestamp can be null but *NOT* empty in the DB!
    String cvsTagTimestamp = tokens[3];
    if ("".equals(cvsTagTimestamp))
        cvsTagTimestamp = null;//from   w  w  w . j a  v  a  2s .com
    String zipExtension = tokens[4];
    assert zipExtension.equals(".zip");

    // copy the fileItem into a byte array
    FileInputStream fis = null;
    ByteArrayOutputStream bytes = null;
    try {
        fis = new FileInputStream(file);
        bytes = new ByteArrayOutputStream();
        CopyUtils.copy(fis, bytes);

        Submission submission = Submission.submitOneSubmission(bytes.toByteArray(), cvsTagTimestamp,
                classAccount, projectNumber, courseName, semester, conn);

        String result = "semester: " + semester + "\n" + "courseName: " + courseName + "\n"
                + "cvsTagTimestamp: " + cvsTagTimestamp + "\n" + "projectNumber: " + projectNumber + "\n"
                + "classAccount: " + classAccount;

        if (submission == null) {
            return "A duplicate!\n" + result;
        }
        return "Successfully inserted\n" + result;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(bytes);
    }
}

From source file:edu.umd.cs.marmoset.utilities.ZipExtractor.java

/**
 * Extract the zip file.// ww w  .j a  v a 2s . com
 * @throws IOException
 * @throws BuilderException
 */
public void extract(File directory) throws IOException, ZipExtractorException {
    ZipFile z = new ZipFile(zipFile);
    Pattern badName = Pattern.compile("[\\p{Cntrl}<>]");

    try {
        Enumeration<? extends ZipEntry> entries = z.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (!shouldExtract(entryName))
                continue;
            if (badName.matcher(entryName).find()) {
                if (entry.getSize() > 0)
                    getLog().debug("Skipped entry of length " + entry.getSize() + " with bad file name "
                            + java.net.URLEncoder.encode(entryName, "UTF-8"));
                continue;
            }
            try {
                // Get the filename to extract the entry into.
                // Subclasses may define this to be something other
                // than the entry name.
                String entryFileName = transformFileName(entryName);
                if (!entryFileName.equals(entryName)) {
                    getLog().debug("Transformed zip entry name: " + entryName + " ==> " + entryFileName);
                }
                entriesExtractedFromZipArchive.add(entryFileName);

                File entryOutputFile = new File(directory, entryFileName).getAbsoluteFile();

                File parentDir = entryOutputFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new ZipExtractorException(
                                "Couldn't make directory for entry output file " + entryOutputFile.getPath());
                    }
                }

                if (!parentDir.isDirectory()) {
                    throw new ZipExtractorException(
                            "Parent directory for entry " + entryOutputFile.getPath() + " is not a directory");
                }

                // Make sure the entry output file lies within the build directory.
                // A malicious zip file might have ".." components in it.

                getLog().trace("entryOutputFile path: " + entryOutputFile.getCanonicalPath());
                if (!entryOutputFile.getCanonicalPath().startsWith(directory.getCanonicalPath() + "/")) {

                    if (!entry.isDirectory())
                        getLog().warn("Zip entry " + entryName + " accesses a path " + entryOutputFile.getPath()
                                + "outside the build directory " + directory.getPath());
                    continue;
                }

                if (entry.isDirectory()) {
                    entryOutputFile.mkdir();
                    continue;
                }

                // Extract the entry
                InputStream entryInputStream = null;
                OutputStream entryOutputStream = null;
                try {
                    entryInputStream = z.getInputStream(entry);
                    entryOutputStream = new BufferedOutputStream(new FileOutputStream(entryOutputFile));

                    CopyUtils.copy(entryInputStream, entryOutputStream);
                } finally {
                    IOUtils.closeQuietly(entryInputStream);
                    IOUtils.closeQuietly(entryOutputStream);
                }

                // Hook for subclasses, to specify when entries are
                // successfully extracted.
                successfulFileExtraction(entryName, entryFileName);
                ++numFilesExtacted;
            } catch (RuntimeException e) {
                getLog().error("Error extracting " + entryName, e);
                throw e;
            }
        }
    } finally {
        z.close();
    }

}

From source file:edu.umd.cs.marmoset.utilities.MarmosetUtilities.java

/**
 * @param conn//  w  w  w . j a va2  s .com
 * @param submissionPK
 * @param filename
 * @throws SQLException
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void fixSubmissionZipfile(Connection conn, @Submission.PK int submissionPK, String filename)
        throws SQLException, FileNotFoundException, IOException {
    Submission submission = Submission.lookupBySubmissionPK(submissionPK, conn);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileInputStream fis = new FileInputStream(filename);
    CopyUtils.copy(fis, baos);
    byte[] bytes = baos.toByteArray();

    submission.setArchiveForUpload(bytes);
    submission.updateCachedArchive(conn);
}