List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java
private void extractBody(Part Mess, cfArrayData AD, String attachURI, String attachDIR) throws Exception { if (Mess.isMimeType("multipart/*")) { Multipart mp = (Multipart) Mess.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) extractBody(mp.getBodyPart(i), AD, attachURI, attachDIR); } else {/*from ww w.j a v a 2s . c o m*/ cfStructData sd = new cfStructData(); String tmp = Mess.getContentType(); if (tmp.indexOf(";") != -1) tmp = tmp.substring(0, tmp.indexOf(";")); sd.setData("mimetype", new cfStringData(tmp)); String filename = getFilename(Mess); String dispos = getDisposition(Mess); MimeType messtype = new MimeType(tmp); // Note that we can't use Mess.isMimeType() here due to bug #2080 if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && messtype.match("text/*")) { Object content; String contentType = Mess.getContentType().toLowerCase(); // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7 if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) { InputStream ins = Mess.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(ins, bos); content = new String(UTF7Converter.convert(bos.toByteArray())); } else { try { content = Mess.getContent(); } catch (UnsupportedEncodingException e) { content = Mess.getInputStream(); } catch (IOException ioe) { // This will happen on BD/Java when the attachment has no content // NOTE: this is the fix for bug NA#3198. content = ""; } } if (content instanceof InputStream) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy((InputStream) content, bos); sd.setData("content", new cfStringData(new String(bos.toByteArray()))); } else { sd.setData("content", new cfStringData(content.toString())); } sd.setData("file", cfBooleanData.FALSE); sd.setData("filename", new cfStringData(filename == null ? "" : filename)); } else if (attachDIR != null) { sd.setData("content", new cfStringData("")); if (filename == null || filename.length() == 0) filename = "unknownfile"; filename = getAttachedFilename(attachDIR, filename); //--[ An attachment, save it out to disk try { BufferedInputStream in = new BufferedInputStream(Mess.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( cfEngine.thisPlatform.getFileIO().getFileOutputStream(new File(attachDIR + filename))); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); sd.setData("file", cfBooleanData.TRUE); sd.setData("filename", new cfStringData(filename)); if (attachURI.charAt(attachURI.length() - 1) != '/') sd.setData("url", new cfStringData(attachURI + '/' + filename)); else sd.setData("url", new cfStringData(attachURI + filename)); sd.setData("size", new cfNumberData((int) new File(attachDIR + filename).length())); } catch (Exception ignoreException) { // NOTE: this could happen when we don't have permission to write to the specified directory // so let's log an error message to make this easier to debug. cfEngine.log("-] Failed to save attachment to " + attachDIR + filename + ", exception=[" + ignoreException.toString() + "]"); } } else { sd.setData("file", cfBooleanData.FALSE); sd.setData("content", new cfStringData("")); } AD.addElement(sd); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
/** * extract tarfile to constituent parts processing gzips along the way * yyyyMMdd.tar->/yyyyMMdd/INode-CH_RNC01/A2010...gz *//*from w w w .ja v a 2 s .co m*/ protected void untar(File tf) throws FileNotFoundException { try { TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(tf)); TarArchiveEntry t1 = null; while ((t1 = tais.getNextTarEntry()) != null) { if (t1.isDirectory()) { if (t1.getName().contains("account")) identifier = ".vcc"; else identifier = ""; } else { String fn = t1.getName().substring(t1.getName().lastIndexOf("/")); File f = new File(getCalTempPath() + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = tais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); File unz = null; if (f.getName().endsWith("zip")) unz = unzip3(f); else unz = ungzip(f); if (unz != null) allfiles.add(unz); f.delete(); } } tais.close(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
/** * Top unzip method. extract tarfile to constituent parts processing gzips * along the way e.g. yyyyMMdd.zip->/yyyyMMdd/INode-CH_RNC01/A2010...zip *///from w w w . j a v a 2 s .c o m protected void unzip1(File zipfile) throws FileNotFoundException { try { ZipArchiveInputStream zais = new ZipArchiveInputStream(new FileInputStream(zipfile)); ZipArchiveEntry z1 = null; while ((z1 = zais.getNextZipEntry()) != null) { if (z1.isDirectory()) { /*hack to add vcc identifier because fucking ops cant rename a simple file*/ if (z1.getName().contains("account")) identifier = ".vcc"; else identifier = ""; } else { String fn = z1.getName().substring(z1.getName().lastIndexOf("/")); File f = new File(getCalTempPath() + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = zais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); File unz = null; if (f.getName().endsWith("zip")) unz = unzip3(f); else unz = ungzip(f); if (unz != null) allfiles.add(unz); f.delete(); } } zais.close(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
From source file:edu.caltech.ipac.firefly.server.catquery.SDSSQuery.java
@Override protected File loadDataFile(TableServerRequest request) throws IOException, DataAccessException { File outFile;/*from www .j av a2 s. c om*/ try { // votable has utf-16 encoding, which mismatches the returned content type // this confuses tools File csv = createFile(request, ".csv"); String uploadFname = request.getParam(SDSSRequest.FILE_NAME); if (StringUtils.isEmpty(uploadFname)) { URL url = createGetURL(request); URLConnection conn = URLDownload.makeConnection(url); conn.setRequestProperty("Accept", "*/*"); URLDownload.getDataToFile(conn, csv); } else { File uploadFile = ServerContext.convertToFile(uploadFname); File sdssUFile; if (uploadFile.canRead()) { sdssUFile = getSDSSUploadFile(uploadFile); } else { throw new EndUserException("SDSS catalog search failed", "Can not read uploaded file: " + uploadFname); } URL url = new URL(SERVICE_URL_UPLOAD); // use uploadFname //POST http://skyserver.sdss3.org/public/en/tools/crossid/x_crossid.aspx _postBuilder = new MultiPartPostBuilder(url.toString()); if (_postBuilder == null) { throw new EndUserException("Failed to create HTTP POST request", "URL " + SERVICE_URL_UPLOAD); } insertPostParams(request, sdssUFile); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(csv), 10240); MultiPartPostBuilder.MultiPartRespnse resp = null; try { resp = _postBuilder.post(writer); } finally { writer.close(); } if (resp == null) { throw new IOException("Exception during post"); } else if (resp.getStatusCode() < 200 || resp.getStatusCode() > 300) { // throw new IOException(resp.getStatusMsg()); // try repeating the request through CasJobs boolean nearestOnly = request.getBooleanParam(SDSSRequest.NEAREST_ONLY); String radiusArcMin = request.getParam(SDSSRequest.RADIUS_ARCMIN); SDSSCasJobs.getCrossMatchResults(sdssUFile, nearestOnly, radiusArcMin, csv); } } // check for errors in returned file evaluateCVS(csv); DataGroup dg = DsvToDataGroup.parse(csv, CSVFormat.DEFAULT.withCommentStart('#')); if (dg == null) { _log.briefInfo("no data found for search"); return null; } /* //TG No need to decrement up_id, since we are using the original upload id if (!StringUtils.isEmpty(uploadFname) && dg.containsKey("up_id")) { // increment up_id(uploaded id) by 1 if it's an multi object search DataType upId = dg.getDataDefintion("up_id"); for(DataObject row : dg) { int id = StringUtils.getInt(String.valueOf(row.getDataElement(upId)), -1); if (id >= 0) { row.setDataElement(upId, id + 1); } } } */ outFile = createFile(request, ".tbl"); IpacTableWriter.save(outFile, dg); } catch (MalformedURLException e) { _log.error(e, "Bad URL"); throw makeException(e, "SDSS Catalog Query Failed - bad url"); } catch (IOException e) { _log.error(e, e.toString()); throw makeException(e, "SDSS Catalog Query Failed - network Error"); } catch (EndUserException e) { _log.error(e, e.toString()); throw makeException(e, "SDSS Catalog Query Failed - network Error"); } catch (Exception e) { _log.error(e, e.toString()); throw makeException(e, "SDSS Catalog Query Failed"); } return outFile; }
From source file:truesculpt.ui.panels.WebFilePanel.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getManagers().getUtilsManager().updateFullscreenWindowStatus(getWindow()); setContentView(R.layout.webfile);/* ww w. j a va 2 s .c o m*/ getManagers().getUsageStatisticsManager().TrackEvent("OpenFromWeb", "", 1); mWebView = (WebView) findViewById(R.id.webview); mWebView.setWebViewClient(new MyWebViewClient()); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new JavaScriptInterface(this, getManagers()), "Android"); int nVersionCode = getManagers().getUpdateManager().getCurrentVersionCode(); mWebView.loadUrl(mStrBaseWebSite + "?version=" + nVersionCode); mPublishToWebBtn = (Button) findViewById(R.id.publish_to_web); mPublishToWebBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String name = getManagers().getMeshManager().getName(); final File imagefile = new File(getManagers().getFileManager().GetImageFileName()); final File objectfile = new File(getManagers().getFileManager().GetObjectFileName()); getManagers().getUsageStatisticsManager().TrackEvent("PublishToWeb", name, 1); if (imagefile.exists() && objectfile.exists()) { try { final File zippedObject = File.createTempFile("object", "zip"); zippedObject.deleteOnExit(); BufferedReader in = new BufferedReader(new FileReader(objectfile)); BufferedOutputStream out = new BufferedOutputStream( new GZIPOutputStream(new FileOutputStream(zippedObject))); System.out.println("Compressing file"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); long size = 0; size = new FileInputStream(imagefile).getChannel().size(); size += new FileInputStream(zippedObject).getChannel().size(); size /= 1000; final SpannableString msg = new SpannableString( "You will upload your latest saved version of this scupture representing " + size + " ko of data\n\n" + "When clicking the yes button you accept to publish your sculpture under the terms of the creative commons share alike, non commercial license\n" + "http://creativecommons.org/licenses/by-nc-sa/3.0" + "\n\nDo you want to proceed ?"); Linkify.addLinks(msg, Linkify.ALL); AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this); builder.setMessage(msg).setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { PublishPicture(imagefile, zippedObject, name); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dlg = builder.create(); dlg.show(); // Make the textview clickable. Must be called after // show() ((TextView) dlg.findViewById(android.R.id.message)) .setMovementMethod(LinkMovementMethod.getInstance()); } catch (Exception e) { e.printStackTrace(); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this); builder.setMessage( "File has not been saved, you need to save it before publishing\nDo you want to proceed to save window ?") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ((FileSelectorPanel) getParent()).getTabHost().setCurrentTab(2); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } } }); }
From source file:net.sf.jvifm.model.FileModelManager.java
private void extractEntry(InputStream zi, File file) throws Exception { BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file)); while (true) { int n = zi.read(buffer); if (n < 0) break; bf.write(buffer, 0, n);/*from www . ja v a 2s . c o m*/ } bf.close(); }
From source file:com.kuprowski.mogile.multipart.MojiFileItem.java
@Override public void write(File file) throws Exception { BufferedOutputStream out = null; InputStream in = null;/*from www.j av a2s . c o m*/ try { out = new BufferedOutputStream(new FileOutputStream(file)); in = getMojiFile().getInputStream(); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } }
From source file:eu.planets_project.pp.plato.application.AdminAction.java
/** * Renders the given exported XML-Document as HTTP response */// w ww . j a v a 2 s . com private String returnXMLExport(Document doc) { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_kkmmss"); String timestamp = format.format(new Date(System.currentTimeMillis())); String filename = "export_" + timestamp + ".xml"; HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext() .getResponse(); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\""); //response.setContentLength(xml.length()); try { BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); XMLWriter writer = new XMLWriter(out, ProjectExporter.prettyFormat); writer.write(doc); writer.flush(); writer.close(); out.flush(); out.close(); } catch (IOException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error("Could not open response-outputstream: ", e); } FacesContext.getCurrentInstance().responseComplete(); return null; }
From source file:eu.planets_project.pp.plato.action.project.XmlAction.java
public String exportLibrary() { LibraryTree lib = null;// ww w.j ava 2s .co m List<LibraryTree> trees = null; trees = em.createQuery("select l from LibraryTree l where (l.name = 'mainlibrary') ").getResultList(); if ((trees != null) && (trees.size() > 0)) { lib = trees.get(0); } if (lib != null) { // convert project-name to a filename, add date: SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_kkmmss"); String filename = "RequirementsLibrary-" + formatter.format(new Date()); String binarydataTempPath = OS.getTmpPath() + "RequirementsLibrary-" + System.currentTimeMillis() + "/"; File binarydataTempDir = new File(binarydataTempPath); binarydataTempDir.mkdirs(); LibraryExport exp = new LibraryExport(); try { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + ".xml\""); // the length of the resulting XML file is unknown due to formatting: response.setContentLength(xml.length()); try { BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); exp.exportToStream(lib, out); out.flush(); out.close(); } catch (IOException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error("Could not open response-outputstream: ", e); } FacesContext.getCurrentInstance().responseComplete(); } finally { OS.deleteDirectory(binarydataTempDir); } } else { FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "No Library found, create one first."); } System.gc(); return null; }
From source file:net.sf.taverna.cagrid.activity.CaGridActivity.java
/** * Load the trusted caGrid CAs' certificates and store them in * the Truststore and in a special folder (inside Taverna's security * conf folder) so that globus can look them up as well. *///from www .j a va 2 s . c o m private static void loadCaGridCAsCertificates() { // If not already done, import the caGrid Trusted CAs' certificates into Taverna's truststore // Get the location of Taverna's security configuration directory File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory(); File caGridSecConfigDirectory = new File(secConfigDirectory, "cagrid"); caGridSecConfigDirectory.mkdirs(); // Tructes CAs folder File trustedCertsDirectory = new File(caGridSecConfigDirectory, "trusted-certificates"); trustedCertsDirectory.mkdirs(); // Set the system property read by Globus to determine the location // of the folder containing the caGrid trusted CAs' certificates System.setProperty("X509_CERT_DIR", trustedCertsDirectory.getAbsolutePath()); // Get the file which existence implies that caGrid trusted CAs have been loaded File caCertsLoadedFile = new File(caGridSecConfigDirectory, "trustedCAsLoaded.txt"); if (!caCertsLoadedFile.exists() || System.getenv("TWS_USER_PROXY") != null) { logger.info("caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager."); if (System.getenv("TWS_USER_PROXY") == null) { JOptionPane.showMessageDialog(null, "caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.", "CaGrid plugin message", JOptionPane.INFORMATION_MESSAGE); } List<String> certificateResources = new ArrayList<String>(); certificateResources.add("1c3f2ca8.0"); certificateResources.add("62f4fd66.0"); certificateResources.add("68907d53.0"); certificateResources.add("8e3e7e54.0"); certificateResources.add("d1b603c3.0"); certificateResources.add("ed524cf5.0"); certificateResources.add("0ad31d10.0"); certificateResources.add("17e36bb5.0"); certificateResources.add("f3b3491b.0"); certificateResources.add("d0b62510.0");//to be replaced by its CA cert CredentialManager cm = null; try { //TODO something wrong here, needs correction cm = CredentialManager.getInstance(); } catch (CMException cmex) { // We are in deep trouble here - something's wrong with Credential Manager String exMessage = "Failed to instantiate Credential Manager - cannot load caGrid CAs' certificates."; JOptionPane.showMessageDialog(null, exMessage, "CaGrid plugin message", JOptionPane.ERROR_MESSAGE); cmex.printStackTrace(); logger.error(exMessage); return; } for (String certificate : certificateResources) { InputStream certStream = null; try { String certificateResourcePath = "/trusted-certificates/" + certificate; certStream = CaGridActivity.class.getResourceAsStream(certificateResourcePath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); // The following should be able to load PKCS #7 certificate chain files // as well as ASN.1 DER or PEM-encoded (sequences of) certificates Collection<? extends Certificate> chain = cf.generateCertificates(certStream); certStream.close(); // Use only the first cert in the chain - we know there will be only one inside X509Certificate cert = (X509Certificate) chain.iterator().next(); // Save to Credential Manager's Truststore cm.saveTrustedCertificate(cert); // Save to the trusted-certificates directory inside cagrid security conf directory File certificateFile = new File(trustedCertsDirectory, certificate); InputStream certStreamNew = null; BufferedOutputStream fOut = null; try { // Reload the certificate resource certStreamNew = CaGridActivity.class.getResourceAsStream(certificateResourcePath); fOut = new BufferedOutputStream(new FileOutputStream(certificateFile)); IOUtils.copy(certStreamNew, fOut); } catch (Exception ex) { String exMessage = "Failed to save caGrid CA's certificate " + certificate + " to cagrid security folder " + certificateFile + " for globus."; logger.error(exMessage, ex); } finally { if (fOut != null) { try { fOut.close(); } catch (Exception ex) { logger.error("Can't close certificate resource " + certificateFile, ex); } } if (certStreamNew != null) { try { certStreamNew.close(); } catch (Exception ex) { logger.error("Can't close certificate resource " + certificate, ex); } } } } catch (Exception ex) { String exMessage = "Failed to load or save caGrid CA's certificate " + certificate + " to Truststore."; logger.error(exMessage, ex); } } Writer out = null; try { out = new BufferedWriter(new FileWriter(caCertsLoadedFile)); out.write("true"); // just write anything to the file } catch (IOException e) { // ignore } if (out != null) { try { out.close(); } catch (Exception ex) { // ignore } } } }