Java Code Examples for java.io.FileNotFoundException#getMessage()

The following examples show how to use java.io.FileNotFoundException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileStreamIterator.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public boolean hasNext() {
  if (mNext != null) {
    return true;
  }
  if (mIt.hasNext()) {
    mNextFile = mIt.next();
    ++mCounter;
    try {
      mNext = FileUtils.createInputStream(mNextFile, true);
      if (mMaxCount == 1) {
        Diagnostic.info("Processing " + mProcessLabel + "\"" + mNextFile + "\"");
      } else {
        Diagnostic.progress(String.format("Processing \"%s\" (%d of %d)", mNextFile, mCounter, mMaxCount));
      }
    } catch (final FileNotFoundException fnfe) {
      throw new NoTalkbackSlimException("The file: \"" + mNextFile.getPath() + "\" either could not be found or could not be opened. The underlying error message is: \"" + fnfe.getMessage() + "\"");
    } catch (final IOException ex) {
      throw new NoTalkbackSlimException(ErrorType.IO_ERROR, "The file: \"" + mNextFile.getPath() + "\" had a problem while reading. The underlying error message is: \"" + ex.getMessage() + "\"");
    }
    return true;
  }
  return false;
}
 
Example 2
Source File: LinuxProcFsStatistics.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
static int init() {
  nonPidFilesInProc = getNumberOfNonProcessProcFiles();
  sys_cpus = Runtime.getRuntime().availableProcessors();
  pageSize = Integer.getInteger(pageSizeProperty, DEFAULT_PAGESIZE);
  cpuStatSingleton = new CpuStat();
  hasProcVmStat = new File("/proc/vmstat").exists();
  hasDiskStats = new File("/proc/diskstats").exists();
  st = new SpaceTokenizer();
  procFile = new File( "/proc/" + NativeCalls.getInstance().getProcessId() + "/stat" );
  try {
    fchannel = new FileInputStream(procFile).getChannel();
  } catch (FileNotFoundException e) {
    throw new GemFireIOException(e.getMessage(), e);
  }
  procFileReader = Channels.newReader(fchannel, Charset.defaultCharset().newDecoder(), -1);
  return 0;
}
 
Example 3
Source File: LinuxProcFsStatistics.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
static int init() {
  nonPidFilesInProc = getNumberOfNonProcessProcFiles();
  sys_cpus = Runtime.getRuntime().availableProcessors();
  pageSize = Integer.getInteger(pageSizeProperty, DEFAULT_PAGESIZE);
  cpuStatSingleton = new CpuStat();
  hasProcVmStat = new File("/proc/vmstat").exists();
  hasDiskStats = new File("/proc/diskstats").exists();
  st = new SpaceTokenizer();
  procFile = new File( "/proc/" + NativeCalls.getInstance().getProcessId() + "/stat" );
  try {
    fchannel = new FileInputStream(procFile).getChannel();
  } catch (FileNotFoundException e) {
    throw new GemFireIOException(e.getMessage(), e);
  }
  procFileReader = Channels.newReader(fchannel, Charset.defaultCharset().newDecoder(), -1);
  return 0;
}
 
Example 4
Source File: ThemeController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 在线拉取主题
 *
 * @param remoteAddr 远程地址
 * @param themeName  主题名称
 * @return JsonResult
 */
@PostMapping(value = "/clone")
@ResponseBody
public JsonResult cloneFromRemote(@RequestParam(value = "remoteAddr") String remoteAddr,
                                  @RequestParam(value = "themeName") String themeName) {
    if (StrUtil.isBlank(remoteAddr) || StrUtil.isBlank(themeName)) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.info-no-complete"));
    }
    try {
        File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
        File themePath = new File(basePath.getAbsolutePath(), "templates/themes");
        String cmdResult = RuntimeUtil.execForStr("git clone " + remoteAddr + " " + themePath.getAbsolutePath() + "/" + themeName);
        if (NOT_FOUND_GIT.equals(cmdResult)) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git"));
        }
        HaloConst.THEMES.clear();
        HaloConst.THEMES = HaloUtils.getThemes();
    } catch (FileNotFoundException e) {
        log.error("Cloning theme failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.clone-theme-failed") + e.getMessage());
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.install-success"));
}
 
