List of usage examples for org.apache.commons.io IOUtils write
public static void write(StringBuffer data, OutputStream output) throws IOException
StringBuffer
to bytes on an OutputStream
using the default character encoding of the platform. From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacroTest.java
@Test public void testAbout() throws Exception { final MockExportDownloadResourceManager resourceManager = new MockExportDownloadResourceManager(); resourceManager.setDownloadResourceWriter(new MockDownloadResourceWriter()); final PlantUmlMacro macro = new PlantUmlMacro(resourceManager, null, mocks.getSpaceManager(), mocks.getSettingsManager(), mocks.getPluginAccessor(), mocks.getShortcutLinksManager(), mocks.getConfigurationManager(), mocks.getI18NBeanFactory()); final ImmutableMap<String, String> macroParams = new ImmutableMap.Builder<String, String>() .put(PlantUmlMacroParams.Param.type.name(), DiagramType.UML.name().toLowerCase()).build(); final String macroBody = new StringBuilder().append("@startuml\n").append("about\n").append("@enduml\n") .toString();/*from ww w . j av a2 s.c o m*/ final String result = macro.execute(macroParams, macroBody, new PageContextMock()); assertEquals("<div style=\"margin: 20px 0 15px 0;\">blabla Version: <b>1.x</b> by Vendor. <a href=\"URL\">" + "Plugin Homepage</a>__plugin.info.feedback__</div><span class=\"image-wrap\" style=\"\">" + "<img src='junit/resource.png' style=\"\" /></span>", result); final ByteArrayOutputStream out = (ByteArrayOutputStream) resourceManager .getResourceWriter(null, null, null).getStreamForWriting(); assertTrue(out.toByteArray().length > 0); // file size depends on installation of graphviz IOUtils.write(out.toByteArray(), new FileOutputStream("target/junit-plantuml-about.png")); }
From source file:io.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java
@Test public void allows_settings_default_control_name_using_static_configuration() throws IOException { File file = folder.newFile("filename.txt"); IOUtils.write("Something21", new FileOutputStream(file)); RestAssuredMockMvc.config = RestAssuredMockMvcConfig.config() .multiPartConfig(multiPartConfig().with().defaultControlName("something")); RestAssuredMockMvc.given().multiPart(file).when().post("/fileUploadWithControlNameEqualToSomething").then() .body("size", greaterThan(10)).body("name", equalTo("something")) .body("originalName", equalTo("filename.txt")); }
From source file:com.thoughtworks.go.server.domain.JobInstanceLogTest.java
@Test public void shouldFindIndexPageFromTestOutputRecursivelyWithMultipleFolders() throws Exception { final File logFolder = new File(rootFolder, "logs"); final File testOutput = new File(rootFolder, TestArtifactPlan.TEST_OUTPUT_FOLDER); final File junitReportFolder = new File(testOutput, "junitreport"); junitReportFolder.mkdirs();/*from www . j a v a 2 s. co m*/ logFolder.mkdirs(); FileOutputStream fileOutputStream = new FileOutputStream(new File(junitReportFolder, "index.html")); IOUtils.write("Test", fileOutputStream); IOUtils.closeQuietly(fileOutputStream); HashMap map = new HashMap(); map.put("artifactfolder", rootFolder); jobInstanceLog = new JobInstanceLog(null, map); assertThat(jobInstanceLog.getTestIndexPage().getName(), is("index.html")); }
From source file:mrcg.MRCGInstance.java
private void copyResources(File src, File dest) { for (File fsrc : src.listFiles()) { if (Utils.in(fsrc.getName(), ".DS_Store", "CVS")) continue; File fdest = new File(dest, fsrc.getName()); if (fsrc.isDirectory()) { if (!fdest.exists()) { System.out.println("creating: " + fdest.getAbsolutePath()); fdest.mkdirs();/* w w w . j a v a 2 s . com*/ } copyResources(fsrc, fdest); } else { if (fdest.getName().endsWith(".vel")) { fdest = new File(dest, fsrc.getName().replace(".vel", "")); } if (!fdest.exists()) { System.out.println("creating: " + fdest.getAbsolutePath()); if (fsrc.getName().endsWith(".vel")) { Reader in = null; Writer out = null; try { in = new BufferedReader(new FileReader(fsrc)); String template = IOUtils.toString(in); String content = Utils.execute(template, "basePackage", basePackage, "projectName", getString("config.projectname"), "databaseName", getString("database.name"), "transactionFilter", transactionFilter, "exceptionFilter", exceptionHandler, "tagUtils", tagUtils); out = new BufferedWriter(new FileWriter(fdest)); IOUtils.write(content, out); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } else { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(fsrc)); out = new BufferedOutputStream(new FileOutputStream(fdest)); IOUtils.copy(in, out); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } } }
From source file:com.ikon.util.impexp.RepositoryExporter.java
/** * Performs a recursive repository content export with metadata *//*from w w w . ja v a 2 s .c o m*/ private static ImpExpStats exportDocumentsHelper(String token, String fldPath, File fs, String metadata, boolean history, Writer out, InfoDecorator deco) throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ParseException, NoSuchGroupException, MessagingException { log.debug("exportDocumentsHelper({}, {}, {}, {}, {}, {}, {})", new Object[] { token, fldPath, fs, metadata, history, out, deco }); ImpExpStats stats = new ImpExpStats(); DocumentModule dm = ModuleManager.getDocumentModule(); FolderModule fm = ModuleManager.getFolderModule(); MailModule mm = ModuleManager.getMailModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); Gson gson = new Gson(); String path = null; File fsPath = null; if (firstTime) { path = fs.getPath(); fsPath = new File(path); firstTime = false; } else { // Repository path needs to be "corrected" under Windoze path = fs.getPath() + File.separator + PathUtils.getName(fldPath).replace(':', '_'); fsPath = new File(path); fsPath.mkdirs(); FileLogger.info(BASE_NAME, "Created folder ''{0}''", fsPath.getPath()); if (out != null) { out.write(deco.print(fldPath, 0, null)); out.flush(); } } for (Iterator<Mail> it = mm.getChildren(token, fldPath).iterator(); it.hasNext();) { Mail mailChild = it.next(); path = fsPath.getPath() + File.separator + PathUtils.getName(mailChild.getPath()).replace(':', '_'); ImpExpStats mailStats = exportMail(token, mailChild.getPath(), path + ".eml", metadata, out, deco); // Stats stats.setSize(stats.getSize() + mailStats.getSize()); stats.setMails(stats.getMails() + mailStats.getMails()); } for (Iterator<Document> it = dm.getChildren(token, fldPath).iterator(); it.hasNext();) { Document docChild = it.next(); path = fsPath.getPath() + File.separator + PathUtils.getName(docChild.getPath()).replace(':', '_'); ImpExpStats docStats = exportDocument(token, docChild.getPath(), path, metadata, history, out, deco); // Stats stats.setSize(stats.getSize() + docStats.getSize()); stats.setDocuments(stats.getDocuments() + docStats.getDocuments()); } for (Iterator<Folder> it = fm.getChildren(token, fldPath).iterator(); it.hasNext();) { Folder fldChild = it.next(); ImpExpStats tmp = exportDocumentsHelper(token, fldChild.getPath(), fsPath, metadata, history, out, deco); path = fsPath.getPath() + File.separator + PathUtils.getName(fldChild.getPath()).replace(':', '_'); // Metadata if (metadata.equals("JSON")) { FolderMetadata fmd = ma.getMetadata(fldChild); String json = gson.toJson(fmd); FileOutputStream fos = new FileOutputStream(path + Config.EXPORT_METADATA_EXT); IOUtils.write(json, fos); fos.close(); } else if (metadata.equals("XML")) { FileOutputStream fos = new FileOutputStream(path + ".xml"); FolderMetadata fmd = ma.getMetadata(fldChild); JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(FolderMetadata.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(fmd, fos); } catch (JAXBException e) { log.error(e.getMessage(), e); FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage()); } } // Stats stats.setSize(stats.getSize() + tmp.getSize()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); stats.setFolders(stats.getFolders() + tmp.getFolders() + 1); stats.setOk(stats.isOk() && tmp.isOk()); } log.debug("exportDocumentsHelper: {}", stats); return stats; }
From source file:ch.cyberduck.core.cryptomator.B2LargeUploadServiceTest.java
@Test public void testUploadWithBulk() throws Exception { // 5L * 1024L * 1024L final Host host = new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(), new Credentials( System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key"))); final B2Session session = new B2Session(host); session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path home = new Path("/test-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final CryptoVault cryptomator = new CryptoVault( new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new DisabledPasswordStore()); final Path vault = cryptomator.create(session, null, new VaultCredentials("test")); final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); session.withRegistry(//from w w w . ja va 2s . c om new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator)); final TransferStatus writeStatus = new TransferStatus(); final int length = 5242885; final byte[] content = RandomUtils.nextBytes(length); writeStatus.setLength(content.length); final CryptoBulkFeature<Void> bulk = new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new B2DeleteFeature(session), cryptomator); bulk.pre(Transfer.Type.upload, Collections.singletonMap(test, writeStatus), new DisabledConnectionCallback()); final CryptoUploadFeature m = new CryptoUploadFeature<>(session, new B2LargeUploadService(session, new B2WriteFeature(session), 5242880L, 5), new B2WriteFeature(session), cryptomator); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); IOUtils.write(content, local.getOutputStream(false)); m.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), writeStatus, null); assertEquals((long) content.length, writeStatus.getOffset(), 0L); assertTrue(writeStatus.isComplete()); assertTrue(new CryptoFindFeature(session, new B2FindFeature(session), cryptomator).find(test)); assertEquals(content.length, new CryptoAttributesFeature(session, new B2AttributesFinderFeature(session), cryptomator).find(test) .getSize()); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length); final TransferStatus readStatus = new TransferStatus().length(content.length); final InputStream in = new CryptoReadFeature(session, new B2ReadFeature(session), cryptomator).read(test, readStatus, new DisabledConnectionCallback()); new StreamCopier(readStatus, readStatus).transfer(in, buffer); assertArrayEquals(content, buffer.toByteArray()); new CryptoDeleteFeature(session, new B2DeleteFeature(session), cryptomator) .delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback()); local.delete(); session.close(); }
From source file:com.thoughtworks.go.config.GoConfigDataSource.java
@Deprecated public synchronized GoConfigHolder write(String configFileContent, boolean shouldMigrate) throws Exception { File configFile = fileLocation(); FileOutputStream output = null; try {/*from ww w . jav a 2s . co m*/ if (shouldMigrate) { configFileContent = upgrader.upgradeIfNecessary(configFileContent); } GoConfigHolder configHolder = internalLoad(configFileContent, new ConfigModifyingUser()); String toWrite = configAsXml(configHolder.configForEdit); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Writing config file: " + configFile.getAbsolutePath()); } output = new FileOutputStream(configFile); IOUtils.write(toWrite, output); return configHolder; } catch (Exception e) { LOGGER.error("Unable to write config file: " + configFile.getAbsolutePath() + "\n" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(output); } }
From source file:com.litwan.yanel.impl.resources.textedit.TextEditResource.java
public void execute() throws UsecaseException { final String content = getEditorContent(); final Resource resToEdit = getResToEdit(); if (log.isDebugEnabled()) log.debug("saving content: " + content); if (ResourceAttributeHelper.hasAttributeImplemented(resToEdit, "Modifiable", "2")) { try {//from w w w. ja v a2 s .com OutputStream os = ((ModifiableV2) resToEdit).getOutputStream(); IOUtils.write(content, os); addInfoMessage("Succesfully saved resource " + resToEdit.getPath() + ". "); if (isResToEditVersionableV2()) { VersionableV2 versionable = (VersionableV2) resToEdit; try { versionable.checkin("Updated with textEdit"); addInfoMessage("Succesfully checked in resource " + resToEdit.getPath() + ". "); } catch (Exception e) { String msg = "Could not check in resource: " + resToEdit.getPath() + " " + e.getMessage() + ". "; log.error(msg, e); addError(msg); throw new UsecaseException(msg, e); } } } catch (Exception e) { log.error("Exception: " + e); throw new UsecaseException(e.getMessage(), e); } } else { addError("Could not save the document. "); } setParameter(PARAMETER_CONTINUE_PATH, PathUtil.backToRealm(getPath()) + getEditPath().substring(1)); // allow jelly template to show link to new event }
From source file:gov.nih.nci.firebird.service.file.FileServiceBean.java
@Override public void writeCompressedFile(FirebirdFile file, OutputStream out) throws IOException { IOUtils.write(file.getByteDataSource().getData(), out); }
From source file:ch.cyberduck.core.irods.IRODSUploadFeatureTest.java
@Test public void testInterruptStatus() throws Exception { final ProtocolFactory factory = new ProtocolFactory( new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory) .read(new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile")); final Host host = new Host(profile, profile.getDefaultHostname(), new Credentials(System.getProperties().getProperty("irods.key"), System.getProperties().getProperty("irods.secret"))); final IRODSSession session = new IRODSSession(host); session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final int length = 32770; final byte[] content = RandomUtils.nextBytes(length); final OutputStream out = local.getOutputStream(false); IOUtils.write(content, out); out.close();/*from ww w. j a va2 s . c om*/ final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final TransferStatus status = new TransferStatus().length(content.length); final Checksum checksum = new IRODSUploadFeature(session).upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener() { @Override public void sent(final long bytes) { super.sent(bytes); status.setCanceled(); } }, status, new DisabledConnectionCallback()); assertTrue(status.isCanceled()); assertFalse(status.isComplete()); session.close(); }