@Override public void setClobAsAsciiStream( PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(asciiStream != null ? "Copied ASCII stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
@Override public void setClobAsCharacterStream( PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(characterStream, clob.setCharacterStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(characterStream != null ? "Copied character stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
@Override public void setClobAsString(PreparedStatement ps, int paramIndex, final String content) throws SQLException { if (content != null) { Clob clob = (Clob) createLob(ps, true, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getCharacterOutputStream", (Class[]) null); Writer writer = (Writer) methodToInvoke.invoke(lob, (Object[]) null); FileCopyUtils.copy(content, writer); } }); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug("Set string for Oracle CLOB with length " + clob.length()); } } else { ps.setClob(paramIndex, (Clob) null); logger.debug("Set Oracle CLOB to null"); } }
@Override public void setClobAsAsciiStream( PreparedStatement ps, int paramIndex, final InputStream asciiStream, int contentLength) throws SQLException { if (asciiStream != null) { Clob clob = (Clob) createLob(ps, true, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getAsciiOutputStream", (Class[]) null); OutputStream out = (OutputStream) methodToInvoke.invoke(lob, (Object[]) null); FileCopyUtils.copy(asciiStream, out); } }); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug("Set ASCII stream for Oracle CLOB with length " + clob.length()); } } else { ps.setClob(paramIndex, (Clob) null); logger.debug("Set Oracle CLOB to null"); } }
@Override public void setClobAsCharacterStream( PreparedStatement ps, int paramIndex, final Reader characterStream, int contentLength) throws SQLException { if (characterStream != null) { Clob clob = (Clob) createLob(ps, true, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getCharacterOutputStream", (Class[]) null); Writer writer = (Writer) methodToInvoke.invoke(lob, (Object[]) null); FileCopyUtils.copy(characterStream, writer); } }); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug("Set character stream for Oracle CLOB with length " + clob.length()); } } else { ps.setClob(paramIndex, (Clob) null); logger.debug("Set Oracle CLOB to null"); } }
@Override protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { this.connection.addRequestProperty(headerName, headerValue); } } if (this.connection.getDoOutput() && this.outputStreaming) { this.connection.setFixedLengthStreamingMode(bufferedOutput.length); } this.connection.connect(); if (this.connection.getDoOutput()) { FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream()); } return new SimpleClientHttpResponse(this.connection); }
@Override public void run(ApplicationArguments args) throws Exception { if (ShellUtils.hasHelpOption(args)) { String usageInstructions; final Reader reader = new InputStreamReader(getInputStream(HelpAwareShellApplicationRunner.class, "/usage.txt")); try { usageInstructions = FileCopyUtils.copyToString(new BufferedReader(reader)); usageInstructions.replaceAll("(\\r|\\n)+", System.getProperty("line.separator")); } catch (Exception ex) { throw new IllegalStateException("Cannot read stream", ex); } System.out.println(usageInstructions); } }
/** * Pre-load some fake images * * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded. */ @Bean CommandLineRunner setUp() throws IOException { return (args) -> { FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT)); Files.createDirectory(Paths.get(UPLOAD_ROOT)); FileCopyUtils.copy("Test file", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-cover.jpg")); FileCopyUtils.copy("Test file2", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-2nd-edition-cover.jpg")); FileCopyUtils.copy("Test file3", new FileWriter(UPLOAD_ROOT + "/bazinga.png")); }; }
/** * Pre-load some test images * * @return Spring Boot {@link CommandLineRunner} automatically * run after app context is loaded. */ @Bean CommandLineRunner setUp() throws IOException { return (args) -> { FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT)); Files.createDirectory(Paths.get(UPLOAD_ROOT)); FileCopyUtils.copy("Test file", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-cover.jpg")); FileCopyUtils.copy("Test file2", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-2nd-edition-cover.jpg")); FileCopyUtils.copy("Test file3", new FileWriter(UPLOAD_ROOT + "/bazinga.png")); }; }
private static void unpackZip(ZipFile zipFile, File unpackDir) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destination = new File(unpackDir.getAbsolutePath() + "/" + entry.getName()); if (entry.isDirectory()) { destination.mkdirs(); } else { destination.getParentFile().mkdirs(); FileCopyUtils.copy(zipFile.getInputStream(entry), new FileOutputStream(destination)); } if (entry.getTime() != -1) { destination.setLastModified(entry.getTime()); } } }
@Test public void shouldPackOnlyMissingResources() throws Exception { ZipFile zipFile = new ZipFile(SampleProjects.springTravel()); try { ApplicationArchive archive = new ZipApplicationArchive(zipFile); CloudResources allResources = new CloudResources(archive); List<CloudResource> resources = new ArrayList<CloudResource>(allResources.asList()); resources.remove(0); CloudResources knownRemoteResources = new CloudResources(resources); UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources); ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileCopyUtils.copy(payload.getInputStream(), bos); assertThat(payload.getArchive(), is(archive)); assertThat(payload.getTotalUncompressedSize(), is(93)); assertThat(bos.toByteArray().length, is(2451)); } finally { zipFile.close(); } }
public void saveContent(String transferId, String contentFileId, InputStream contentStream) throws TransferException { Lock lock = checkLock(transferId); try { File stagedFile = new File(getStagingFolder(transferId), contentFileId); if (stagedFile.createNewFile()) { FileCopyUtils.copy(contentStream, new BufferedOutputStream(new FileOutputStream(stagedFile))); } } catch (Exception ex) { throw new TransferException(MSG_ERROR_WHILE_STAGING_CONTENT, new Object[]{transferId, contentFileId}, ex); } finally { lock.enableLockTimeout(); } }
/** * Populates a file with the content in the reader, but also converts the encoding to UTF-8. */ private void saveContentInUtf8File(ContentReader reader, File file) { String encoding = reader.getEncoding(); try { Reader in = new InputStreamReader(reader.getContentInputStream(), encoding); Writer out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8"); FileCopyUtils.copy(in, out); // both streams are closed } catch (IOException e) { throw new ContentIOException("Failed to copy content to file and convert "+encoding+" to UTF-8: \n" + " file: " + file, e); } }
/** * Copies the {@link #getContentInputStream() input stream} to the given * <code>OutputStream</code> */ public final void getContent(OutputStream os) throws ContentIOException { try { InputStream is = getContentInputStream(); FileCopyUtils.copy(is, os); // both streams are closed // done } catch (IOException e) { throw new ContentIOException("Failed to copy content to output stream: \n" + " accessor: " + this, e); } }
public final void getContent(File file) throws ContentIOException { try { InputStream is = getContentInputStream(); FileOutputStream os = new FileOutputStream(file); FileCopyUtils.copy(is, os); // both streams are closed // done } catch (IOException e) { throw new ContentIOException("Failed to copy content to file: \n" + " accessor: " + this + "\n" + " file: " + file, e); } }
/** * Makes use of the encoding, if available, to convert bytes to a string. * <p> * All the content is streamed into memory. So, like the interface said, * be careful with this method. * * @see ContentAccessor#getEncoding() */ public final String getContentString() throws ContentIOException { try { // read from the stream into a byte[] InputStream is = getContentInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); FileCopyUtils.copy(is, os); // both streams are closed byte[] bytes = os.toByteArray(); // get the encoding for the string String encoding = getEncoding(); // create the string from the byte[] using encoding if necessary String content = (encoding == null) ? new String(bytes) : new String(bytes, encoding); // done return content; } catch (Exception e) { throw new ContentIOException("Failed to copy content to string: \n" + " accessor: " + this, e); } }
/** * 保存Resource到持久化,这个实现中是文件 * * @param mediaEntity * @return File */ @Override public Resource storeResource(MediaEntity mediaEntity) throws IOException { if (!(mediaEntity.getResource() instanceof WxMediaResource)) { return null; } WxMediaResource wxMediaResource = (WxMediaResource) mediaEntity.getResource(); if (wxMediaResource.isUrlMedia()) { return null; } String fileName = wxMediaResource.getFilename(); if (fileName == null) { fileName = mediaEntity.getMediaId(); } File file = new File(StringUtils.applyRelativePath(Type.TEMP.equals(mediaEntity.getStoreType()) ? defaultTempFilePath : defaultFilePath, fileName)); if (file.exists()) { return new FileSystemResource(file); } file.createNewFile(); file.setLastModified(System.currentTimeMillis()); FileCopyUtils.copy(mediaEntity.getResource().getInputStream(), new FileOutputStream(file)); mediaEntity.setResourcePath(file.getAbsolutePath()); store(mediaEntity); return new FileSystemResource(file); }
public void testGetContentBinary_01() throws Exception { // To URL String url = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 12345L, 56L, "harry"); // To Reader ContentReader reader = new SpoofedTextContentReader(url); InputStream is = reader.getContentInputStream(); try { byte[] bytes = FileCopyUtils.copyToByteArray(is); assertEquals(56L, bytes.length); } finally { is.close(); } // Compare readers ContentReader copyOne = reader.getReader(); ContentReader copyTwo = reader.getReader(); // Get exactly the same binaries assertTrue(AbstractContentReader.compareContentReaders(copyOne, copyTwo)); }
public String getContent() throws IOException { // ensure we only try to read the content once - as this method may be called several times // but the inputstream can only be processed a single time if (this.content == null) { ByteArrayOutputStream os = new ByteArrayOutputStream(1024); FileCopyUtils.copy(stream, os); // both streams are closed byte[] bytes = os.toByteArray(); // get the encoding for the string String encoding = getEncoding(); // create the string from the byte[] using encoding if necessary this.content = (encoding == null) ? new String(bytes) : new String(bytes, encoding); } return this.content; }
public StoreResult saveStore(String model, String key, DataSource dataSource) throws Exception { String path = key; File dir = new File(baseDir + "/" + model); dir.mkdirs(); File targetFile = new File(baseDir + "/" + model + "/" + path); FileOutputStream fos = new FileOutputStream(targetFile); try { FileCopyUtils.copy(dataSource.getInputStream(), fos); fos.flush(); } finally { fos.close(); } StoreResult storeResult = new StoreResult(); storeResult.setModel(model); storeResult.setKey(path); storeResult.setDataSource(new FileDataSource(targetFile)); return storeResult; }
private Class<?> doLoadClass(String name) throws ClassNotFoundException { String internalName = StringUtils.replace(name, ".", "/") + ".class"; InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName); if (is == null) { throw new ClassNotFoundException(name); } try { byte[] bytes = FileCopyUtils.copyToByteArray(is); bytes = applyTransformers(name, bytes); Class<?> cls = defineClass(name, bytes, 0, bytes.length); // Additional check for defining the package, if not defined yet. if (cls.getPackage() == null) { int packageSeparator = name.lastIndexOf('.'); if (packageSeparator != -1) { String packageName = name.substring(0, packageSeparator); definePackage(packageName, null, null, null, null, null, null, null); } } this.classCache.put(name, cls); return cls; } catch (IOException ex) { throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex); } }
@Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException { Blob blob = ps.getConnection().createBlob(); try { FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryBlobs.add(blob); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug(binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength : "Set BLOB to null"); } }
@Override public void setBlobAsBytes(PreparedStatement ps, int paramIndex, final byte[] content) throws SQLException { if (content != null) { Blob blob = (Blob) createLob(ps, false, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getBinaryOutputStream"); OutputStream out = (OutputStream) methodToInvoke.invoke(lob); FileCopyUtils.copy(content, out); } }); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug("Set bytes for Oracle BLOB with length " + blob.length()); } } else { ps.setBlob(paramIndex, (Blob) null); logger.debug("Set Oracle BLOB to null"); } }
@Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, final InputStream binaryStream, int contentLength) throws SQLException { if (binaryStream != null) { Blob blob = (Blob) createLob(ps, false, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getBinaryOutputStream", (Class[]) null); OutputStream out = (OutputStream) methodToInvoke.invoke(lob, (Object[]) null); FileCopyUtils.copy(binaryStream, out); } }); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug("Set binary stream for Oracle BLOB with length " + blob.length()); } } else { ps.setBlob(paramIndex, (Blob) null); logger.debug("Set Oracle BLOB to null"); } }