Example 5
Source File: LOGBackConfigurer.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize LOGBack from the given URL.
 *
 * @param logConfigLocation the path pointing to the location of the config file.
 * @param installJULBridge  set to true to install SLF4J JUL bridge
 * @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
 */
public static void initLogging(String logConfigLocation, boolean installJULBridge) {
    try {
        String location = resolvePlaceholders(logConfigLocation);

        if (location.indexOf("${") >= 0) {
            throw new IllegalStateException("unable to resolve certain placeholders: " + sanitise(location));
        }
        // clean up location
        location = location.replaceAll("\\\\", "/");
        String notice = "If you are watching the console output, it may stop after this point, if configured to only write to file.";
        Logger.getLogger(LOGBackConfigurer.class.getName()).info("Initializing LOGBack from [" + sanitise(location) + "]. " + notice);

        initLogging(getURL(location), installJULBridge);

    } catch (FileNotFoundException ex) {
        throw new IllegalArgumentException("invalid '" + sanitise(logConfigLocation) + "' parameter: " + ex.getMessage());
    }
}
 
Example 6
Source File: FileAppender.java    From gflogger with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	try {
		encoder = multibyte ? Charset.forName(codepage).newEncoder() : null;
		maxBytesPerChar = multibyte ? (int) Math.floor(encoder.maxBytesPerChar()) : 1;
		createFileChannel();
	} catch (final FileNotFoundException e) {
		throw new RuntimeException(e.getMessage(), e);
	}

	super.start();
}
 
Example 7
Source File: FactoryImpl.java    From opoopress with Apache License 2.0 5 votes vote down vote up
void addConfiguration(File factoryFile) {
    if (factoryFile != null && factoryFile.exists()) {
        try {
            addConfiguration(new FileInputStream(factoryFile));
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }
}
 
Example 8
Source File: TmfTraceStub.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void initTrace(final IResource resource, final String path, final Class<? extends ITmfEvent> type) throws TmfTraceException {
    try {
        fTrace = new RandomAccessFile(path, "r"); //$NON-NLS-1$
    } catch (FileNotFoundException e) {
        throw new TmfTraceException(e.getMessage());
    }
    super.initTrace(resource, path, type);
}
 
Example 9
Source File: PeerCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
void validateParamsAndGenerate(String outputFile, int number) throws IOException {
  try {
    File f = new File(outputFile);
    if (f.exists()) {
      throw new InvalidConfigurationException(
          String.format(
              "Not overwriting existing file %s \nDelete file or use --output-file to point to a file that does not currently exist.",
              outputFile));
    }
    FileWriter fileWriter = new FileWriter(outputFile, Charset.defaultCharset());
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.println("Private Key(Hex)\tPublic Key(Hex)\tPeerId(Base58)");
    for (int i = 0; i < number; i++) {
      PrivKey privKey = KeyKt.generateKeyPair(KEY_TYPE.SECP256K1).component1();
      PubKey pubKey = privKey.publicKey();
      PeerId peerId = PeerId.fromPubKey(pubKey);
      printWriter.println(
          Bytes.wrap(privKey.bytes()).toHexString()
              + "\t"
              + Bytes.wrap(pubKey.bytes()).toHexString()
              + "\t"
              + peerId.toBase58());
    }
    printWriter.close();
  } catch (final FileNotFoundException ex) {
    throw new InvalidConfigurationException(
        "use --output-file to point to a file in an existing directory " + ex.getMessage());
  }
}
 
Example 10
Source File: Dir.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@code MDTM <SP> <pathname> <CRLF>}<br>
 * <p>
 * Returns the date and time of when a file was modified.
 */
