List of usage examples for java.io FileNotFoundException getMessage
public String getMessage()
From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { String errorMsg = ""; InputStream in = null;/*from w w w . j a va 2 s . c om*/ OutputStream out = null; // load key store file try { char[] pwd = cliProperties.readKeyStorePwd(); File file = new File(KEY_STORE_FILE); if (file.exists() && file.isFile()) { keyStore.load(new FileInputStream(file), pwd); } else { //init an empty keystore keyStore.load(null, pwd); } // show certificate informations MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; String sha1Fingerprint = ""; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest()); sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest()); if (keyStore.getCertificate(md5Fingerprint) != null) { if (i == chain.length - 1) { return; } else { continue; } } System.out.println(); System.out.println("Server Certificate"); System.out.println("================================================================"); System.out.println("Subject: " + cert.getSubjectDN()); System.out.println("Issuer: " + cert.getIssuerDN()); System.out.println("SHA Fingerprint: " + sha1Fingerprint); System.out.println("MD5 Fingerprint: " + md5Fingerprint); System.out.println("Issued on: " + dateFormate.format(cert.getNotBefore())); System.out.println("Expires on: " + dateFormate.format(cert.getNotAfter())); System.out.println("Signature: " + cert.getSignature()); System.out.println(); if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) { throw new CertificateException("The security certificate has expired."); } ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE); // Read user input String readMsg; if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) { readMsg = reader.readLine().trim(); } else { readMsg = "yes"; } if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) { { // add new certificate into key store file. keyStore.setCertificateEntry(md5Fingerprint, cert); out = new FileOutputStream(KEY_STORE_FILE); keyStore.store(out, pwd); CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE); // save keystore password cliProperties.saveKeyStorePwd(pwd); } } else { if (i == chain.length - 1) { throw new CertificateException("Could not find a valid certificate in the keystore."); } else { continue; } } } } catch (FileNotFoundException e) { errorMsg = "Cannot find the keystore file: " + e.getMessage(); } catch (NoSuchAlgorithmException e) { errorMsg = "SSL Algorithm not supported: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMsg = "IO error: " + e.getMessage(); } catch (KeyStoreException e) { errorMsg = "Keystore error: " + e.getMessage(); } catch (ConfigurationException e) { errorMsg = "cli.properties access error: " + e.getMessage(); } finally { if (!CommandsUtils.isBlank(errorMsg)) { System.out.println(errorMsg); logger.error(errorMsg); } if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Input stream of serengeti.keystore close failed."); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of serengeti.keystore close failed."); } } } }
From source file:com.sap.dirigible.repository.ext.db.DBUtils.java
/** * Read whole SQL script from the class path. It can contain multiple * statements separated with ';'/*from ww w . jav a 2 s.com*/ * * @param path * @return the SQL script as a String */ public String readScript(Connection conn, String path, Class<?> clazz) throws IOException { logger.debug("entering readScript"); //$NON-NLS-1$ String sql = null; InputStream in = clazz.getResourceAsStream(path); if (in == null) { throw new IOException("SQL script does not exist: " + path); } BufferedInputStream bufferedInput = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); byte[] buffer = new byte[1024]; try { bufferedInput = new BufferedInputStream(in); int bytesRead = 0; while ((bytesRead = bufferedInput.read(buffer)) != -1) { String chunk = new String(buffer, 0, bytesRead, Charset.defaultCharset()); writer.write(chunk); } writer.flush(); sql = new String(baos.toByteArray(), Charset.defaultCharset()); String productName = conn.getMetaData().getDatabaseProductName(); IDialectSpecifier dialectSpecifier = getDialectSpecifier(productName); sql = dialectSpecifier.specify(sql); } catch (FileNotFoundException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (SQLException ex) { logger.error(ex.getMessage()); } finally { try { if (bufferedInput != null) bufferedInput.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } } logger.debug("exiting readScript"); //$NON-NLS-1$ return sql; }
From source file:gov.redhawk.core.filemanager.filesystem.JavaFileSystem.java
@Override public CF.File create(final String fileName) throws InvalidFileName, FileException { if ("".equals(fileName)) { throw new InvalidFileName(ErrorNumberType.CF_EIO, ""); }//from w w w.j a v a 2 s. c o m final File file = new File(this.root, fileName); if (file.exists()) { throw new FileException(ErrorNumberType.CF_EEXIST, "File already exists of the name: " + fileName); } try { final JavaFileFileImpl impl = new JavaFileFileImpl(file, false); final byte[] id = this.poa.activate_object(impl); return FileHelper.narrow(this.poa.id_to_reference(id)); } catch (final FileNotFoundException e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final ServantAlreadyActive e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final WrongPolicy e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final ObjectNotActive e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } }
From source file:gov.redhawk.core.filemanager.filesystem.JavaFileSystem.java
@Override public CF.File open(final String fileName, final boolean readOnly) throws InvalidFileName, FileException { final File file = new File(this.root, fileName); if (!file.exists()) { throw new FileException(ErrorNumberType.CF_ENOENT, "No such file or directory\n"); }// w w w .j a v a 2 s. c om if (file.isDirectory()) { throw new FileException(ErrorNumberType.CF_ENOENT, "Can not open a directory\n"); } try { final JavaFileFileImpl impl = new JavaFileFileImpl(file, readOnly); final byte[] id = this.poa.activate_object(impl); return FileHelper.narrow(this.poa.id_to_reference(id)); } catch (final FileNotFoundException e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final ServantAlreadyActive e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final WrongPolicy e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } catch (final ObjectNotActive e) { throw new FileException(ErrorNumberType.CF_EIO, e.getMessage()); } }
From source file:com.sec.ose.osi.thread.job.identify.data.IdentifyQueue.java
public boolean makeBackup() { if (this.size() <= 0) return true; String originalFilePath = identifyQueueFilePath; String backupFilePath = originalFilePath + ".backup." + FormatUtil.getTimeForLicenseNotice(); try {/*from www . j a v a 2s.c om*/ FileOperator.copyFile(new File(originalFilePath), new File(backupFilePath)); } catch (FileNotFoundException e) { log.error(e.getMessage()); return false; } return true; }
From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java
protected void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w . ja v a2s. co m*/ if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(response.SC_BAD_REQUEST); return; } String media = null, type = null; FileItemFactory fiF = new DiskFileItemFactory(); ServletFileUpload sfU = new ServletFileUpload(fiF); List<FileItem> fileItems = new LinkedList<FileItem>(); Iterator i = sfU.parseRequest(request).iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("media")) media = item.getString(); else if (item.getFieldName().equals("type")) type = item.getString(); } else if (item.getName().matches(zipExtRegex)) { processZipFileItem(fiF, item, fileItems); } else if (uploadFileNameFilter.accept(null, item.getName())) { fileItems.add(item); } } if (fileItems.size() == 0) { setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload"); return; } processFileItemList(fileItems, media, type); int len = fileItems.size(); setTextResponse(response, response.SC_OK, "Successfully uploaded " + len + " file" + (len > 1 ? "s" : "")); } catch (FileNotFoundException fnfE) { setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage()); } catch (IllegalArgumentException iaE) { setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage()); } catch (FileUploadException fuE) { setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage()); } }
From source file:com.michaeljones.hellohadoop.restclient.HadoopHdfsRestClient.java
public HttpMethodFuture GetRedirectLocationAsync(String remoteRelativePath, String localPath) { // %1 nameNodeHost, %2 username %3 resource. String uri = String.format(BASIC_URL_FORMAT, nameNodeHost, username, remoteRelativePath); List<Pair<String, String>> queryParams = new ArrayList(); queryParams.add(new Pair<>("user.name", username)); queryParams.add(new Pair<>("op", "CREATE")); queryParams.add(new Pair<>("overwrite", "true")); try {/*w w w. j a v a 2 s .c o m*/ return restImpl.GetRedirectLocationAsync(uri, localPath, queryParams); } catch (FileNotFoundException ex) { LOGGER.error("Hadoop get redirect location async file not found: " + ex.getMessage()); throw new RuntimeException("Create File failed : " + ex.getMessage()); } }
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String) *//*from www. ja va 2s. c o m*/ public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#returnKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } KeyPair keyPair = null; InputStream pubStream = null; InputStream privStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { throw new KeyManagementException("Configured key directory does not exist and unable to create it"); } File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if ((publicFile.exists()) && (privateFile.exists())) { privStream = new FileInputStream(privateFile); byte[] privKeyBytes = IOUtils.toByteArray(privStream); pubStream = new FileInputStream(publicFile); byte[] pubKeyBytes = IOUtils.toByteArray(pubStream); // files exist KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm()); // generate private key PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes); PrivateKey privKey = keyFactory.generatePrivate(privateSpec); // generate pubkey X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(publicSpec); // make the keypair keyPair = new KeyPair(pubKey, privKey); } else { // files dont exist throw new KeyManagementException("Failed to locate user keys"); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (InvalidKeySpecException iksx) { throw new KeyManagementException(iksx.getMessage(), iksx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (privStream != null) { IOUtils.closeQuietly(privStream); } if (pubStream != null) { IOUtils.closeQuietly(pubStream); } } return keyPair; }
From source file:com.doplgangr.secrecy.FileSystem.File.java
public java.io.File readFile(CryptStateListener listener) { decrypting = true;/* w w w.j a v a2s .c om*/ InputStream is = null; OutputStream out = null; java.io.File outputFile = null; try { outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder()); outputFile.mkdirs(); outputFile.createNewFile(); AES_Encryptor enc = new AES_Encryptor(key); is = new CipherInputStream(new FileInputStream(file), enc.decryptstream()); listener.setMax((int) file.length()); ReadableByteChannel inChannel = Channels.newChannel(is); FileChannel outChannel = new FileOutputStream(outputFile).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize); while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) { byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.compact(); listener.updateProgress((int) outChannel.size()); } inChannel.close(); outChannel.close(); Util.log(outputFile.getName(), outputFile.length()); return outputFile; } catch (FileNotFoundException e) { listener.onFailed(2); Util.log("Encrypted File is missing", e.getMessage()); } catch (IOException e) { Util.log("IO Exception while decrypting", e.getMessage()); if (e.getMessage().contains("pad block corrupted")) listener.onFailed(1); else e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { listener.Finished(); decrypting = false; try { if (is != null) { is.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } // An error occured. Too Bad if (outputFile != null) storage.purgeFile(outputFile); return null; }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.environment.UnixFileEnvironmentRepository.java
public void save(final String backupFileName, ConfigResponse config, Environment environment) throws PluginException { BufferedReader envFileReader = null; FileOutputStream newSetEnv = null; try {/*from w w w . jav a 2 s .com*/ try { envFileReader = new BufferedReader(new FileReader(backupFileName)); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save setenv. Error parsing existing file. Cause: " + e.getMessage()); } try { newSetEnv = new FileOutputStream(Metric.decode(config.getValue("installpath")) + "/bin/setenv.sh"); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save setenv. Error writing to existing file. Cause: " + e.getMessage()); } // write backup file to setenv, replacing existing JVM_OPTS line String line; try { line = envFileReader.readLine(); boolean processedJavaHome = false; for (; line != null; line = envFileReader.readLine()) { if (line.trim().startsWith("JVM_OPTS")) { while (line != null && !line.trim().endsWith("\"")) { line = envFileReader.readLine(); } writeJvmOpts(environment, newSetEnv); continue; } else if (line.trim().startsWith("JAVA_HOME") || line.trim().startsWith("#JAVA_HOME")) { processedJavaHome = true; writeJavaHome(environment, newSetEnv); } else { newSetEnv.write(line.getBytes()); newSetEnv.write("\n".getBytes()); } } if (!processedJavaHome) { // append JAVA_HOME even if it is not already in the file writeJavaHome(environment, newSetEnv); } newSetEnv.flush(); newSetEnv.getFD().sync(); } catch (IOException e) { throw new PluginException("Error writing JVM options to setenv. Cause: " + e.getMessage()); } } finally { try { if (envFileReader != null) { envFileReader.close(); } } catch (IOException e) { logger.warn("Error closing reader to backup setenv file. Cause: " + e.getMessage()); } try { if (newSetEnv != null) { newSetEnv.close(); } } catch (IOException e) { logger.warn("Error closing output stream to setenv file. Cause: " + e.getMessage()); } } }