List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from ww w. j a va 2 s.co m*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java
public void decompressZip(File inputZipPath, File zipPath) { int BUFFER = 2048; List<File> zipFiles = new ArrayList<File>(); try {/*from w w w .j a va 2 s .c om*/ zipPath.mkdir(); } catch (SecurityException e) { jlog.fatal("Security exception when creating " + zipPath.getName()); } ZipFile zipFile = null; boolean isZip = true; // Open Zip file for reading (should be in temppath) try { zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ); } catch (IOException e) { jlog.fatal("IO exception in " + inputZipPath.getName()); } // Create an enumeration of the entries in the zip file Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); if (isZip) { // Process each entry while (zipFileEntries.hasMoreElements()) { // Get a zip file entry ZipEntry entry = zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = null; // destFile should be pointing to temppath\%date%\ try { destFile = new File(zipPath.getAbsolutePath(), currentEntry); destFile = new File(zipPath.getAbsolutePath(), destFile.getName()); } catch (NullPointerException e) { jlog.fatal("File not found" + destFile.getName()); } // If the entry is a .zip add it to the list so that it can be extracted if (currentEntry.endsWith(".zip")) { zipFiles.add(destFile); } try { // Extract file if not a directory if (!entry.isDirectory()) { // Stream the zip entry BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; FileOutputStream fos = null; // Write the current file to disk try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { jlog.fatal("File not found " + destFile.getName()); } catch (SecurityException e) { jlog.fatal("Access denied to " + destFile.getName()); } BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } catch (IOException ioe) { jlog.fatal("IO exception in " + zipFile.getName()); } } try { zipFile.close(); } catch (IOException e) { jlog.fatal("IO exception when closing " + zipFile.getName()); } } // Recursively decompress the list of zip files for (File f : zipFiles) { decompressZip(f, zipPath); } return; }
From source file:m.c.m.proxyma.resource.ProxymaServletResponse.java
/** * This private method serilizes the response data into the passed http response. * * @param responseData the data to send//from w w w . j a va2 s . c o m * @param theResponse the response implementation to use to send the data * @return the status code of the operation. */ private int serializeAndSendResponseData(ProxymaResponseDataBean responseData, HttpServletResponse theResponse) { //set the returnCode int exitStatus = responseData.getStatus(); theResponse.setStatus(exitStatus); //set all the headers of the response data into the http servlet response.. log.finer("Sending headers.."); Iterator<String> stringIterarot = responseData.getHeaderNames().iterator(); String headerName = null; ProxymaHttpHeader header = null; Collection<ProxymaHttpHeader> multiHeader = null; while (stringIterarot.hasNext()) { headerName = stringIterarot.next(); if (responseData.isMultipleHeader(headerName)) { //Process multiple values header. multiHeader = responseData.getMultivalueHeader(headerName); Iterator<ProxymaHttpHeader> headers = multiHeader.iterator(); while (headers.hasNext()) { header = headers.next(); theResponse.setHeader(header.getName(), header.getValue()); } } else { //Process Sungle value header header = responseData.getHeader(headerName); theResponse.setHeader(header.getName(), header.getValue()); } } //set the cookies into the http servlet response. log.finer("Sending cookies.."); Iterator<Cookie> cookieIterator = responseData.getCookies().iterator(); while (cookieIterator.hasNext()) { theResponse.addCookie(cookieIterator.next()); } //Serialize the data of the ByteBuffer into the servlet response.. if (responseData.getData() != null) { BufferedOutputStream bos = null; log.finer("Sending data.."); try { bos = new BufferedOutputStream(theResponse.getOutputStream()); ByteBufferReader data = ByteBufferFactory.createNewByteBufferReader(responseData.getData()); byte[] buffer = new byte[WRITE_BUFFER_SIZE]; int count; while ((count = data.readBytes(buffer, WRITE_BUFFER_SIZE)) >= 0) bos.write(buffer, 0, count); } catch (Exception e) { log.severe("Error in writing buffer data into the response!"); e.printStackTrace(); exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { try { if (bos != null) { bos.flush(); bos.close(); } } catch (IOException e) { log.severe("Error closing response output buffer!"); e.printStackTrace(); exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } } return exitStatus; }
From source file:com.glaf.core.util.ZipUtils.java
public static void unzip(java.io.InputStream inputStream, String path, List<String> excludes) throws Exception { File file = new File(path); FileUtils.mkdirsWithExistsCheck(file); ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try {// w w w . ja v a2 s . co m zipInputStream = new ZipInputStream(inputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { boolean isDirectory = zipEntry.isDirectory(); byte abyte0[] = new byte[BUFFER]; String s1 = zipEntry.getName(); String ext = FileUtils.getFileExt(s1); if (excludes.contains(ext) || excludes.contains(ext.toLowerCase())) { continue; } s1 = convertEncoding(s1); String s2 = path + sp + s1; s2 = FileUtils.getJavaFileSystemPath(s2); if (s2.indexOf('/') != -1 || isDirectory) { String s4 = s2.substring(0, s2.lastIndexOf('/')); File file2 = new File(s4); FileUtils.mkdirsWithExistsCheck(file2); } if (isDirectory) { continue; } fileoutputstream = new FileOutputStream(s2); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i = 0; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); IOUtils.closeStream(fileoutputstream); IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { IOUtils.closeStream(zipInputStream); IOUtils.closeStream(fileoutputstream); IOUtils.closeStream(bufferedoutputstream); } }
From source file:org.apache.synapse.format.hessian.HessianMessageFormatter.java
/** * Reads details from the SOAPFault and creates a new Hessian fault using those details and * writes it to the output stream./*w ww. java 2 s. c om*/ * * @param soapFault the SOAP fault to convert and write as a Hessian fault * @param out the output stream to write the Hessian fault to * * @throws AxisFault if an error occurs writing the message to the output stream */ private void convertAndWriteHessianFault(SOAPFault soapFault, OutputStream out) throws AxisFault { BufferedOutputStream faultOutStream = new BufferedOutputStream(out); try { String hessianFaultCode = "500"; String hessianFaultMessage = ""; String hessianFaultDetail = ""; if (soapFault.getCode() != null) { hessianFaultCode = soapFault.getCode().getText(); } if (soapFault.getReason() != null) { hessianFaultMessage = soapFault.getReason().getText(); } if (soapFault.getDetail() != null) { hessianFaultDetail = soapFault.getDetail().getText(); } HessianUtils.writeFault(hessianFaultCode, hessianFaultMessage, hessianFaultDetail, faultOutStream); faultOutStream.flush(); } catch (IOException e) { handleException("Unalbe to write the fault as a Hessian message", e); } finally { try { if (faultOutStream != null) { faultOutStream.close(); } } catch (IOException ignore) { log.warn("Error closing output stream.", ignore); } } }
From source file:com.glaf.core.util.ZipUtils.java
public static void unzip(File zipFile, String dir) throws Exception { File file = new File(dir); FileUtils.mkdirsWithExistsCheck(file); FileInputStream fileInputStream = null; ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try {// www.jav a 2s.c o m fileInputStream = new FileInputStream(zipFile); zipInputStream = new ZipInputStream(fileInputStream); fileInputStream = new FileInputStream(zipFile); zipInputStream = new ZipInputStream(fileInputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { boolean isDirectory = zipEntry.isDirectory(); byte abyte0[] = new byte[BUFFER]; String s1 = zipEntry.getName(); s1 = convertEncoding(s1); String s2 = dir + "/" + s1; s2 = FileUtils.getJavaFileSystemPath(s2); if (s2.indexOf('/') != -1 || isDirectory) { String s4 = s2.substring(0, s2.lastIndexOf('/')); File file2 = new File(s4); FileUtils.mkdirsWithExistsCheck(file2); } if (isDirectory) { continue; } fileoutputstream = new FileOutputStream(s2); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i = 0; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); IOUtils.closeStream(fileoutputstream); IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { IOUtils.closeStream(fileInputStream); IOUtils.closeStream(zipInputStream); IOUtils.closeStream(fileoutputstream); IOUtils.closeStream(bufferedoutputstream); } }
From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java
/** * //from ww w. j ava 2 s . co m * @param old the file to be copied * @param newDir the directory to move the file to * @return */ public int copyToDirectory(String old, String newDir) { File old_file = new File(old); File temp_dir = new File(newDir); byte[] data = new byte[BUFFER]; int read = 0; if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) { String file_name = old.substring(old.lastIndexOf("/"), old.length()); File cp_file = new File(newDir + file_name); try { BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file)); BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file)); while ((read = i_stream.read(data, 0, BUFFER)) != -1) o_stream.write(data, 0, read); o_stream.flush(); i_stream.close(); o_stream.close(); } catch (FileNotFoundException e) { Log.e("FileNotFoundException", e.getMessage()); return -1; } catch (IOException e) { Log.e("IOException", e.getMessage()); return -1; } } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) { String files[] = old_file.list(); String dir = newDir + old.substring(old.lastIndexOf("/"), old.length()); int len = files.length; if (!new File(dir).mkdir()) return -1; for (int i = 0; i < len; i++) copyToDirectory(old + "/" + files[i], dir); } else if (!temp_dir.canWrite()) return -1; return 0; }
From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. *//*from w w w .ja v a2s. c o m*/ private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(this.updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } }
From source file:com.aurel.track.exchange.track.importer.TrackImportAction.java
/** * Render the import page/*from w ww . j a v a 2 s . c o m*/ */ @Override /** * Save the zip file and import the data * @return */ public String execute() { LOGGER.info("Import started"); InputStream inputStream; try { inputStream = new FileInputStream(uploadFile); } catch (FileNotFoundException e) { LOGGER.error("Getting the input stream for the zip failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed"))); return null; } /** * delete the old temporary attachment directory if exists from previous imports */ String tempAttachmentDirectory = AttachBL.getAttachDirBase() + File.separator + AttachBL.tmpAttachments; AttachBL.deleteDirectory(new File(tempAttachmentDirectory)); /** * extract the zip to a temporary directory */ ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); final int BUFFER = 2048; File unzipTempDirectory = new File(tempAttachmentDirectory); if (!unzipTempDirectory.exists()) { unzipTempDirectory.mkdirs(); } BufferedOutputStream dest = null; ZipEntry zipEntry; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(unzipTempDirectory, zipEntry.getName()); // grab file's parent directory structure int count; byte data[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zipInputStream.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zipInputStream.close(); } catch (Exception e) { LOGGER.error("Extracting the zip to the temporary directory failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * get the data file (the only file from the zip which is not an attachment) */ File importDataFile = new File(tempAttachmentDirectory, ExchangeFieldNames.EXCHANGE_ZIP_ENTRY); if (!importDataFile.exists()) { LOGGER.error("The file " + ExchangeFieldNames.EXCHANGE_ZIP_ENTRY + " not found in the zip"); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * field parser */ LOGGER.debug("Parsing the fields"); List<ISerializableLabelBean> customFieldsBeans = new ImporterFieldParser().parse(importDataFile); Map<Integer, Integer> fieldsMatcherMap = null; try { fieldsMatcherMap = TrackImportBL.getFieldMatchMap(customFieldsBeans); } catch (ImportExceptionList importExceptionList) { LOGGER.error("Getting the field match map failed "); JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true)); return null; } /** * dropdown parser */ LOGGER.debug("Parsing the external dropdowns"); SortedMap<String, List<ISerializableLabelBean>> externalDropdowns = new ImporterDropdownParser() .parse(importDataFile, fieldsMatcherMap); /** * data parser */ LOGGER.debug("Parsing the items"); List<ExchangeWorkItem> externalReportBeansList = new ImporterDataParser().parse(importDataFile, fieldsMatcherMap); try { LOGGER.debug("Importing the items"); ImportCounts importCounts = TrackImportBL.importWorkItems(externalReportBeansList, externalDropdowns, fieldsMatcherMap, personID, locale); LOGGER.debug("Imported " + importCounts.getNoOfCreatedIssues() + " new issues " + " modified " + importCounts.getNoOfUpdatedIssues()); JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(true, getText("admin.actions.importTp.lbl.result", new String[] { Integer.valueOf(importCounts.getNoOfCreatedIssues()).toString(), Integer.valueOf(importCounts.getNoOfUpdatedIssues()).toString() }), true, locale), false); } catch (ImportExceptionList importExceptionList) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true), false); return null; } catch (ImportException importException) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText(importException.getMessage()), true, locale), false); return null; } catch (Exception e) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText("admin.actions.importTp.err.failed"), true, locale), false); return null; } LOGGER.info("Import done"); return null; }