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:ch.cyberduck.core.cryptomator.S3MultipartUploadServiceTest.java
@Test public void testUploadSinglePart() throws Exception { // 5L * 1024L * 1024L final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")))) { };/*from ww w. j a va 2 s . c om*/ session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path home = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()); cryptomator.create(session, null, new VaultCredentials("test")); session.withRegistry( new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator)); final CryptoUploadFeature m = new CryptoUploadFeature<>(session, new S3MultipartUploadService(session, new S3WriteFeature(session), 5L * 1024L * 1024L, 5), new S3WriteFeature(session), cryptomator); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final int length = 5242880; final byte[] content = RandomUtils.nextBytes(length); IOUtils.write(content, local.getOutputStream(false)); final TransferStatus writeStatus = new TransferStatus(); final Cryptor cryptor = cryptomator.getCryptor(); final FileHeader header = cryptor.fileHeaderCryptor().create(); writeStatus.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header)); writeStatus.setLength(content.length); 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 S3FindFeature(session), cryptomator).find(test)); assertEquals(content.length, new CryptoAttributesFeature(session, new S3AttributesFinderFeature(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 S3ReadFeature(session), cryptomator).read(test, readStatus, new DisabledConnectionCallback()); new StreamCopier(readStatus, readStatus).transfer(in, buffer); assertArrayEquals(content, buffer.toByteArray()); new CryptoDeleteFeature(session, new S3DefaultDeleteFeature(session), cryptomator) .delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback()); local.delete(); session.close(); }
From source file:com.mmj.app.web.controller.user.UserController.java
@RequestMapping(value = "/gozapIdentifyCode") public ModelAndView gozapIdentifyCode(String t, HttpServletRequest request, HttpServletResponse response) { response.setContentType("image/png; charset=utf-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "private, must-revalidate,no-store, no-cache, must-revalidate,post-check=0, pre-check=0"); response.addHeader("Content-Disposition", "attachment; filename=\"" + "gozapIdentifyCode" + "\""); response.setCharacterEncoding("UTF-8"); final byte[] bytes = WebsiteCheckCodeManager.INSTANCE.create(CookieManagerLocator.get(request, response), response);/* w w w .j av a 2 s. c o m*/ OutputStream os; try { os = response.getOutputStream(); IOUtils.write(bytes, os); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:edu.scripps.fl.pubchem.web.session.WebSessionBase.java
protected void debugPageToTempFile(String page, boolean displayFile) throws IOException { File file = File.createTempFile(getClass().getName(), ".html"); IOUtils.write(page, new FileOutputStream(file)); if (displayFile) Desktop.getDesktop().open(file); }
From source file:com.ikon.webdav.resource.MailResource.java
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { log.debug("sendContent({}, {})", params, contentType); try {//from w w w . j ava 2s. c om String fixedMailPath = ResourceUtils.fixRepositoryPath(mail.getPath()); Mail mail = OKMMail.getInstance().getProperties(null, fixedMailPath); if (mail.getAttachments().isEmpty()) { IOUtils.write(mail.getContent(), out); } else { MimeMessage m = MailUtils.create(null, mail); m.writeTo(out); out.flush(); } } catch (PathNotFoundException e) { log.error("PathNotFoundException: " + e.getMessage(), e); throw new RuntimeException("Failed to update content: " + mail.getPath()); } catch (AccessDeniedException e) { log.error("AccessDeniedException: " + e.getMessage(), e); throw new RuntimeException("Failed to update content: " + mail.getPath()); } catch (RepositoryException e) { log.error("RepositoryException: " + e.getMessage(), e); throw new RuntimeException("Failed to update content: " + mail.getPath()); } catch (DatabaseException e) { log.error("DatabaseException: " + e.getMessage(), e); throw new RuntimeException("Failed to update content: " + mail.getPath()); } catch (MessagingException e) { log.error("MessagingException: " + e.getMessage(), e); throw new RuntimeException("Failed to update content: " + mail.getPath()); } }
From source file:ch.cyberduck.core.cryptomator.SwiftLargeObjectUploadFeatureTest.java
@Test public void testLargeObjectUpload() throws Exception { // 5L * 1024L * 1024L final Host host = new Host(new SwiftProtocol(), "identity.api.rackspacecloud.com", new Credentials(System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret"))); final SwiftSession session = new SwiftSession(host); session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path home = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory)); home.attributes().setRegion("DFW"); final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()); cryptomator.create(session, null, new VaultCredentials("test")); session.withRegistry(// w ww. j a va 2 s . c o m new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator)); final CryptoUploadFeature m = new CryptoUploadFeature<>(session, new SwiftLargeObjectUploadFeature(session, new SwiftRegionService(session), new SwiftWriteFeature(session, new SwiftRegionService(session)), 5242880L, 5), new SwiftWriteFeature(session, new SwiftRegionService(session)), cryptomator); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final int length = 5242885; final byte[] content = RandomUtils.nextBytes(length); IOUtils.write(content, local.getOutputStream(false)); final TransferStatus writeStatus = new TransferStatus(); final Cryptor cryptor = cryptomator.getCryptor(); final FileHeader header = cryptor.fileHeaderCryptor().create(); writeStatus.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header)); writeStatus.setLength(content.length); 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 SwiftFindFeature(session), cryptomator).find(test)); assertEquals(content.length, new CryptoListService(session, session, cryptomator) .list(test.getParent(), new DisabledListProgressListener()).get(test).attributes().getSize()); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length); final TransferStatus readStatus = new TransferStatus().length(content.length); final InputStream in = new CryptoReadFeature(session, new SwiftReadFeature(session, new SwiftRegionService(session)), cryptomator).read(test, readStatus, new DisabledConnectionCallback()); new StreamCopier(readStatus, readStatus).transfer(in, buffer); assertArrayEquals(content, buffer.toByteArray()); new CryptoDeleteFeature(session, new SwiftDeleteFeature(session), cryptomator) .delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback()); local.delete(); session.close(); }
From source file:be.roots.taconic.pricingguide.service.PDFServiceTest.java
public static void saveAndTestByteArray(byte[] fileAsByteArray, Integer numberOfPagesExpected) throws IOException, DocumentException { try {/*from www. j a v a 2 s .c o m*/ final byte[] clone = fileAsByteArray.clone(); assertNotNull(clone); File file = File.createTempFile( "result-" + Thread.currentThread().getStackTrace()[2].getMethodName() + "-", ".pdf"); IOUtils.write(fileAsByteArray, new FileOutputStream(file)); if (MANUAL_MODE) { LOGGER.info("Wrote test file to " + file.getAbsolutePath()); } else { assertTrue(file.exists()); assertTrue(file.length() > 0); file.delete(); } if (numberOfPagesExpected != null) { PdfReader reader = new PdfReader(clone); assertEquals(numberOfPagesExpected.intValue(), reader.getNumberOfPages()); } } catch (IOException e) { e.printStackTrace(); assertTrue(false); } }
From source file:eu.europa.ejusticeportal.dss.controller.action.NewSealMethodTest.java
/** * Initialises the trusted list store and creates the sealed PDF for the other tests. * * @throws Exception/*from w ww . j a v a2 s . c o m*/ */ @BeforeClass public static void createSealedPDF() throws Exception { System.setProperty(SealedPDFService.PASSWORD_FILE_PROPERTY, "classpath:server.pwd"); System.setProperty(SealedPDFService.CERTIFICATE_FILE_PROPERTY, "classpath:server.p12"); portal = new PortalFacadeTestImpl(TEST_XML, "dss/hello-world.pdf"); HttpProxyConfig hc = Mockito.mock(HttpProxyConfig.class); Mockito.when(hc.isHttpEnabled()).thenReturn(Boolean.FALSE); Mockito.when(hc.isHttpsEnabled()).thenReturn(Boolean.FALSE); Mockito.when(config.getExpiredValidationLevel()).thenReturn(ValidationLevel.EXCEPTION); Mockito.when(config.getOriginValidationLevel()).thenReturn(ValidationLevel.EXCEPTION); Mockito.when(config.getTamperedValidationLevel()).thenReturn(ValidationLevel.WARN); Mockito.when(config.getRevokedValidationLevel()).thenReturn(ValidationLevel.WARN); Mockito.when(config.getSignedValidationLevel()).thenReturn(ValidationLevel.EXCEPTION); Mockito.when(config.getTrustedValidationLevel()).thenReturn(ValidationLevel.WARN); Mockito.when(config.getWorkflowValidationLevel()).thenReturn(ValidationLevel.DISABLED); Mockito.when(config.getLotlUrl()) .thenReturn("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml"); Mockito.when(config.getRefreshPeriod()).thenReturn(3600); Mockito.when(config.getSealMethod()).thenReturn(SEAL_METHOD); ((PortalFacadeTestImpl) portal).setConfig(config); RefreshingTrustedListsCertificateSource.init(hc, config); RefreshingTrustedListsCertificateSource.getInstance().refresh(); byte[] originalDocument = portal.getPDFDocument(getRequest()); OutputStream os = new FileOutputStream(NO_SEAL_PDF_FILE); IOUtils.write(originalDocument, os); byte[] doc = SealedPDFService.getInstance().sealDocument(portal.getPDFDocument(getRequest()), portal.getPDFDocumentXML(getRequest()), "disclaimer", SEAL_METHOD);// document with embedded XML, signed by the server os = new FileOutputStream(SEALED_PDF_FILE); IOUtils.write(doc, os); }
From source file:com.adeptj.runtime.mvc.TemplateEngine.java
/** * Renders the template contained by the TemplateContext. * * @param context the TemplateEngine context * @throws TemplateProcessingException the {@link TemplateProcessingException} *///from w w w. j a va 2 s .com public void render(TemplateContext context) { try { Mustache mustache = ServiceTrackers.getInstance().getMustacheEngine() .getMustache(context.getTemplate()); StringBuilder output = new StringBuilder(SB_CAPACITY); mustache.render(output, context.getTemplateData()); IOUtils.write(output.toString(), context.getResponse().getWriter()); } catch (Exception ex) { // NOSONAR LOGGER.error(ex.getMessage(), ex); context.getRequest().setAttribute(ERROR_EXCEPTION, ex); throw new TemplateProcessingException(ex.getMessage(), ex); } }
From source file:at.tfr.securefs.process.ProcessFilesTest.java
@Test public void testCopyFilesByWalk() throws Exception { // Given: NO target directory yet!!, the source file final String data = "Hallo Echo"; try (OutputStream os = cp.getEncrypter(fromFile)) { IOUtils.write(data, os); }//from w ww. j a va 2s . c om Assert.assertFalse(Files.exists(toRoot.resolve(DATA_FILES))); Assert.assertFalse(Files.exists(targetToFile)); // When: copy of fromRoot to toRoot ProcessFiles pf = new ProcessFilesBean(new MockSecureFsCache()); ProcessFilesData cfd = new ProcessFilesData().setFromRootPath(fromRoot.toString()) .setToRootPath(toRoot.toString()).setAllowOverwriteExisting(false).setUpdate(false) .setProcessActive(true); pf.copy(fromRoot, toRoot, cp, newSecret, cfd); // Then: a target file is created in same subpath like sourceFile: Assert.assertTrue("subpath is not created", Files.exists(toRoot.resolve(DATA_FILES))); Assert.assertTrue("target file not created", Files.exists(targetToFile)); // Then: the content of target file is decryptable with newSecret // and equals content of source file byte[] buf = new byte[data.getBytes().length]; try (InputStream is = cp.getDecrypter(targetToFile, newSecret)) { IOUtils.read(is, buf); } Assert.assertEquals("failed to decrypt data", data, String.valueOf(data)); }
From source file:gov.nih.nci.cagrid.caarray.client.CaArraySvcClient.java
private static void gridTransferTest(CaArraySvcClient client) throws Exception, IOException { CaArrayFile file = new CaArrayFile(); file.setId(FILE_ID);//from www.ja va 2 s. c o m byte[] fileData = client.readFileUsingGridTransfer(file); System.out.println("File data: "); IOUtils.write(fileData, System.out); }