public CommandResponse doMDTM(CommandRequest request) {

    // argument check
    if (!request.hasArgument()) {
        return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
    }

    // get filenames
    String fileName = request.getArgument();
    InodeHandle reqFile;
    User user = request.getSession().getUserNull(request.getUser());

    try {
        reqFile = request.getCurrentDirectory().getInodeHandle(fileName, user);
    } catch (FileNotFoundException ex) {
        return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
    }

    try {
        synchronized (DATE_FMT) {
            return new CommandResponse(213,
                    DATE_FMT.format(new Date(reqFile.lastModified())));
        }
    } catch (FileNotFoundException e) {
        return new CommandResponse(550, e.getMessage());
    }

    //out.print(ftpStatus.getResponse(213, request, user, args));
    //} else {
    //	out.write(ftpStatus.getResponse(550, request, user, null));
    //}
}
 
Example 11
Source File: Dir.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public CommandResponse doSITE_FIXSLAVECOUNT(CommandRequest request) {
    try {
        request.getCurrentDirectory().recalcSlaveRefCounts();
    } catch (FileNotFoundException e) {
        return new CommandResponse(500, e.getMessage());
    }
    CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
    return response;
}
 
Example 12
Source File: Dir.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@code MDTM <SP> <pathname> <CRLF>}<br>
 * <p>
 * Returns the date and time of when a file was modified.
 */
public CommandResponse doMDTM(CommandRequest request) {

    // argument check
    if (!request.hasArgument()) {
        return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
    }

    // get filenames
    String fileName = request.getArgument();
    InodeHandle reqFile;
    User user = request.getSession().getUserNull(request.getUser());

    try {
        reqFile = request.getCurrentDirectory().getInodeHandle(fileName, user);
    } catch (FileNotFoundException ex) {
        return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
    }

    try {
        synchronized (DATE_FMT) {
            return new CommandResponse(213,
                    DATE_FMT.format(new Date(reqFile.lastModified())));
        }
    } catch (FileNotFoundException e) {
        return new CommandResponse(550, e.getMessage());
    }

    //out.print(ftpStatus.getResponse(213, request, user, args));
    //} else {
    //	out.write(ftpStatus.getResponse(550, request, user, null));
    //}
}
 
Example 13
Source File: JavaKeystoreKeyProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) {
    try {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_KEY)), model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_PASSWORD_KEY).toCharArray());

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(model.get(JavaKeystoreKeyProviderFactory.KEY_ALIAS_KEY), model.get(JavaKeystoreKeyProviderFactory.KEY_PASSWORD_KEY).toCharArray());
        PublicKey publicKey = KeyUtils.extractPublicKey(privateKey);

        KeyPair keyPair = new KeyPair(publicKey, privateKey);

        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(model.get(JavaKeystoreKeyProviderFactory.KEY_ALIAS_KEY));
        if (certificate == null) {
            certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());
        }

        return createKeyWrapper(keyPair, certificate);
    } catch (KeyStoreException kse) {
        throw new RuntimeException("KeyStore error on server. " + kse.getMessage(), kse);
    } catch (FileNotFoundException fnfe) {
        throw new RuntimeException("File not found on server. " + fnfe.getMessage(), fnfe);
    } catch (IOException ioe) {
        throw new RuntimeException("IO error on server. " + ioe.getMessage(), ioe);
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException("Algorithm not available on server. " + nsae.getMessage(), nsae);
    } catch (CertificateException ce) {
        throw new RuntimeException("Certificate error on server. " + ce.getMessage(), ce);
    } catch (UnrecoverableKeyException uke) {
        throw new RuntimeException("Keystore on server can not be recovered. " + uke.getMessage(), uke);
    }
}
 
Example 14
Source File: CatalogMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Read the catalog to raise any error.
 *
 * @param catalogFile catalog file
 * @throws MojoExecutionException if an error occurred while reading the catalog
 */
