List of usage examples for java.io FileOutputStream flush
public void flush() throws IOException
From source file:com.scanvine.android.util.SVDownloadManager.java
private boolean fetchFile(Context context, String urlString, File localFile) { try {/*www . jav a 2 s . c o m*/ InputStream is = getStreamFor(urlString); FileOutputStream out = new FileOutputStream(localFile); byte[] buffer = new byte[4096]; int len = 0; while ((len = is.read(buffer)) >= 0) { out.write(buffer, 0, len); } out.flush(); out.close(); return true; } catch (Exception ex) { Log.e("" + this, "fetchFile failed", ex); return false; } }
From source file:com.rabross.android.minecraftskinwidget.ImageDownloader.java
/** * Write bitmap associated with a url to disk cache *//*from w ww .ja v a2 s.c om*/ private void putBitmapInDiskCache(String name, String url, Bitmap bitmap) { try { File cacheFile = new File(mContext.getCacheDir(), String.valueOf(getCacheName(name, url, true))); FileOutputStream fos = new FileOutputStream(cacheFile); bitmap.compress(CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); cacheFile.length(); } catch (Exception e) { Log.e(TAG, "Error when saving image to cache. ", e); } }
From source file:org.yestech.publish.publisher.LocalFileSystemPublisher.java
@Override public void publish(IFileArtifact artifact) { IFileArtifactMetaData metaData = artifact.getArtifactMetaData(); InputStream artifactStream = artifact.getStream(); Pair<String, String> names = metaData.getUniqueNames(); String uniquePath = generateUniqueIdentifier(metaData.getArtifactOwner()); if (names != null) { String path = names.getFirst(); if (StringUtils.isNotBlank(path)) { uniquePath = path;// w w w .j a va 2 s. c o m } } File fullPath = new File(directory + File.separator + uniquePath); if (!fullPath.exists()) { fullPath.mkdirs(); } String uniqueFileName = generateUniqueIdentifier(metaData); if (names != null) { String fileName = names.getSecond(); if (StringUtils.isNotBlank(fileName)) { uniqueFileName = fileName; } } String location = fullPath.getAbsolutePath() + File.separator + uniqueFileName; FileOutputStream outputStream = null; try { if (logger.isDebugEnabled()) { logger.debug("Saving file: " + location); } outputStream = openOutputStream(new File(location)); IOUtils.copyLarge(artifactStream, outputStream); outputStream.flush(); if (logger.isDebugEnabled()) { logger.debug("Saved file: " + location); } } catch (IOException e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(artifactStream); IOUtils.closeQuietly(outputStream); PublishUtils.reset(artifact); } if (StringUtils.isBlank(metaData.getLocation())) { metaData.setLocation(location); } }
From source file:cServ.AltaDoc.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j a v a 2 s .c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { System.out.println("hit altadoc"); //begin database operation String nomArch = ""; String nombre = ""; String contra = ""; int id = 0; System.out.println(request.getParameter("idprofe")); String displayString = "Contrasea incorrecta"; String divColor = "danger"; String rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; //start file up FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } for (Iterator it = items.iterator(); it.hasNext();) { DiskFileItem diskFileItem = (DiskFileItem) it.next(); if (diskFileItem.isFormField()) { String fieldname = diskFileItem.getFieldName(); String fieldvalue = diskFileItem.getString(); System.out.println("fn: " + fieldname + " fv " + fieldvalue); if (fieldname.equals("nombre")) { nombre = fieldvalue; } else if (fieldname.equals("contra")) { contra = fieldvalue; } else if (fieldname.equals("idprofe")) { id = Integer.parseInt(fieldvalue); } } else { //start getpath String relativeWebPath = "/../../web/pages/profesor/adminDocsPanels/docDump/"; System.out.println("relative thing " + getServletContext().getRealPath(relativeWebPath)); System.out.println(relativeWebPath); String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath); System.out.println("complete path " + absoluteDiskPath + "\\" + nomArch); absoluteDiskPath += "\\" + nomArch; //end getpath byte[] fileBytes = diskFileItem.get(); nomArch = diskFileItem.getName(); File file = new File(absoluteDiskPath + diskFileItem.getName()); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(fileBytes); fileOutputStream.flush(); } } //end file up //start db insertion Validator valid = new Validator(); valid.ValidatePDF(nomArch); if (valid.isValid() == true) { String adString = altaDoc(id, nomArch); if (adString.equals("operacion realizada")) { displayString = "Documento dado de alta"; divColor = "success"; rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; } } else { displayString = "Archivo no vlido"; divColor = "danger"; rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; } //end db insertion out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<link rel=\"stylesheet\" href=\"css/style.css\">"); out.println("<title>Servlet AltaGrupo</title>"); out.println("</head>"); out.println("<body>"); out.println("<div class=\"container\">\n" + " <div class=\"row\">\n" + " <br><br>\n" + " <div class=\"panel panel-" + divColor + "\">\n" + " <div class=\"panel-heading\">\n" + " <h3 class=\"panel-title\">Espera</h3>\n" + " </div>\n" + " <div class=\"panel-body\">\n" + " " + displayString + " \n" + " </div>\n" + " </div>\n" + " </div>\n" + " </div>"); out.println(rdrUrl); out.println("</body>"); out.println("</html>"); //end database operation } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.openkm.extension.servlet.ZohoServlet.java
/** * //www .j a v a2 s . c om */ private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, IOException, OKMException { Map<String, String> result = new HashMap<String, String>(); File tmp = null; try { String path = OKMRepository.getInstance().getNodePath(null, nodeUuid); String fileName = PathUtils.getName(path); tmp = File.createTempFile("okm", ".tmp"); InputStream is = OKMDocument.getInstance().getContent(null, path, false); Document doc = OKMDocument.getInstance().getProperties(null, path); FileOutputStream fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); fos.close(); String id = UUID.randomUUID().toString(); String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload"; Part[] parts = { new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY), new StringPart("output", "url"), new StringPart("mode", "normaledit"), new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY), new StringPart("lang", lang), new StringPart("id", id), new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl) }; PostMethod filePost = new PostMethod(zohoUrl); filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { log.debug("OK: " + filePost.getResponseBodyAsString()); ZohoToken zot = new ZohoToken(); zot.setId(id); zot.setUser(getThreadLocalRequest().getRemoteUser()); zot.setNode(nodeUuid); zot.setCreation(Calendar.getInstance()); ZohoTokenDAO.create(zot); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream())); String line; while ((line = rd.readLine()) != null) { if (line.startsWith("URL=")) { result.put("url", line.substring(4)); result.put("id", id); break; } } rd.close(); } else { String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString(); log.error("ERROR: {}", error); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error); } } finally { FileUtils.deleteQuietly(tmp); } return result; }
From source file:org.opensaml.util.http.HttpResource.java
/** * Saves the resource data to the backup file. When this method is invoked a temp file is created, the data written * to it, and then the existing backup file is deleted and the temp file renamed to the backup file. * //from ww w. j av a 2 s.c o m * @param data resource data to be written to the backup file * * @throws IOException thrown if there is a problem writing the backup file (e.g. if the process does not have write * permission to the backup file) */ private void saveToBackupFile(final byte[] data) throws IOException { log.debug("Saving backup of response to {}", backupFile.getAbsolutePath()); final File tmpFile = File.createTempFile(Integer.toString(resourceUrl.hashCode()), null); final FileOutputStream out = new FileOutputStream(tmpFile); out.write(data); out.flush(); CloseableSupport.closeQuietly(out); backupFile.delete(); tmpFile.renameTo(backupFile); log.debug("Wrote {} bytes to backup file {}", backupFile.length(), backupFile.getAbsolutePath()); }
From source file:de.appplant.cordova.plugin.notification.Asset.java
/** *Get Uri for HTTP Content/*from ww w . j a v a2 s. c o m*/ * @param path HTTP adress * @return Uri of the downloaded file */ private Uri getUriForHTTP(String path) { try { URL url = new URL(path); String fileName = path.substring(path.lastIndexOf('/') + 1); String resName = fileName.substring(0, fileName.lastIndexOf('.')); String extension = path.substring(path.lastIndexOf('.')); File dir = activity.getExternalCacheDir(); if (dir == null) { Log.e("Asset", "Missing external cache dir"); return Uri.EMPTY; } String storage = dir.toString() + STORAGE_FOLDER; File file = new File(storage, resName + extension); new File(storage).mkdir(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); FileOutputStream outStream = new FileOutputStream(file); copyFile(input, outStream); outStream.flush(); outStream.close(); return Uri.fromFile(file); } catch (MalformedURLException e) { Log.e("Asset", "Incorrect URL"); e.printStackTrace(); } catch (FileNotFoundException e) { Log.e("Asset", "Failed to create new File from HTTP Content"); e.printStackTrace(); } catch (IOException e) { Log.e("Asset", "No Input can be created from http Stream"); e.printStackTrace(); } return Uri.EMPTY; }
From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java
/** * @param mapping/* w ww . ja va2 s . co m*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward exportCertificate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String sel = ((ShowKeyStoreForm) form).getSelectedItem(); KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore(); FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil .getPageInterceptListenerById(request.getSession(), "fileDownload"); if (l == null) { l = new FileDownloadPageInterceptListener(); CoreUtil.addPageInterceptListener(request.getSession(), l); } File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".cer"); FileOutputStream out = new FileOutputStream(clientCertFile); X509Certificate cert = (X509Certificate) systemClientStore.getCertificate(sel); out.write(cert.getEncoded()); out.flush(); out.close(); l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream", mapping.findForward("success"), "exportCertificate.message", "keystore", sel)); return mapping.findForward("success"); }
From source file:de.tor.tribes.types.UserProfile.java
public boolean storeProfileData() { String profileDir = getProfileDirectory(); if (!new File(profileDir).exists()) { if (!new File(profileDir).mkdirs()) { logger.error("Failed to create profile directory"); return false; }//from ww w.j a va 2 s. c o m } FileOutputStream fout = null; try { fout = new FileOutputStream(getProfileDirectory() + "/profile.properties"); mProperties.store(fout, ""); fout.flush(); } catch (Exception e) { logger.error("Failed to store profile properties", e); return false; } finally { try { if (fout != null) { fout.close(); fout = null; } } catch (IOException ignored) { } } return true; }
From source file:com.l2jfree.loginserver.L2LoginIdentifier.java
private synchronized void load() { if (isLoaded()) return;// www . j a v a 2 s .c om File f = new File(System.getProperty("user.home", null), FILENAME); ByteBuffer bb = ByteBuffer.allocateDirect(8); if (!f.exists() || f.length() != 8) { _uid = getRandomUID(); _loaded = true; _log.info("A new UID has been generated for this login server."); FileOutputStream fos = null; try { f.createNewFile(); fos = new FileOutputStream(f); FileChannel fc = fos.getChannel(); bb.putLong(getUID()); bb.flip(); fc.write(bb); fos.flush(); } catch (IOException e) { _log.warn("Could not store login server's UID!", e); } finally { IOUtils.closeQuietly(fos); f.setReadOnly(); } } else { FileInputStream fis = null; try { fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); fc.read(bb); } catch (IOException e) { _log.warn("Could not read stored login server's UID!", e); } finally { IOUtils.closeQuietly(fis); } if (bb.position() > 0) { bb.flip(); _uid = bb.getLong(); } else _uid = getRandomUID(); _loaded = true; } }