List of usage examples for org.apache.commons.io CopyUtils copy
public static void copy(String input, Writer output) throws IOException
String
to a Writer
. From source file:cn.edu.zju.acm.onlinejudge.action.ProblemImportAction.java
private static void createProblems(ProblemPackage pack, long cid) throws Exception { ProblemPersistence problemPersistence = PersistenceManager.getInstance().getProblemPersistence(); ProblemEntry[] problems = pack.getProblemEntries(); for (int i = 0; i < problems.length; ++i) { // info//from w w w.j a v a 2 s. c om problems[i].getProblem().setContestId(cid); problemPersistence.createProblem(problems[i].getProblem(), 0); long problemId = problems[i].getProblem().getId(); ProblemImportAction.createReference(ReferenceType.DESCRIPTION, problems[i].getText(), problemId, 0, ProblemManager.PROBLEM_TEXT_FILE, null); ProblemImportAction.createReference(ReferenceType.INPUT, problems[i].getInput(), problemId, 0, ProblemManager.INPUT_FILE, null); ProblemImportAction.createReference(ReferenceType.OUTPUT, problems[i].getOutput(), problemId, 0, ProblemManager.OUTPUT_FILE, null); ProblemImportAction.createReference(ReferenceType.HEADER, problems[i].getChecker(), problemId, 0, ProblemManager.CHECKER_FILE, null); ProblemImportAction.createReference(ReferenceType.CHECKER_SOURCE, problems[i].getCheckerSource(), problemId, 0, ProblemManager.CHECKER_SOURCE_FILE, problems[i].getCheckerSourceType()); ProblemImportAction.createReference(ReferenceType.JUDGE_SOLUTION, problems[i].getSolution(), problemId, 0, ProblemManager.JUDGE_SOLUTION_FILE, problems[i].getSolutionType()); // images } Map<String, byte[]> images = pack.getImages(); String imagesPath = ConfigManager.getImagePath(); for (String string : images.keySet()) { String name = string; String path = imagesPath + "/" + name; byte[] image = images.get(name); FileOutputStream out = new FileOutputStream(path); try { CopyUtils.copy(new ByteArrayInputStream(image), out); } catch (Exception e) { out.close(); throw e; } } }
From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java
/** * Adds a zipfile from an inputStream to the aggregate zipfile. * * @param dirName name of the top-level directory that will be * @param inputStream the inputStream to the zipfile created in the aggregate zip file * @throws IOException//from w ww. jav a 2 s . c om * @throws BadInputZipFileException */ private void addZipFileFromInputStream(String dirName, long time, InputStream inputStream) throws IOException, BadInputZipFileException { // First pass: just scan through the contents of the // input file to make sure it's really valid. ZipInputStream zipInput = null; try { zipInput = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry entry; while ((entry = zipInput.getNextEntry()) != null) { zipInput.closeEntry(); } } catch (IOException e) { throw new BadInputZipFileException("Input zip file seems to be invalid", e); } finally { if (zipInput != null) zipInput.close(); } // FIXME: It is probably wrong to call reset() on any input stream; for my application the inputStream will only ByteArrayInputStream or FileInputStream inputStream.reset(); // Second pass: read each entry from the input zip file, // writing it to the output file. zipInput = null; try { // add the root directory with the correct timestamp if (time > 0L) { // Create output entry ZipEntry outputEntry = new ZipEntry(dirName + "/"); outputEntry.setTime(time); zipOutput.closeEntry(); } zipInput = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry entry; while ((entry = zipInput.getNextEntry()) != null) { try { String name = entry.getName(); // Convert absolute paths to relative if (name.startsWith("/")) { name = name.substring(1); } // Prepend directory name name = dirName + "/" + name; // Create output entry ZipEntry outputEntry = new ZipEntry(name); if (time > 0L) outputEntry.setTime(time); zipOutput.putNextEntry(outputEntry); // Copy zip input to output CopyUtils.copy(zipInput, zipOutput); } catch (Exception zex) { // ignore it } finally { zipInput.closeEntry(); zipOutput.closeEntry(); } } } finally { if (zipInput != null) { try { zipInput.close(); } catch (IOException ignore) { // Ignore } } } }
From source file:cn.edu.zju.acm.onlinejudge.judgeservice.JudgeClientJudgeThread.java
private void zipProblemData(File outputFile, Problem problem) throws PersistenceException, JudgeServerErrorException, ProblemDataErrorException { try {/* w w w .j a va2 s. c o m*/ ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outputFile)); try { List<Reference> inputFiles = this.referenceDAO.getProblemReferences(problem.getId(), ReferenceType.INPUT); List<Reference> outputFiles = this.referenceDAO.getProblemReferences(problem.getId(), ReferenceType.OUTPUT); if (inputFiles.size() != outputFiles.size() && inputFiles.size() > 0 && outputFiles.size() > 0) { throw new ProblemDataErrorException( "Unequal number of inputs and outputs for problem " + problem.getId()); } for (Reference input : inputFiles) { if (input.getContent() == null) { throw new ProblemDataErrorException( "Can not find content for input with reference id " + input.getId()); } } for (Reference output : outputFiles) { if (output.getContent() == null) { throw new ProblemDataErrorException( "Can not find content for output with reference id " + output.getId()); } } Reference specialJudge = null; if (problem.isChecker()) { List<Reference> specialJudges = this.referenceDAO.getProblemReferences(problem.getId(), ReferenceType.CHECKER_SOURCE); if (specialJudges.size() == 0) { throw new ProblemDataErrorException( "Can not find special judge for problem " + problem.getId()); } if (specialJudges.size() > 1) { throw new ProblemDataErrorException( "Find more than one special judge for problem " + problem.getId()); } specialJudge = specialJudges.get(0); String contentType = specialJudge.getContentType(); if (contentType == null) { throw new ProblemDataErrorException( "Can not find source content type for special judge with reference id " + specialJudge.getId()); } byte[] content = specialJudge.getContent(); if (content == null) { throw new ProblemDataErrorException( "Can not find source content for special judge with reference id " + specialJudge.getId()); } if (content.length == 0) { throw new ProblemDataErrorException( "Empty source for special judge with reference id " + specialJudge.getId()); } } for (int i = 0; i < inputFiles.size(); i++) { zipOut.putNextEntry(new ZipEntry(String.format("%d.in", i + 1))); CopyUtils.copy(inputFiles.get(i).getContent(), zipOut); } for (int i = 0; i < outputFiles.size(); i++) { zipOut.putNextEntry(new ZipEntry(String.format("%d.out", i + 1))); CopyUtils.copy(outputFiles.get(i).getContent(), zipOut); } if (specialJudge != null) { zipOut.putNextEntry(new ZipEntry(String.format("judge.%s", specialJudge.getContentType()))); CopyUtils.copy(specialJudge.getContent(), zipOut); } } finally { zipOut.close(); } } catch (IOException e) { throw new JudgeServerErrorException("Fail to zip problem data", e); } }
From source file:cn.edu.zju.acm.onlinejudge.judgeservice.JudgeClientJudgeThread.java
private int sendDataCommand(Problem problem) throws PersistenceException, JudgeServerErrorException, IOException, ProblemDataErrorException { File tempFile;/* w w w . j av a 2 s .c o m*/ try { tempFile = File.createTempFile("prob", null); } catch (IOException e) { throw new JudgeServerErrorException("Can not create temporary file", e); } try { this.zipProblemData(tempFile, problem); FileInputStream fin; try { fin = new FileInputStream(tempFile); } catch (FileNotFoundException e) { throw new JudgeServerErrorException("Can not find temporary file " + tempFile.getAbsolutePath(), e); } this.logger.info("Data size:" + tempFile.length()); this.sendCommand(JudgeClientCommandsFactory.createDataCommand((int) tempFile.length())); int reply = this.readJudgeReply(); if (reply == JudgeReply.READY.getId()) { try { CopyUtils.copy(fin, this.out); } finally { fin.close(); } reply = this.readJudgeReply(); if (reply == JudgeReply.COMPILING.getId()) { reply = this.readJudgeReply(); } } return reply; } finally { tempFile.delete(); } }
From source file:edu.umd.cs.marmoset.modelClasses.Project.java
public static Project importProject(InputStream in, Course course, StudentRegistration canonicalStudentRegistration, Connection conn) throws SQLException, IOException, ClassNotFoundException { Project project = new Project(); ZipInputStream zipIn = new ZipInputStream(in); // Start transaction conn.setAutoCommit(false);//from w w w. j a v a2 s .c o m conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); byte[] canonicalBytes = null; byte[] testSetupBytes = null; byte[] projectStarterFileBytes = null; while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) break; if (entry.getName().contains("project.out")) { // Found the serialized project! ObjectInputStream objectInputStream = new ObjectInputStream(zipIn); project = (Project) objectInputStream.readObject(); // Set the PKs to null, the values that get serialized are actually from // a different database with a different set of keys project.setProjectPK(0); project.setTestSetupPK(0); project.setArchivePK(null); project.setVisibleToStudents(false); // These two PKs need to be passed in when we import/create the project project.setCoursePK(course.getCoursePK()); project.setCanonicalStudentRegistrationPK(canonicalStudentRegistration.getStudentRegistrationPK()); // Insert the project so that we have a projectPK for other methods project.insert(conn); } else if (entry.getName().contains("canonical")) { // Found the canonical submission... ByteArrayOutputStream baos = new ByteArrayOutputStream(); CopyUtils.copy(zipIn, baos); canonicalBytes = baos.toByteArray(); } else if (entry.getName().contains("test-setup")) { // Found the test-setup! ByteArrayOutputStream baos = new ByteArrayOutputStream(); CopyUtils.copy(zipIn, baos); testSetupBytes = baos.toByteArray(); } else if (entry.getName().contains("project-starter-files")) { // Found project starter files ByteArrayOutputStream baos = new ByteArrayOutputStream(); CopyUtils.copy(zipIn, baos); projectStarterFileBytes = baos.toByteArray(); } } Timestamp submissionTimestamp = new Timestamp(System.currentTimeMillis()); // Now "upload" bytes as an archive for the project starter files, if it exists if (projectStarterFileBytes != null) { project.setArchiveForUpload(projectStarterFileBytes); project.uploadCachedArchive(conn); } // Now "submit" these bytes as a canonical submission // TODO read the submissionTimestamp from the serialized project in the archive Submission submission = Submission.submit(canonicalBytes, canonicalStudentRegistration, project, "t" + submissionTimestamp.getTime(), "ProjectImportTool, serialMinorVersion", Integer.toString(serialMinorVersion, 100), submissionTimestamp, conn); // Now "upload" the test-setup bytes as an archive String comment = "Project Import Tool uploaded at " + submissionTimestamp; TestSetup testSetup = TestSetup.submit(testSetupBytes, project, comment, conn); project.setTestSetupPK(testSetup.getTestSetupPK()); testSetup.setTestRunPK(submission.getCurrentTestRunPK()); testSetup.update(conn); return project; }
From source file:org.jlibrary.client.export.freemarker.CategoryTemplateProcessor.java
/** * @see org.jlibrary.client.export.freemarker.FreemarkerTemplateProcessor#processTemplate(org.jlibrary.client.export.freemarker.FreemarkerFactory) *///from w ww . jav a 2 s . c o m public void processTemplate(FreemarkerFactory factory, Page page, String path) throws ExportException { page.expose(FreemarkerVariables.REPOSITORY, context.getRepository()); page.expose(FreemarkerVariables.CATEGORY, category); page.expose(FreemarkerVariables.DATE, new Date()); if (context.getRepository().getTicket().getUser().equals(User.ADMIN_USER)) { page.expose(FreemarkerVariables.USER, Messages.getMessage(User.ADMIN_NAME)); } else { page.expose(FreemarkerVariables.USER, context.getRepository().getTicket().getUser().getName()); } String rootURL = exporter.getRootURL(category); String categoriesRootURL = "categories/" + rootURL; page.expose(FreemarkerVariables.ROOT_URL, rootURL); page.expose(FreemarkerVariables.CATEGORIES_ROOT_URL, categoriesRootURL); page.expose(FreemarkerVariables.LOCATION_URL, exporter.getLocationURL(category)); page.expose(FreemarkerVariables.PRINT_FILE, getPrintFile(category)); page.expose(FreemarkerVariables.PAGE_AUTHOR, ""); page.expose(FreemarkerVariables.PAGE_KEYWORDS, WordCounter.buildKeywords(category.getDescription(), 5)); CategoryHelper helper = exporter.getCategoryHelper(); Collection nodes = helper.findNodesForCategory(category.getId()); ExportFilter filter = exporter.getFilter(); page.expose(FreemarkerVariables.CATEGORY_DOCUMENTS, filter.filterCategoryNodes(category, nodes)); String dirPath = getCategoryPath(category); File dirFile = new File(dirPath); if (!dirFile.exists()) { if (!dirFile.mkdirs()) { String message = "[CategoryTemplateProcessor] The directory " + category.getName() + " couldn't be created"; logger.error(message); throw new ExportException(message); } } FileOutputStream fos = null; try { fos = new FileOutputStream(path); CopyUtils.copy(page.getAsString(), fos); } catch (Exception e) { logger.error(e.getMessage(), e); throw new ExportException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } }
From source file:org.jlibrary.client.export.freemarker.DirectoryTemplateProcessor.java
/** * @see org.jlibrary.client.export.freemarker.FreemarkerTemplateProcessor#processTemplate(org.jlibrary.client.export.freemarker.FreemarkerFactory) *//* w w w.j a v a 2 s. co m*/ public void processTemplate(FreemarkerFactory factory, Page page, String path) throws ExportException { // Create the physical directory String dirPath = getFilePath(directory.getPath()); File dirFile = new File(dirPath); if (!dirFile.exists()) { if (!dirFile.mkdirs()) { String message = "[DirectoryTemplateProcessor] The directory " + directory.getName() + " couldn't be created"; logger.error(message); throw new ExportException(message); } } page.expose(FreemarkerVariables.REPOSITORY, context.getRepository()); page.expose(FreemarkerVariables.DIRECTORY, directory); page.expose(FreemarkerVariables.DATE, new Date()); if (context.getRepository().getTicket().getUser().equals(User.ADMIN_USER)) { page.expose(FreemarkerVariables.USER, Messages.getMessage(User.ADMIN_NAME)); } else { page.expose(FreemarkerVariables.USER, context.getRepository().getTicket().getUser().getName()); } if (hasIndexDocument()) { page.expose(FreemarkerVariables.DIRECTORY_CONTENT, getDirectoryContent()); page.expose(FreemarkerVariables.PAGE_KEYWORDS, indexDocument.getMetaData().getKeywords()); } else { page.expose(FreemarkerVariables.DIRECTORY_CONTENT, ""); page.expose(FreemarkerVariables.PAGE_KEYWORDS, WordCounter.buildKeywords(directory.getDescription(), 5)); } String rootURL = exporter.getRootURL(directory); page.expose(FreemarkerVariables.ROOT_URL, rootURL); page.expose(FreemarkerVariables.CATEGORIES_ROOT_URL, rootURL + "/categories"); page.expose(FreemarkerVariables.LOCATION_URL, exporter.getLocationURL(directory)); page.expose(FreemarkerVariables.PRINT_FILE, getPrintFile(directory)); page.expose(FreemarkerVariables.PAGE_AUTHOR, ""); Repository repository = context.getRepository(); String userId = directory.getCreator(); Ticket ticket = repository.getTicket(); ServerProfile profile = repository.getServerProfile(); SecurityService ss = JLibraryServiceFactory.getInstance(profile).getSecurityService(); try { User user = ss.findUserById(ticket, userId); page.expose(FreemarkerVariables.NODE_CREATOR, user.getName()); } catch (Exception e) { logger.error(e.getMessage(), e); } if (userId.equals(User.ADMIN_CODE)) { page.expose(FreemarkerVariables.NODE_CREATOR, Messages.getMessage(User.ADMIN_NAME)); } else { User user = MembersRegistry.getInstance().getUser(repository.getId(), userId); page.expose(FreemarkerVariables.NODE_CREATOR, user.getName()); } FileOutputStream fos = null; try { fos = new FileOutputStream(path); CopyUtils.copy(page.getAsString(), fos); } catch (Exception e) { logger.error(e.getMessage(), e); throw new ExportException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } }
From source file:org.jlibrary.client.export.freemarker.DocumentTemplateProcessor.java
private void processTemplate(FreemarkerFactory factory, Page page, String path) throws ExportException { if (Types.isImageFile(document.getTypecode())) { loadContent();//from w w w . ja va2 s .co m return; } page.expose(FreemarkerVariables.REPOSITORY, context.getRepository()); page.expose(FreemarkerVariables.DOCUMENT, document); page.expose(FreemarkerVariables.DATE, new Date()); if (context.getRepository().getTicket().getUser().equals(User.ADMIN_USER)) { page.expose(FreemarkerVariables.USER, Messages.getMessage(User.ADMIN_NAME)); } else { page.expose(FreemarkerVariables.USER, context.getRepository().getTicket().getUser().getName()); } String rootURL = exporter.getRootURL(document); page.expose(FreemarkerVariables.ROOT_URL, rootURL); page.expose(FreemarkerVariables.CATEGORIES_ROOT_URL, rootURL + "/categories"); page.expose(FreemarkerVariables.LOCATION_URL, exporter.getLocationURL(document)); page.expose(FreemarkerVariables.PRINT_FILE, getPrintFile(document)); if (document.getMetaData().getAuthor().equals(Author.UNKNOWN)) { page.expose(FreemarkerVariables.PAGE_AUTHOR, Messages.getMessage(Author.UNKNOWN_NAME)); } else { page.expose(FreemarkerVariables.PAGE_AUTHOR, document.getMetaData().getAuthor().getName()); } page.expose(FreemarkerVariables.PAGE_KEYWORDS, document.getMetaData().getKeywords()); page.expose(FreemarkerVariables.DOCUMENT_CATEGORIES, loadCategories()); page.expose(FreemarkerVariables.DOCUMENT_CONTENT, loadContent()); loadDocumentInformation(page); FileOutputStream fos = null; try { fos = new FileOutputStream(path); CopyUtils.copy(page.getAsString(), fos); } catch (Exception e) { logger.error(e.getMessage(), e); throw new ExportException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } }
From source file:org.kalypso.test.bsu.wfs.SingleSignonTest.java
private void copy(File file) throws Exception { URL url = new URL("http://bsu-srv-u04242/gruenplan/control?action=init"); FileWriter writer = new FileWriter(file); CopyUtils.copy(url.openStream(), writer); IOUtils.closeQuietly(writer);/* www .jav a 2 s.c o m*/ }
From source file:org.roosster.api.ClasspathResourceHandler.java
/** * This handler does not respect://from w w w . j a v a 2 s . c o m * <ul> * <li>Ranges</li> * <li>GZip encoding</li> * <li>if-Modified-Since or even ETag</li> * </ul> * It simply opens a stream from the classpath, and streams it to the * OutputStream. No other fancy stuff. */ public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { if (!HttpRequest.__GET.equals(request.getMethod())) { response.sendError(HttpResponse.__405_Method_Not_Allowed); response.setField(HttpFields.__Allow, "GET"); return; } String loc = docRoot + request.getPath(); if (cache.containsKey(loc)) { // serve request from already processed cache CopyUtils.copy((String) cache.get(loc), response.getOutputStream()); request.setHandled(true); } else { InputStream input = getClass().getResourceAsStream(loc); LOG.debug("Found Resource '" + loc + "' in classpath? " + (input != null ? "YES" : "NO")); if (input != null) { if (loc.endsWith("jpg") || loc.endsWith("png") || loc.endsWith("gif")) { CopyUtils.copy(input, response.getOutputStream()); request.setHandled(true); } else { BufferedReader reader = null; try { reader = new BufferedReader(new StringReader(IOUtils.toString(input))); Template tmpl = new Template(reader); tmpl.set(TMPL_BASEPATH, httpd.getBasePath()); tmpl.set(TMPL_APIBASEPATH, httpd.getApiBasePath()); String str = tmpl.toString(); CopyUtils.copy(str, response.getOutputStream()); cache.put(loc, str); request.setHandled(true); } catch (TemplateCreationException ex) { throw new IOException("Can't create template! Message: " + ex.getMessage()); } finally { input.close(); reader.close(); } } } } }