List of usage examples for java.io FileNotFoundException toString
public String toString()
From source file:org.cerberus.engine.execution.impl.RecorderService.java
@Override public TestCaseExecutionFile recordSeleniumLog(TestCaseExecution testCaseExecution) { TestCaseExecutionFile object = null; // Used for logging purposes String logPrefix = Infos.getInstance().getProjectNameAndVersion() + " - "; if (testCaseExecution.getApplicationObj().getType().equals("GUI")) { if (testCaseExecution.getSeleniumLog() == 2 || (testCaseExecution.getSeleniumLog() == 1 && !testCaseExecution.getControlStatus().equals("OK"))) { LOG.debug(logPrefix + "Starting to save Selenium log file."); try { Recorder recorder = this.initFilenames(testCaseExecution.getId(), null, null, null, null, null, null, null, 0, "selenium_log", "txt"); File dir = new File(recorder.getFullPath()); dir.mkdirs();//from w w w .j a va2 s . com File file = new File(recorder.getFullFilename()); FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); for (String element : this.webdriverService .getSeleniumLog(testCaseExecution.getSession())) { out.writeBytes(element); } byte[] bytes = baos.toByteArray(); fileOutputStream.write(bytes); out.close(); baos.close(); fileOutputStream.close(); // Index file created to database. object = testCaseExecutionFileFactory.create(0, testCaseExecution.getId(), recorder.getLevel(), "Selenium log", recorder.getRelativeFilenameURL(), "TXT", "", null, "", null); testCaseExecutionFileService.save(object); } catch (FileNotFoundException ex) { LOG.error(logPrefix + ex.toString()); } catch (IOException ex) { LOG.error(logPrefix + ex.toString()); } LOG.debug(logPrefix + "Selenium log recorded in : " + recorder.getRelativeFilenameURL()); } catch (CerberusException ex) { LOG.error(logPrefix + ex.toString()); } } } else { LOG.debug(logPrefix + "Selenium Log not recorded because test on non GUI application"); } return object; }
From source file:de.mpg.escidoc.pubman.viewItem.bean.FileBean.java
/** * Prepares the file the user wants to download * /*from w w w . j a va 2 s .c o m*/ */ public String downloadFile() { try { LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication() .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper"); String fileLocation = ServiceLocator.getFrameworkUrl() + this.file.getContent(); String filename = this.file.getName(); // Filename suggested in browser Save As dialog filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed by the http-response (filename will be cutted after the first empty space) String contentType = this.file.getMimeType(); // For dialog, try System.out.println("MIME: " + contentType); // application/x-download FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); if (this.file.getDefaultMetadata() != null) { response.setContentLength(this.file.getDefaultMetadata().getSize()); } response.setContentType(contentType); System.out.println("MIME: " + response.getContentType()); byte[] buffer = null; if (this.file.getDefaultMetadata() != null) { try { GetMethod method = new GetMethod(fileLocation); method.setFollowRedirects(false); if (loginHelper.getESciDocUserHandle() != null) { // downloading by account user addHandleToMethod(method, loginHelper.getESciDocUserHandle()); } // Execute the method with HttpClient. HttpClient client = new HttpClient(); ProxyHelper.setProxy(client, fileLocation); //???? client.executeMethod(method); OutputStream out = response.getOutputStream(); InputStream input = method.getResponseBodyAsStream(); try { if (this.file.getDefaultMetadata() != null) { buffer = new byte[this.file.getDefaultMetadata().getSize()]; int numRead; long numWritten = 0; while ((numRead = input.read(buffer)) != -1) { out.write(buffer, 0, numRead); out.flush(); numWritten += numRead; } facesContext.responseComplete(); } } catch (IOException e1) { logger.debug("Download IO Error: " + e1.toString()); } input.close(); out.close(); } catch (FileNotFoundException e) { logger.debug("File not found: " + e.toString()); } } } catch (Exception e) { logger.debug("File Download Error: " + e.toString()); System.out.println(e.toString()); } return null; }
From source file:org.atricore.idbus.idojos.serializedsessionstore.SerializedSessionStore.java
private synchronized void load() throws SSOSessionException { // Check again, just in case other thread loaded the store while we were waiting for the lock if (_loaded)/*from w w w .j a va 2 s. c om*/ return; FileInputStream in = null; ObjectInputStream s = null; logger.info("Loading serialized sessions from file : " + getSerializedFile()); try { in = new FileInputStream(getSerializedFile()); s = new ObjectInputStream(in); _sessions = (HashMap) s.readObject(); Iterator i = _sessions.values().iterator(); while (i.hasNext()) { BaseSession ssoSession = (BaseSession) i.next(); super.save(ssoSession); } } catch (FileNotFoundException e) { if (logger.isDebugEnabled()) logger.debug("[checkLoad()] FileNotFoundeException : " + getSerializedFile()); // no serialized sessions found. Create it _sessions = new HashMap(); saveSerializedSessions(); } catch (Exception e) { logger.warn( "Can't load serialized sessions from " + getSerializedFile() + " : " + e.getMessage() != null ? e.getMessage() : e.toString(), e); // no serialized sessions found. Create it _sessions = new HashMap(); saveSerializedSessions(); } finally { if (in != null) try { in.close(); } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("I/O after loading ... " + e.getMessage(), e); } _loaded = true; } }
From source file:org.etudes.component.app.melete.MeleteAbstractExportServiceImpl.java
/** * creates file from input path to output path * @param inputpath - input path for file * @param outputpath - output path for file * @throws Exception/* w w w . j a va2 s .co m*/ */ public void createFile(String inputurl, String outputurl) throws Exception { FileInputStream in = null; FileOutputStream out = null; try { File inputFile = new File(inputurl); File outputFile = new File(outputurl); in = new FileInputStream(inputFile); out = new FileOutputStream(outputFile); int c; int len; byte buf[] = new byte[102400]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { logger.debug(e.toString()); } catch (IOException e) { throw e; } finally { try { if (in != null) in.close(); } catch (IOException e1) { } try { if (out != null) out.close(); } catch (IOException e2) { } } }
From source file:de.mpg.mpdl.inge.pubman.web.viewItem.bean.FileBean.java
/** * Prepares the file the user wants to download * //from w w w. j a v a2s . c om */ public String downloadFile() { try { LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication() .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper"); String fileLocation = PropertyReader.getFrameworkUrl() + this.file.getContent(); String filename = this.file.getName(); // Filename suggested in browser Save As dialog filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed // by the http-response (filename will be cutted after // the first empty space) String contentType = this.file.getMimeType(); // For dialog, try System.out.println("MIME: " + contentType); // application/x-download FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); if (this.file.getDefaultMetadata() != null) { response.setContentLength(this.file.getDefaultMetadata().getSize()); } response.setContentType(contentType); System.out.println("MIME: " + response.getContentType()); byte[] buffer = null; if (this.file.getDefaultMetadata() != null) { try { GetMethod method = new GetMethod(fileLocation); method.setFollowRedirects(false); if (loginHelper.getESciDocUserHandle() != null) { // downloading by account user addHandleToMethod(method, loginHelper.getESciDocUserHandle()); } // Execute the method with HttpClient. HttpClient client = new HttpClient(); ProxyHelper.setProxy(client, fileLocation); // ???? client.executeMethod(method); OutputStream out = response.getOutputStream(); InputStream input = method.getResponseBodyAsStream(); try { if (this.file.getDefaultMetadata() != null) { buffer = new byte[this.file.getDefaultMetadata().getSize()]; int numRead; long numWritten = 0; while ((numRead = input.read(buffer)) != -1) { out.write(buffer, 0, numRead); out.flush(); numWritten += numRead; } facesContext.responseComplete(); } } catch (IOException e1) { logger.debug("Download IO Error: " + e1.toString()); } input.close(); out.close(); } catch (FileNotFoundException e) { logger.debug("File not found: " + e.toString()); } } } catch (Exception e) { logger.debug("File Download Error: " + e.toString()); System.out.println(e.toString()); } return null; }
From source file:my.madet.function.HttpParser.java
public void SaveToSdCard(String fileName, String str) { File file = new File(Environment.getExternalStorageDirectory(), fileName); FileOutputStream fos;/* w w w. j a v a 2 s . co m*/ // use FileWriter to write file /* * FileWriter fw = new FileWriter(file.getAbsoluteFile()); * BufferedWriter bw = new BufferedWriter(fw); */ byte[] data = str.getBytes(); try { if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); fos.write(data); fos.flush(); fos.close(); } catch (FileNotFoundException e) { // handle exception Log.e("SaveToSdCard", "File Not found exception"); } catch (IOException e) { // handle exception Log.e("SaveToSdCard", "Exception" + e.toString()); } }
From source file:com.jaeksoft.searchlib.crawler.web.spider.Crawl.java
/** * Download the file and extract content informations * /* ww w. j ava2 s .co m*/ * @param httpDownloader */ public DownloadItem download(HttpDownloader httpDownloader) { synchronized (this) { InputStream is = null; DownloadItem downloadItem = null; try { URL url = urlItem.getURL(); if (url == null) throw new MalformedURLException("Malformed URL: " + urlItem.getUrl()); // URL normalisation URI uri = url.toURI(); url = uri.toURL(); credentialItem = credentialManager == null ? null : credentialManager.matchCredential(url); List<CookieItem> cookieList = cookieManager.getCookies(url.toExternalForm()); downloadItem = ClientCatalog.getCrawlCacheManager().loadCache(uri); boolean fromCache = (downloadItem != null); if (!fromCache) downloadItem = httpDownloader.get(uri, credentialItem, null, cookieList); else if (Logging.isDebug) Logging.debug("Crawl cache deliver: " + uri); urlItem.setContentDispositionFilename(downloadItem.getContentDispositionFilename()); urlItem.setContentBaseType(downloadItem.getContentBaseType()); urlItem.setContentTypeCharset(downloadItem.getContentTypeCharset()); urlItem.setContentEncoding(downloadItem.getContentEncoding()); urlItem.setContentLength(downloadItem.getContentLength()); urlItem.setLastModifiedDate(downloadItem.getLastModified()); urlItem.setFetchStatus(FetchStatus.FETCHED); urlItem.setHeaders(downloadItem.getHeaders()); Integer code = downloadItem.getStatusCode(); if (code == null) throw new IOException("Http status is null"); urlItem.setResponseCode(code); redirectUrlLocation = downloadItem.getRedirectLocation(); if (redirectUrlLocation != null) urlItem.setRedirectionUrl(redirectUrlLocation.toURL().toExternalForm()); urlItem.setBacklinkCount(config.getUrlManager().countBackLinks(urlItem.getUrl())); if (code >= 200 && code < 300) { if (!fromCache) is = ClientCatalog.getCrawlCacheManager().storeCache(downloadItem); else is = downloadItem.getContentInputStream(); parseContent(is); } else if (code == 301) { urlItem.setFetchStatus(FetchStatus.REDIR_PERM); } else if (code > 301 && code < 400) { urlItem.setFetchStatus(FetchStatus.REDIR_TEMP); } else if (code >= 400 && code < 500) { urlItem.setFetchStatus(FetchStatus.GONE); } else if (code >= 500 && code < 600) { urlItem.setFetchStatus(FetchStatus.HTTP_ERROR); } } catch (FileNotFoundException e) { Logging.info("FileNotFound: " + urlItem.getUrl()); urlItem.setFetchStatus(FetchStatus.GONE); setError("FileNotFound: " + urlItem.getUrl()); } catch (LimitException e) { Logging.warn(e.toString() + " (" + urlItem.getUrl() + ")"); urlItem.setFetchStatus(FetchStatus.SIZE_EXCEED); setError(e.getMessage()); } catch (InstantiationException e) { Logging.error(e.getMessage(), e); urlItem.setParserStatus(ParserStatus.PARSER_ERROR); setError(e.getMessage()); } catch (IllegalAccessException e) { Logging.error(e.getMessage(), e); urlItem.setParserStatus(ParserStatus.PARSER_ERROR); setError(e.getMessage()); } catch (ClassNotFoundException e) { Logging.error(e.getMessage(), e); urlItem.setParserStatus(ParserStatus.PARSER_ERROR); setError(e.getMessage()); } catch (URISyntaxException e) { Logging.warn(e.getMessage(), e); urlItem.setFetchStatus(FetchStatus.URL_ERROR); setError(e.getMessage()); } catch (MalformedURLException e) { Logging.warn(e.getMessage(), e); urlItem.setFetchStatus(FetchStatus.URL_ERROR); setError(e.getMessage()); } catch (IOException e) { Logging.error(e.getMessage(), e); urlItem.setFetchStatus(FetchStatus.ERROR); setError(e.getMessage()); } catch (IllegalArgumentException e) { Logging.error(e.getMessage(), e); urlItem.setFetchStatus(FetchStatus.ERROR); setError(e.getMessage()); } catch (Exception e) { Logging.error(e.getMessage(), e); urlItem.setFetchStatus(FetchStatus.ERROR); setError(e.getMessage()); } finally { IOUtils.close(is); } return downloadItem; } }
From source file:cl.gisred.android.RepartoActivity.java
private void copiarBaseDatos() { String ruta = String.format("%s/db/", getExternalCacheDir().getAbsolutePath()); String archivo = dbName;/*w w w . ja v a 2 s. c om*/ File tempDir = new File(ruta); if (!tempDir.exists()) { tempDir.mkdir(); } else { File[] archivos = tempDir.listFiles(); for (File arch : archivos) arch.delete(); } File archivoDB = new File(ruta + archivo); if (!archivoDB.exists()) { try { FileInputStream fileInputStream = new FileInputStream(getDatabasePath(dbName)); InputStream IS = fileInputStream; OutputStream OS = new FileOutputStream(archivoDB); byte[] buffer = new byte[1024]; int length = 0; while ((length = IS.read(buffer)) > 0) { OS.write(buffer, 0, length); } OS.flush(); OS.close(); IS.close(); } catch (FileNotFoundException e) { Log.e("ERROR", "Archivo no encontrado, " + e.toString()); } catch (IOException e) { Log.e("ERROR", "Error al copiar la Base de Datos, " + e.toString()); } } }
From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java
/** * The <code>MultiPageExecutor</code> method creates multi page searchable pdf using IText. * //from w ww. j a v a2s. c o m * @param batchInstanceThread {@link BatchInstanceThread} thread instance of batch * @param imageHtmlMap {@link Map} map containing image url with corresponding hocr * @param isColoredPDF true for colored image pdf else otherwise * @param isSearchablePDF true for searchable pdf else otherwise * @param pdfFilePath {@link String} path where new pdf has to be created * @param widthOfLine Integer for line width to be used */ public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final Map<String, HocrPage> imageHtmlMap, final boolean isColoredPDF, final boolean isSearchablePDF, final String pdfFilePath, final int widthOfLine, final String[] pages) { if (imageHtmlMap != null && !imageHtmlMap.isEmpty()) { this.pages = new String[pages.length]; this.pages = pages.clone(); batchInstanceThread.add(new AbstractRunnable() { @Override public void run() { String pdf = pdfFilePath; Document document = null; PdfWriter writer = null; FileOutputStream fileOutputStream = null; boolean isPdfSearchable = isSearchablePDF; boolean isColoredImage = isColoredPDF; LOGGER.info("is searchable pdf: " + isPdfSearchable + ", is Colored Image: " + isColoredImage); try { document = new Document(PageSize.LETTER, 0, 0, 0, 0); fileOutputStream = new FileOutputStream(pdf); writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); Set<String> imageSet = imageHtmlMap.keySet(); for (String imageUrl : imageSet) { HocrPage hocrPage = imageHtmlMap.get(imageUrl); String newImageUrl = getCompressedImage(isColoredImage, imageUrl); LOGGER.info("New Image URL: " + newImageUrl); addImageToPdf(writer, hocrPage, newImageUrl, isPdfSearchable, widthOfLine); document.newPage(); (new File(newImageUrl)).delete(); } } catch (FileNotFoundException fileNotFoundException) { LOGGER.error("Error occurred while creating pdf " + pdf + " : " + fileNotFoundException.toString()); } catch (DocumentException documentException) { LOGGER.error( "Error occurred while creating pdf " + pdf + " : " + documentException.toString()); } finally { if (document != null && document.isOpen()) { document.close(); } // Closing pdf writer if (null != writer) { writer.close(); } // Closing file output stream of pdf if (null != fileOutputStream) { try { fileOutputStream.close(); } catch (IOException ioException) { LOGGER.error("Error occurred while closing stream for pdf " + pdf + " : " + ioException.toString()); } } } } }); } }
From source file:edu.utexas.cs.tactex.servercustomers.factoredcustomer.TimeseriesGenerator.java
private void initArima101x101ModelParams() { InputStream paramsStream;/*from w ww. ja v a2s . com*/ String paramsName = tsStructure.modelParamsName; switch (tsStructure.modelParamsSource) { case BUILTIN: throw new Error("Unknown builtin model parameters with name: " + paramsName); // break; case CLASSPATH: paramsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(paramsName); break; case FILEPATH: try { paramsStream = new FileInputStream(paramsName); } catch (FileNotFoundException e) { throw new Error("Could not find file to initialize model parameters: " + paramsName); } break; default: throw new Error("Unexpected reference timeseries source type: " + tsStructure.refSeriesSource); } if (paramsStream == null) throw new Error("Model parameters input stream is uninitialized!"); try { modelParams.load(paramsStream); } catch (java.io.IOException e) { throw new Error("Error reading model parameters from file: " + paramsName + "; caught IOException: " + e.toString()); } Y0 = Double.parseDouble((String) modelParams.get("Y0")); Yd = ParserFunctions.parseDoubleArray((String) modelParams.get("Yd")); Yh = ParserFunctions.parseDoubleArray((String) modelParams.get("Yh")); phi1 = Double.parseDouble((String) modelParams.get("phi1")); Phi1 = Double.parseDouble((String) modelParams.get("Phi1")); theta1 = Double.parseDouble((String) modelParams.get("theta1")); Theta1 = Double.parseDouble((String) modelParams.get("Theta1")); lambda = Double.parseDouble((String) modelParams.get("lambda")); gamma = Double.parseDouble((String) modelParams.get("gamma")); sigma = Double.parseDouble((String) modelParams.get("sigma")); //randomSeedRepo = // (RandomSeedRepo) SpringApplicationContext.getBean("randomSeedRepo"); arimaNoise = new Random(service.getRandomSeedRepo() .getRandomSeed("factoredcustomer.TimeseriesGenerator", SeedIdGenerator.getId(), "ArimaNoise") .getValue()); }