private static ArchetypeCatalog readCatalog(File catalogFile) throws MojoExecutionException {
    try {
        return ArchetypeCatalog.read(new FileInputStream(catalogFile));
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException(ex.getMessage(), ex);
    }
}
 
Example 15
Source File: ConnectorCertificateChecker.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean isCertificateRevoked(File certFile, DateTime validOn) throws TechnicalConnectorException {
   try {
      CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
      X509Certificate cert = (X509Certificate)certFactory.generateCertificate(new FileInputStream(certFile));
      return this.isCertificateRevoked(cert, validOn);
   } catch (FileNotFoundException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   } catch (CertificateException var6) {
      throw new CertificateVerificationException(var6.getMessage(), var6);
   }
}
 
Example 16
Source File: Dir.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@code CWD  <SP> <pathname> <CRLF>}<br>
 * <p>
 * This command allows the user to work with a different
 * directory for file storage or retrieval without
 * altering his login or accounting information.  Transfer
 * parameters are similarly unchanged.  The argument is a
 * pathname specifying a directory.
 */
public CommandResponse doCWD(CommandRequest request) {

    if (!request.hasArgument()) {
        return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
    }

    DirectoryHandle newCurrentDirectory;
    User user = request.getSession().getUserNull(request.getUser());

    try {
        DirectoryHandle currentDirectory = request.getCurrentDirectory();
        if (currentDirectory.exists()) {
            // If the current directory exist, proceed as usual
            newCurrentDirectory = currentDirectory.getDirectory(request.getArgument(), user);
        } else {
            // If directly no longer exists (wipe, nuke), try to change from root
            newCurrentDirectory = new DirectoryHandle("/").getDirectory(request.getArgument(), user);
        }
    } catch (FileNotFoundException ex) {
        return new CommandResponse(550, ex.getMessage());
    } catch (ObjectNotValidException e) {
        return new CommandResponse(550, request.getArgument() + ": is not a directory");
    }

    return new CommandResponse(250,
            "Directory changed to " + newCurrentDirectory.getPath(),
            newCurrentDirectory, request.getUser());
}
 
Example 17
Source File: ConnectorCertificateChecker.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean isCertificateRevoked(File certFile, DateTime validOn) throws TechnicalConnectorException {
   try {
      CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
      X509Certificate cert = (X509Certificate)certFactory.generateCertificate(new FileInputStream(certFile));
      return this.isCertificateRevoked(cert, validOn);
   } catch (FileNotFoundException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   } catch (CertificateException var6) {
      throw new CertificateVerificationException(var6.getMessage(), var6);
   }
}
 
