Example usage for java.io FileNotFoundException getMessage

List of usage examples for java.io FileNotFoundException getMessage

Introduction

In this page you can find the example usage for java.io FileNotFoundException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:au.edu.unsw.cse.soc.federatedcloud.curator.CuratorAPI.java

private List<CloudResourceDescription> queryKnowledgeBase(String query) {
    File folder = new File(KB_LOCATION);
    File[] jsonFiles = folder.listFiles(new FileFilter() {
        @Override/*from ww  w . ja  va  2s. co  m*/
        public boolean accept(File pathname) {
            System.out.println(pathname.getName());
            return pathname.getName().endsWith(".json");
        }
    });

    List<CloudResourceDescription> descs = new ArrayList<CloudResourceDescription>();
    if (jsonFiles == null) {
        try {
            throw new FileNotFoundException("No Resource descriptions found at:" + KB_LOCATION);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            return descs; //Returns a zero length List
        }
    } else {
        for (File file : jsonFiles) {
            if (file.isDirectory()) {
                continue;
            }
            try {
                CloudResourceDescription desc = DataModelUtil.buildCouldResourceDescriptionFromJSON(file);
                descs.add(desc);
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
        System.out.println("Size of Descriptions:" + descs.size());
        return descs;
    }

}

From source file:edu.du.penrose.systems.fedoraApp.util.MetsBatchFileSplitter.java

/**
 * Split the batchIngest command file. If the batch contains additions put the results into the 'mets/new' directory. If updates put the
 * files into the 'mets/upates' directory. The ingest command (only one per batchfile!!) is saved in a comment prior to the <mets:mets>
 * element for each split file. This means the batch can only contain files of one type ie adds or updates.
 * <br><br>// w  ww.j a v  a  2 s . c o m
 * If an error occurs we will try to remove any generated output file and then throw an exception.
 * <br>
 * One the ingest command line is found ie "<ingestControl command="A" type="pidInOBJID" />" ALL other command line are ignored!! AFter that
 * point we only look for <mets:mets> and </mets:mets> to split the file.
 * 
 * NOTE Since this method may need to get fedora pids The following libraries are needed...
 * wsdl4j-1.5.1.jar
 * commons-discovery.jar
 * fcrepo-server-3.4-utilities-main.jar
 * jaxrpc.jar
 * logback-core-0.9.18.jar
 * logback-classic-0.9.18.jar
 * trippi-1.1.2-core.jar
 * fcrepo-common-3.4.jar
 * fcrepo-client-admin-3.4.jar
 * jdom.jar
 * 
 * @param ingestOptions set batchIngestDate, batchDescription, 
 * @param threadStatus can be null.
 * @param inFile batch file to split
 * @param metsNewDirectory
 * @param metsUpdatesDirectory
 * @param nameFileFromOBJID create xml file's that are named the same as it's OBJID element. This seems like a good idea but if the file
 * already exists you will get a error, killing the entire ingest.
 * @param fedoraUser used for a replyWithPid ingest.     If null we will pull from the batchIngest.properties file.
 * @param fedoraPassword used for a replyWithPid ingest. If null we will pull from the batchIngest.properties file.
 * 
 * @return IF the batch file is an add of type 'replyWithPid' return a map of OBJID and PIDs otherwise return null. NOTE: if the <mets:mets OBJID> element is
 * empty in the batch file, both the key and the value of the returned map will contain the pid.
 * 
 * @throws Exception
 */
static public Map<String, String> splitMetsBatchFile_version_2(BatchIngestOptions ingestOptions,
        ThreadStatusMsg threadStatus, File inFile, String metsNewDirectory, String metsUpdatesDirectory,
        boolean nameFileFromOBJID, String fedoraHost, String fedoraPort, String fedoraUser,
        String fedoraPassword) throws Exception {
    Map<String, String> pidMap = null;

    FileInputStream batchFileInputStream;
    try {
        batchFileInputStream = new FileInputStream(inFile);
    } catch (FileNotFoundException e) {
        throw new FatalException(e.getMessage());
    }

    DataInputStream batchFileDataInputStream = new DataInputStream(batchFileInputStream);
    BufferedReader batchFileBufferedReader = new BufferedReader(
            new InputStreamReader(batchFileDataInputStream));
    String oneLine = null;
    String ingestControlLine = null;
    int fileCount = 0;
    String documentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    String batchCreationDate = null;
    String batchDescription = null;
    String metsDirectory = null; // will get set to either the new directory or the updates directory.
    File outFile = null;
    FileOutputStream metsFileOutputStream = null;
    BufferedWriter metsBufferedWriter = null;

    boolean headerFoundLookOnlyForMetsNow = false;

    while (batchFileBufferedReader.ready()) {
        oneLine = batchFileBufferedReader.readLine();
        if (!headerFoundLookOnlyForMetsNow) {
            if (oneLine.contains("<?xml version") && oneLine.trim().startsWith("<")) {
                documentType = oneLine;
            }

            // LOOK FOR BATCH DESCRIPTION
            if (oneLine.contains(BATCH_DESCRIPTION_ELEMENT_MARKER) && oneLine.indexOf("<!") == -1) {
                int tempLocation1 = oneLine.indexOf("batchCreationDate=" + QUOTE);
                if (tempLocation1 == -1) {
                    oneLine.indexOf("batchCreationDate=" + APOST);
                }

                int tempLocation2 = oneLine.indexOf(QUOTE, tempLocation1 + 19);
                if (tempLocation2 == -1) {
                    oneLine.indexOf(APOST, tempLocation1 + 19);
                }

                batchCreationDate = oneLine.substring(tempLocation1 + 19, tempLocation2);
                ingestOptions.setBatchIngestDate(batchCreationDate);

                oneLine = batchFileBufferedReader.readLine();
                if (!oneLine.contains("<literal>")) {
                    throw new FatalException("Invalid batchDescription");
                }
                StringBuffer tempBatchDescription = new StringBuffer();
                boolean endBatchDescription = false;
                do {
                    tempBatchDescription.append(oneLine);
                    if (oneLine.contains("</literal>")) {
                        endBatchDescription = true;
                        batchDescription = tempBatchDescription.toString();
                        batchDescription = batchDescription.replace("<literal>", ""); // it may all be on one line.
                        batchDescription = batchDescription.replace("</literal>", "");
                    }
                    oneLine = batchFileBufferedReader.readLine();
                } while (!endBatchDescription);
                ingestOptions.setBatchDescription(batchDescription.trim());
            }

            // look for batch command at the top of the file, prior to the first <mets:mets>
            if (oneLine.contains((INGEST_CONTROL_ELEMENT_MARKER)) && oneLine.indexOf("<!") == -1) {
                if ((!oneLine.contains("command")) || (!oneLine.contains("type"))) {
                    throw new FatalException(
                            "The batch control element must have both command and type attributes");
                }

                ingestControlLine = oneLine.trim();
                boolean validCommandLine = parseCommandLine(ingestOptions, ingestControlLine);
                if (!validCommandLine) {
                    throw new Exception("ERROR: Invalid command line found in batch ingest file:" + inFile
                            + " ,  " + ingestControlLine);
                }

                headerFoundLookOnlyForMetsNow = true;
                switch (ingestOptions.getIngestCommand()) {
                case UPDATE:
                    metsDirectory = metsUpdatesDirectory;
                    break;
                case ADD:
                    metsDirectory = metsNewDirectory;
                    break;
                default:
                    throw new Exception("ERROR: Invalid ingest command");
                }

            } // if line is ingestControl (command line)
        } else // if-else headerFoundLookOnlyForMetsNow
        {
            if (oneLine.contains((INGEST_CONTROL_ELEMENT_MARKER)) && oneLine.indexOf("<!") == -1) {
                logger.warn("More than one ingest control line found in batch file! extras will be ignored:"
                        + inFile);
            }

            // look for <mets:mets> and get complete <mets:mets> element
            if (oneLine.contains("<mets:mets") && oneLine.indexOf("<!") == -1) {
                boolean haveEntireMetsLine = false;
                while (!haveEntireMetsLine) {
                    StringBuffer tempBuffer = new StringBuffer(oneLine);
                    String moreOfMetsLine = null;
                    if (!oneLine.contains(">")) {
                        moreOfMetsLine = batchFileBufferedReader.readLine();
                        tempBuffer.append(moreOfMetsLine);

                        if (moreOfMetsLine.contains(">")) {
                            haveEntireMetsLine = true;
                            oneLine = tempBuffer.toString();
                        } else {
                            oneLine = tempBuffer.toString();
                        }
                    } else {
                        haveEntireMetsLine = true;
                    }
                }

                // process everything up to </mets:mets>
                String objID = MetsBatchFileSplitter.getObjID(oneLine);
                if (nameFileFromOBJID) {
                    outFile = new File(metsDirectory + objID + ".xml");
                    logger.info("outputSplitFile METS file: " + metsDirectory + objID + ".xml");
                    if (outFile.exists()) {
                        String errorMsg = "file already exists:" + outFile.getName();
                        System.out.println(errorMsg);
                        logger.error(errorMsg);
                        throw new FatalException(errorMsg);
                    }
                } else {
                    switch (ingestOptions.getIngestThreadType()) {
                    case BACKGROUND:
                        // TBD this is probably an error
                    case MANUAL:
                        outFile = new File(metsDirectory
                                + edu.du.penrose.systems.util.FileUtil.getDateTimeMilliSecondEnsureUnique()
                                + ".xml");
                        break;
                    case REMOTE:
                        outFile = new File(metsDirectory
                                + edu.du.penrose.systems.util.FileUtil.getDateTimeMilliSecondEnsureUnique()
                                + FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX + ".xml");
                        break;
                    }
                }

                // oneLine now contains the entire <mets:mets....> line
                logger.info("outputSplitFile METS file: " + outFile.toString() + "\n\n");

                boolean errorOccurred = false;
                try {
                    metsFileOutputStream = new FileOutputStream(outFile);
                    metsBufferedWriter = new BufferedWriter(
                            new OutputStreamWriter(metsFileOutputStream, "UTF-8"));
                    metsBufferedWriter.write(documentType);
                    metsBufferedWriter.newLine();

                    switch (ingestOptions.getIngestCommand()) {
                    case ADD:
                        switch (ingestOptions.getAddCommandType()) {
                        case REPLY_WITH_PID:
                            // we get one pid at a time, write it to the <mets:mets> line OBJID value and add it to the pidMap
                            String[] tempPids = null;
                            if (fedoraPassword == null || fedoraUser == null || fedoraHost == null
                                    || fedoraPort == null) {
                                tempPids = FedoraAppUtil.getPIDs(ingestOptions.getInstitution(),
                                        new NonNegativeInteger("1"));
                            } else {
                                tempPids = FedoraAppUtil.getPIDs(fedoraHost, Integer.valueOf(fedoraPort),
                                        fedoraUser, fedoraPassword, ingestOptions.getInstitution(),
                                        new NonNegativeInteger("1"));
                            }

                            String reservedPid = tempPids[0];
                            metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n");
                            if (pidMap == null) {
                                pidMap = new LinkedHashMap<String, String>();
                            }
                            oneLine = putPidInMetsLineOBJID(oneLine, reservedPid);

                            if (objID.contentEquals("")) {
                                pidMap.put(reservedPid, reservedPid);
                            } else {
                                pidMap.put(objID, reservedPid);
                            }

                            break;
                        case PID_IN_OBJID:
                        case NORMAL:
                        default:
                            metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n");
                        }
                        break;
                    case UPDATE:
                        metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n");
                        break;
                    case NOT_SET:
                    default:
                        throw new Exception("ERROR: Invalid ingest command");
                    }

                    // read lines from batch file and write to the new mets file until </mets:mets> line

                    while (!oneLine.contains("</mets:mets")) { // null pointer on premature end of file.
                        metsBufferedWriter.write(oneLine);
                        metsBufferedWriter.newLine();
                        oneLine = batchFileBufferedReader.readLine();
                        if (oneLine == null) {
                            throw new FatalException("Error spliting batch file, missing </mets:mets>");
                        }
                    }
                    metsBufferedWriter.write(oneLine);
                    metsBufferedWriter.newLine();
                    metsBufferedWriter.close();
                } catch (Exception e) {
                    errorOccurred = true; // for cleanup, see below.
                    throw new Exception(e);
                } finally {
                    metsBufferedWriter.close();
                    if (errorOccurred) {
                        outFile.delete(); //clean up.
                    }
                }

                fileCount++;
                if (threadStatus != null) {
                    threadStatus.setStatus("Spliting XML file #: " + fileCount);
                }

            } // if <mets:mets> found (look for another mets section now).

        } // if-else ! headerFoundLookOnlyForMetsNow

    } // while

    return pidMap; // may be null

}

From source file:fr.paris.lutece.plugins.updater.service.catalog.CatalogService.java

/**
 * Retrieve all plugin releases from a repository
 * @return A CatalogInfos list/*from w  w w.  ja  va2s. c  o m*/
 */
public List<CatalogInfos> getCatalogInfos() {
    // clear catalogs data
    _listCatalogs.clear();
    _listInfos.clear();

    try {
        // load catalogs list
        File fileCatalogs = new File(AppPathService.getWebAppPath() + FILE_CATALOGS_LIST);
        FileReader readerFile = new FileReader(fileCatalogs);
        loadCatalogsList(readerFile);

        HttpAccess httpAccess = new HttpAccess();

        for (Catalog catalog : _listCatalogs) {
            String strXmlCatalog = httpAccess.doGet(catalog.getUrl());

            Reader reader = new StringReader(strXmlCatalog);
            load(reader);
        }
    } catch (FileNotFoundException e) {
        AppLogService.error(EXCEPTION_MESSAGE + e.getMessage(), e);
    } catch (HttpAccessException e) {
        AppLogService.error(EXCEPTION_MESSAGE + e.getMessage(), e.getCause());
    }

    return _listInfos;
}

From source file:eu.arthepsy.sonar.plugins.scapegoat.rule.ScapegoatReportSensor.java

private void parseReport(SensorContext context, File report) {
    FileInputStream stream = null;
    try {/*from w  ww .j  a  v  a 2 s .  com*/
        stream = new FileInputStream(report);
        this.parseReport(context, stream);
    } catch (FileNotFoundException e) {
        LOG.error(LOG_PREFIX + " file not found error: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */// w  ww .  j av  a2s  .c  o m
public void contextDestroyed(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextDestroyed(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    SecurityConfigurationData config = SecurityServiceListener.svcBean.getConfigData();

    if (DEBUG) {
        DEBUGGER.debug("SecurityConfigurationData: {}", config);
    }

    try {
        DAOInitializer.closeAuthConnection(
                new FileInputStream(FileUtils.getFile(config.getSecurityConfig().getAuthConfig())), false,
                svcBean);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:com.redhat.tools.nexus.audit.serial.store.JsonAuditStore.java

private AuditInfo getAuditInformation(final File auditFile) throws AuditStoreException {
    if (auditFile.exists() && auditFile.isFile() && auditFile.canRead()) {
        FileReader reader = null;
        try {/* w  w w.j  a  va2 s.c  o  m*/
            reader = new FileReader(auditFile);
            return getGson().fromJson(reader, AuditInfo.class);
        } catch (final FileNotFoundException e) {
            throw new AuditStoreException("Cannot open audit file: %s\nReason: %s", e, auditFile,
                    e.getMessage());
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }

    return null;
}

From source file:com.snaplogic.snaps.uniteller.CustomUFSSecurityMgr.java

@Override
public void changePassword(String machineId, String password) throws UFSSecurityMgrException {
    OutputStream securityOutputStream = null;
    try {/*from  w  ww  .  j  av a2s  .  c  om*/
        urlConnection = new URL(this.fileLocation).openConnection();
        urlConnection.connect();
        securityOutputStream = urlConnection.getOutputStream();
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
        throw new UFSSecurityMgrException(e.getMessage());
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new UFSSecurityMgrException(ex.getMessage());
    }
    synchronized (this.securityProps) {
        this.securityProps.put(machineId, password);
        try {
            this.securityProps.store(securityOutputStream, null);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new UFSSecurityMgrException(e.getMessage());
        } finally {
            cleanup(securityOutputStream, urlConnection);
        }
    }
}

From source file:com.autentia.tnt.listener.StartupListener.java

public void contextInitialized(ServletContextEvent sce) {
    try {//from   www .j av a  2  s.c o m
        // Dump traces now as if nothing had happended before
        log.info("--------------------------------------------------------------------------------");
        log.info("contextInitialized - starting up application");
        log.info("contextInitialized - saving Spring's context for use by all application");

        // Save Spring context
        SpringUtils.configure(WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()));

        // Get configuration directory
        String cfgDir = ConfigurationUtil.getDefault().getConfigDir();
        log.info("contextInitialized - configuration directory set to '" + cfgDir + "'");

        // Normalized cfgDir
        if (cfgDir.endsWith("/") || cfgDir.endsWith("\\")) {
            cfgDir = cfgDir.substring(0, cfgDir.length() - 1);
        }

        // Check configuration directory
        if (!new File(cfgDir).isDirectory()) {
            throw new FileNotFoundException(cfgDir);
        }

        // Configure LOG4J
        String log4jProperties = cfgDir + FILE_LOG4J;
        if (!new File(log4jProperties).exists()) {
            throw new FileNotFoundException(log4jProperties);
        }
        PropertyConfigurator.configure(log4jProperties);
        log.info("contextInitialized - configuring LOG4J system with file " + log4jProperties);

        // Try to create essential directories
        File uploadPath = new File(ConfigurationUtil.getDefault().getUploadPath());
        log.info("contextInitialized - checking upload directory " + uploadPath.getAbsolutePath());
        uploadPath.mkdirs();
        if (!uploadPath.isDirectory()) {
            throw new FileNotFoundException(uploadPath.getAbsolutePath());
        }

        // Load reports
        if (ConfigurationUtil.getDefault().getLoadingReportOnLoad() > 0) {
            log.info("contextInitialized - loading reports in report manager");
            ReportManager.getReportManager();
        } else {
            log.info("contextInitialized - loading reports on startup disabled");
        }

        // Check database
        log.info("contextInitialized - checking database version");
        ApplicationLock.refresh();
    } catch (FileNotFoundException e) {
        log.fatal("contextInitialized - configuration dir or file not found (" + e.getMessage()
                + "): application will not be started", e);
        throw new IllegalStateException("Config dir or file not found", e);
    }
    /* Moved to Spring 
    catch( ConfigurationException e )
    {
      log.fatal("contextInitialized - error reading application configuration: application will not be started",e);
      throw new IllegalStateException("Error reading applocation configuration",e);
    }
    */
}

From source file:net.itransformers.connectiondetails.csvconnectiondetails.CsvConnectionDetailsFileManager.java

private void save() {
    PrintWriter writer = null;//from  w w  w . j a v a 2 s .  c om
    try {
        writer = new PrintWriter(file);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    for (String name : connectionDetailsMap.keySet()) {
        ConnectionDetails connectionDetails = connectionDetailsMap.get(name);
        StringBuilder sb = new StringBuilder();
        sb.append("name=").append(name).append(",");
        sb.append("type=").append(connectionDetails.getConnectionType()).append(":");
        for (String paramKey : connectionDetails.getParams().keySet()) {
            sb.append(paramKey).append("=").append(connectionDetails.getParam(paramKey)).append(",");
        }
        writer.println(sb);
    }
    writer.flush();
    writer.close();
}

From source file:com.disusered.Safe.java

private void initCrypto(String path, String password, CallbackContext callbackContext) {
    if (path != null && path.length() > 0 && password != null && password.length() > 0) {
        SOURCE_URI = Uri.parse(path);
        FILE_NAME = SOURCE_URI.getLastPathSegment();

        CONTEXT = cordova.getActivity().getApplicationContext();
        ENTITY = new Entity(password);

        SOURCE_FILE = new File(SOURCE_URI.getPath());

        // initialize crypto object
        CRYPTO = new Crypto(new SharedPrefsBackedKeyChain(CONTEXT), new SystemNativeCryptoLibrary());

        // check for whether crypto is available
        if (!CRYPTO.isAvailable()) {
            callbackContext.error(1);//from   w w  w  .  j  ava  2 s.co m
            return;
        }

        try {
            // initialize temp file
            TEMP_FILE = File.createTempFile(FILE_NAME, null, CONTEXT.getExternalCacheDir());
            // initialize output stream for temp file
            OUTPUT_STREAM = new BufferedOutputStream(new FileOutputStream(TEMP_FILE));
            // create input stream from source file
            INPUT_STREAM = new FileInputStream(SOURCE_FILE);
        } catch (FileNotFoundException e) {
            callbackContext.error(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            callbackContext.error(e.getMessage());
            e.printStackTrace();
        }
    } else {
        callbackContext.error(2);
    }
}