List of usage examples for java.io FileOutputStream flush
public void flush() throws IOException
From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java
/** * Download content package from CRX instance *//*from w w w .j a v a 2s . c om*/ private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException { try (CloseableHttpClient httpClient = getHttpClient()) { getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl()); // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!) HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload"); MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file) .addTextBody("force", "true"); post.setEntity(entity.build()); JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post); boolean success = jsonResponse.optBoolean("success", false); String msg = jsonResponse.optString("msg", null); String path = jsonResponse.optString("path", null); // package already exists - get path from error message and continue if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && StringUtils.isEmpty(path)) { path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX); success = true; } if (!success) { throw new MojoExecutionException("Package path detection failed: " + msg); } getLog().info("Package path is: " + path + " - now rebuilding package..."); // 2nd: build package HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build"); executePackageManagerMethodHtml(httpClient, buildMethod, 0); // 3rd: download package String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service"); HttpGet downloadMethod = new HttpGet(crxUrl + path); // execute download CloseableHttpResponse response = httpClient.execute(downloadMethod); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // get response stream InputStream responseStream = response.getEntity().getContent(); // delete existing file File outputFileObject = new File(ouputFilePath); if (outputFileObject.exists()) { outputFileObject.delete(); } // write response file FileOutputStream fos = new FileOutputStream(outputFileObject); IOUtil.copy(responseStream, fos); fos.flush(); responseStream.close(); fos.close(); getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath()); return outputFileObject; } else { throw new MojoExecutionException( "Package download failed:\n" + EntityUtils.toString(response.getEntity())); } } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); try { response.close(); } catch (IOException ex) { // ignore } } } } catch (FileNotFoundException ex) { throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex); } catch (IOException ex) { throw new MojoExecutionException("Download operation failed.", ex); } }
From source file:com.speed.ob.api.ClassStore.java
public void dump(File in, File out, Config config) throws IOException { if (in.isDirectory()) { for (ClassNode node : nodes()) { String[] parts = node.name.split("\\."); String dirName = node.name.substring(0, node.name.lastIndexOf(".")); dirName = dirName.replace(".", "/"); File dir = new File(out, dirName); if (!dir.exists()) { if (!dir.mkdirs()) throw new IOException("Could not make output dir: " + dir.getAbsolutePath()); }/*from w w w .j a v a2 s . c o m*/ ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); FileOutputStream fOut = new FileOutputStream( new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1))); fOut.write(data); fOut.flush(); fOut.close(); } } else if (in.getName().endsWith(".jar")) { File output = new File(out, in.getName()); JarFile jf = new JarFile(in); HashMap<JarEntry, Object> existingData = new HashMap<>(); if (output.exists()) { try { JarInputStream jarIn = new JarInputStream(new FileInputStream(output)); JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if (!entry.isDirectory()) { byte[] data = IOUtils.toByteArray(jarIn); existingData.put(entry, data); jarIn.closeEntry(); } } jarIn.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Could not read existing output file, overwriting", e); } } FileOutputStream fout = new FileOutputStream(output); Manifest manifest = null; if (jf.getManifest() != null) { manifest = jf.getManifest(); if (!config.getBoolean("ClassNameTransform.keep_packages") && config.getBoolean("ClassNameTransform.exclude_mains")) { manifest = new Manifest(manifest); if (manifest.getMainAttributes().getValue("Main-Class") != null) { String manifestName = manifest.getMainAttributes().getValue("Main-Class"); if (manifestName.contains(".")) { manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1); manifest.getMainAttributes().putValue("Main-Class", manifestName); } } } } jf.close(); JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout) : new JarOutputStream(fout, manifest); Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files"); if (!existingData.isEmpty()) { for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) { Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName()); jarOut.putNextEntry(entry.getKey()); jarOut.write((byte[]) entry.getValue()); jarOut.closeEntry(); } } for (ClassNode node : nodes()) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); int index = node.name.lastIndexOf("/"); String fileName; if (index > 0) { fileName = node.name.substring(0, index + 1).replace(".", "/"); fileName += node.name.substring(index + 1).concat(".class"); } else { fileName = node.name.concat(".class"); } JarEntry entry = new JarEntry(fileName); jarOut.putNextEntry(entry); jarOut.write(data); jarOut.closeEntry(); } jarOut.close(); } else { if (nodes().size() == 1) { File outputFile = new File(out, in.getName()); ClassNode node = nodes().iterator().next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); byte[] data = writer.toByteArray(); FileOutputStream stream = new FileOutputStream(outputFile); stream.write(data); stream.close(); } } }
From source file:com.starwood.anglerslong.LicenseAddActivity.java
/****************************************************************************** * This will write the actual object to the text file. * * @param outer It's the outermost json object that encompasses all tabs ******************************************************************************/ private void write(JSONObject outer) { FileOutputStream fos; try {/*from ww w . j a v a 2 s .c o m*/ fos = openFileOutput("profile.txt", Context.MODE_PRIVATE); fos.write(outer.toString().getBytes()); fos.flush(); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:it.cnr.missioni.connector.core.MissioneRestServiceTest.java
@Test public void Z_createMissionePDFFile() throws Exception { Response r = missioniCoreClientConnector.downloadMissioneAsPdf("M_01"); InputStream is = r.readEntity(InputStream.class); File downloadfile = new File("./target/missione.pdf"); byte[] byteArray = IOUtils.toByteArray(is); FileOutputStream fos = new FileOutputStream(downloadfile); fos.write(byteArray);//from w w w .ja v a 2 s .c om fos.flush(); fos.close(); }
From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java
protected void extractCover(File f, Format format, String publicationID) { String destinationName = publicationID + "." + format.getName() + ".png"; String entryName = format.getMetadatum("internalPathCover"); if ((entryName == null) || (entryName.equals(""))) { format.addMetadatum("relativePathThumbnail", ""); return;//from ww w .j av a 2 s. c om } try { ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ); ZipEntry entry = zipFile.getEntry(entryName); File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName); String destinationPath = destFile.getAbsolutePath(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int numberOfBytesRead; byte data[] = new byte[BUFFER_SIZE]; FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) { dest.write(data, 0, numberOfBytesRead); } dest.flush(); dest.close(); is.close(); fos.close(); // create thumbnail FileInputStream fis = new FileInputStream(destinationPath); Bitmap imageBitmap = BitmapFactory.decodeStream(fis); imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] imageData = baos.toByteArray(); // write thumbnail to file File destFile2 = new File(this.thumbnailDirectoryPath, destinationName); String destinationPath2 = destFile2.getAbsolutePath(); FileOutputStream fos2 = new FileOutputStream(destFile2); fos2.write(imageData, 0, imageData.length); fos2.flush(); fos2.close(); baos.close(); // close ZIP zipFile.close(); // delete original cover destFile.delete(); // set relativePathThumbnail format.addMetadatum("relativePathThumbnail", destinationName); } catch (Exception e) { // nop } }
From source file:com.sun.faban.harness.agent.Download.java
private void downloadFile(URL url, File file) throws IOException { logger.finer("Downloading file " + url.toString()); GetMethod get = new GetMethod(url.toString()); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(2000); int status = client.executeMethod(get); if (status != HttpStatus.SC_OK) throw new IOException( "Download request for " + url + " returned " + HttpStatus.getStatusText(status) + '.'); InputStream in = get.getResponseBodyAsStream(); FileOutputStream out = new FileOutputStream(file); int length = in.read(buffer); while (length != -1) { out.write(buffer, 0, length);//from ww w .j a v a 2 s.c o m length = in.read(buffer); } out.flush(); out.close(); in.close(); }
From source file:com.uwca.operation.modules.api.company.web.CompanyController.java
private void saveFile(String newFileName, MultipartFile filedata) { String saveFilePath = Global.getUserfilesBaseDir(); File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs();// w w w .j ava2 s.c o m } try { FileOutputStream out = new FileOutputStream(saveFilePath + File.separator + newFileName); out.write(filedata.getBytes()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java
public boolean salvarImagem(String path, FileItemStream item, String nameToSave) { try {/*from w ww. java2 s . c o m*/ File f = new File(path); // File f = new File(path+File.separator+folder); // File parent = new File(f.getParent()); // // if(!parent.exists()) // parent.mkdir(); if (!f.exists()) { f.mkdir(); } File savedFile = new File(f.getAbsoluteFile() + File.separator + nameToSave); FileOutputStream fos = new FileOutputStream(savedFile); InputStream is = item.openStream(); int x = 0; byte[] b = new byte[1024]; while ((x = is.read(b)) != -1) { fos.write(b, 0, x); } fos.flush(); fos.close(); return true; } catch (Exception ex) { } return false; }
From source file:com.temenos.interaction.example.mashup.streaming.HypermediaITCase.java
@Test public void testFollowRelsToProfileImage() throws IOException, UniformInterfaceException, URISyntaxException { RepresentationFactory representationFactory = new StandardRepresentationFactory(); ClientResponse response = webResource.path("/").accept(MediaType.APPLICATION_HAL_JSON) .get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(response.getStatus()).getFamily()); ReadableRepresentation homeResource = representationFactory.readRepresentation( MediaType.APPLICATION_HAL_JSON.toString(), new InputStreamReader(response.getEntityInputStream())); Link profileLink = homeResource.getLinkByRel("http://relations.rimdsl.org/profile"); assertNotNull(profileLink);/*from ww w .j a v a 2s. c o m*/ response.close(); ClientResponse profileResponse = webResource.uri(new URI(profileLink.getHref())) .accept(MediaType.APPLICATION_HAL_JSON).get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(profileResponse.getStatus()).getFamily()); ReadableRepresentation profileResource = representationFactory.readRepresentation( MediaType.APPLICATION_HAL_JSON.toString(), new InputStreamReader(profileResponse.getEntityInputStream())); assertEquals("someone@somewhere.com", profileResource.getProperties().get("email")); Link profileImageLink = profileResource.getLinkByRel("http://relations.rimdsl.org/image"); assertNotNull(profileImageLink); profileResponse.close(); ClientResponse profileImageResponse = webResource.uri(new URI(profileImageLink.getHref())) .get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(profileImageResponse.getStatus()).getFamily()); InputStream imageStream = profileImageResponse.getEntityInputStream(); FileOutputStream fos = new FileOutputStream("./testimg.jpg"); try { IOUtils.copy(imageStream, fos); } finally { IOUtils.closeQuietly(imageStream); } fos.flush(); fos.close(); // check image received correctly assertEquals("image/jpeg", profileImageResponse.getHeaders().getFirst("Content-Type")); long originalFileSize; InputStream stream = null; try { URL url = this.getClass().getResource("/testimg.jpg"); stream = url.openStream(); originalFileSize = stream.available(); } finally { IOUtils.closeQuietly(stream); } File receivedImage = new File("./testimg.jpg"); assertEquals(originalFileSize, receivedImage.length()); profileImageResponse.close(); }
From source file:org.alfresco.extensions.bulkexport.model.FileFolder.java
/** * create content file/*from www. j a v a 2 s .c om*/ * * @param content * @param filePath * @throws IOException */ public void insertFileContent(ByteArrayOutputStream out, String filePath) throws Exception { log.debug("insertFileContent"); filePath = this.basePath + filePath; log.debug("insertFileContent filepath = " + filePath); if (this.isFileExist(filePath) && this.scapeExported) { log.debug("insertFileContent ignore file"); return; } this.createFile(filePath); try { FileOutputStream output = new FileOutputStream(filePath); output.write(out.toByteArray()); output.flush(); output.close(); } catch (Exception e) { e.printStackTrace(); } }