Example 18
Source File: Filedownload.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
public static void save(File file) {
	try {
		save(file, MimeTypes.guessContentTypeFromName(file.getName()));
	} catch (FileNotFoundException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 19
Source File: StatementDuration.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
	@see java.sql.ResultSet#next
	@exception SQLException If database access error occurs.
 */
public boolean next() throws SQLException
{
	if (! gotFile)
	{
		gotFile = true;
	    try 
		{
	        inputFileStreamReader = new InputStreamReader(new FileInputStream(inputFileName));
			bufferedReader = new BufferedReader(inputFileStreamReader, 32*1024);
		} 
		catch (FileNotFoundException ex) 
		{
			throw new SQLException(ex.getMessage());
		}

		hashTable = new Hashtable();
	}

	while (true)
	{
		try
		{
			line = bufferedReader.readLine();
		}
		catch (java.io.IOException ioe)
		{
			throw new SQLException(ioe.getMessage());
		}

		if (line == null)
		{
			return false;
		}

		gmtIndex = line.indexOf(GMT_STRING);
		threadIndex = line.indexOf(BEGIN_THREAD_STRING);
		xidIndex = line.indexOf(BEGIN_XID_STRING);
		lccidIndex = line.indexOf(BEGIN_XID_STRING, xidIndex + 1);

		if (gmtIndex != -1 && threadIndex != -1)
		{
			/* Build a row */
			String[] newRow = new String[6];
			for (int index = 1;
				 index <= 5;
				 index++)
			{
				newRow[index - 1] = setupColumn(index);
			}

			/* NOTE: We need to use the LCCID as the key
			 */
			Object previousRow = hashTable.put(newRow[3],
											   newRow);
			if (previousRow == null)
			{
				continue;
			}

			currentRow = (String[]) previousRow;
			
			/* Figure out the duration. */
			Timestamp endTs = Timestamp.valueOf(newRow[0]);
			long end = endTs.getTime() + endTs.getNanos() / 1000000;
			Timestamp startTs = Timestamp.valueOf(currentRow[0]);
			long start = startTs.getTime() + startTs.getNanos() / 1000000;
			currentRow[5] = Long.toString(end - start);

			return true;
		}
	}
}
 
Example 20
Source File: ModuleList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void stepCreate(Map<String,FileObject> xmlfiles, Map<String,Map<String,Object>> dirtyprops) throws IOException {
    LOG.fine("ModuleList: stepCreate");
    for (Map.Entry<String,FileObject> entry : xmlfiles.entrySet()) {
        String cnb = entry.getKey();
        if (! statuses.containsKey(cnb)) {
            FileObject xmlfile = entry.getValue();
            Map<String, Object> props = dirtyprops.get(cnb);
            if (! cnb.equals(props.get("name"))) throw new IOException("Code name mismatch"); // NOI18N
            String jar = (String)props.get("jar"); // NOI18N
            File jarFile;
            try {
                jarFile = findJarByName(jar, cnb);
            } catch (FileNotFoundException fnfe) {
                final File file = new File(fnfe.getMessage());
                ev.log(Events.MISSING_JAR_FILE, file, true);
                final File p = file.getParentFile();
                File[] arr = p.listFiles();
                LOG.log(Level.FINE, "Content of {0} is:", p); // NOI18N
                int cnt = 0;
                if (arr != null) {
                    for (File f : arr) {
                        LOG.log(Level.FINE, "{0}. = {1}", new Object[] { ++cnt, f }); // NOI18N
                    }
                    LOG.log(Level.FINE, "There was {0} files", cnt); // NOI18N
                } else {
                    LOG.fine("Directory does not exist"); // NOI18N
                }
                dirtyprops.remove(cnb); // #159001
                continue;
            }
            Boolean reloadableB = (Boolean)props.get("reloadable"); // NOI18N
            boolean reloadable = (reloadableB != null ? reloadableB.booleanValue() : false);
            Boolean autoloadB = (Boolean)props.get("autoload"); // NOI18N
            boolean autoload = (autoloadB != null ? autoloadB.booleanValue() : false);
            Boolean eagerB = (Boolean)props.get("eager"); // NOI18N
            boolean eager = (eagerB != null ? eagerB.booleanValue() : false);
            Integer startLevel = (Integer)props.get("startlevel"); // NOI18N
            ModuleHistory hist = new ModuleHistory(jar, "created from " + xmlfile);
            Module m = createModule(jarFile, hist, reloadable, autoload, eager, startLevel);
            m.addPropertyChangeListener(this);
            // Mark the status as disabled for the moment, so in step 3 it will be turned on
            // if in dirtyprops it was marked enabled.
            Map<String, Object> statusProps;
            if (props.get("enabled") != null && ((Boolean)props.get("enabled")).booleanValue()) { // NOI18N
                statusProps = new HashMap<String, Object>(props);
                statusProps.put("enabled", Boolean.FALSE); // NOI18N
            } else {
                statusProps = props;
            }
            DiskStatus status = new DiskStatus();
            status.module = m;
            status.file = xmlfile;
            status.setDiskProps(statusProps);
            statuses.put(cnb, status);
        }
    }
}