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:org.openpplsoft.runtime.TraceFileVerifier.java

/**
 * Initializes the verifier with the component runtime
 * profile that will be verified./*from w ww .j  ava2s .co  m*/
 * @param profile the component runtime profile to verify
 */
public static void init(final ComponentRuntimeProfile profile) {
    /*
     * Open trace file for reading.
     */
    try {
        traceFileReader = new BufferedReader(new FileReader(new File("trace/" + profile.getTraceFileName())));
    } catch (final java.io.FileNotFoundException fnfe) {
        throw new OPSVMachRuntimeException(fnfe.getMessage(), fnfe);
    }

    ignoreStmtsInFile("ignoredSql_ORACLE.dat");
}

From source file:org.openpplsoft.runtime.TraceFileVerifier.java

/**
 * Some SQL statements in the PS tracefile are not issued by OPS,
 * either b/c they're unnecessary/redundant or relate to functionality
 * not yet supported. Passing a file containing a list of SQL statements
 * to this method will cause the verifier to ignore them if they are found
 * in the tracefile./*w  w w .  jav  a 2 s  .co  m*/
 * @param filename name of file in classpath containing SQL stmts to ignore.
 */
public static void ignoreStmtsInFile(final String filename) {
    try {
        final Resource ignoredSqlRsrc = new ClassPathResource(filename);
        final BufferedReader ignoreFileReader = new BufferedReader(new FileReader(ignoredSqlRsrc.getFile()));

        String line;
        while ((line = ignoreFileReader.readLine()) != null) {
            ignoredStmts.put(line, true);
        }
        ignoreFileReader.close();
    } catch (final java.io.FileNotFoundException fnfe) {
        throw new OPSVMachRuntimeException(fnfe.getMessage(), fnfe);
    } catch (final java.io.IOException ioe) {
        throw new OPSVMachRuntimeException(ioe.getMessage(), ioe);
    }
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {/* www .  j av a  2s  .  c o m*/
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}

From source file:com.termmed.utils.FileHelper.java

/**
 * Gets the file type by header.//from   w w  w.  ja v  a 2s. c om
 *
 * @param inputFile the input file
 * @param isReduced the is reduced
 * @return the file type by header
 * @throws Exception the exception
 */
public static String getFileTypeByHeader(File inputFile, boolean isReduced) throws Exception {
    String namePattern = null;
    try {
        Thread currThread = Thread.currentThread();
        if (currThread.isInterrupted()) {
            return null;
        }

        String patternFile;
        if (isReduced) {
            patternFile = "validation-rules_reduced.xml";
        } else {
            patternFile = "validation-rules.xml";
        }
        XMLConfiguration xmlConfig = new XMLConfiguration(
                FileHelper.class.getResource("/org/ihtsdo/utils/" + patternFile));
        if (xmlConfig == null) {
            String error = "Pattern file '" + patternFile + "' doesn't exist.";
            log.error(error);
            throw new Exception(error);
        }
        List<String> namePatterns = new ArrayList<String>();

        Object prop = xmlConfig.getProperty("files.file.fileType");
        if (prop instanceof Collection) {
            namePatterns.addAll((Collection) prop);
        }
        //         System.out.println("");
        boolean toCheck = false;
        String headerRule = null;
        FileInputStream fis = new FileInputStream(inputFile);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String header = br.readLine();
        if (header != null) {
            for (int i = 0; i < namePatterns.size(); i++) {
                if (currThread.isInterrupted()) {
                    return null;
                }
                headerRule = xmlConfig.getString("files.file(" + i + ").headerRule.regex");
                namePattern = namePatterns.get(i);
                //            log.info("===================================");
                //            log.info("For file : " + inputFile.getAbsolutePath());
                //            log.info("namePattern:" + namePattern);
                //            log.info("headerRule:" + headerRule);
                if (header.matches(headerRule)) {

                    //               log.info("Match");
                    if ((inputFile.getName().toLowerCase().contains("textdefinition")
                            && namePattern.equals("rf2-descriptions"))
                            || (inputFile.getName().toLowerCase().contains("description")
                                    && namePattern.equals("rf2-textDefinition"))) {
                        continue;
                    }
                    toCheck = true;
                    break;
                }
            }
        }
        if (!toCheck) {
            log.info("Header for null pattern:" + header);
            namePattern = null;
            //System.out.println( "Cannot found header matcher for : " + inputFile.getName());
        }
        br.close();
    } catch (FileNotFoundException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (ConfigurationException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    }
    return namePattern;
}

From source file:jBittorrentAPI.utils.IOManager.java

/**
 * Read all available bytes from the given file
 * @param file File//from w ww .  ja  v  a  2 s .com
 * @return byte[]
 */
public static byte[] readBytesFromFile(File file) {
    long file_size_long = -1;
    byte[] file_bytes = null;
    InputStream file_stream;

    try {
        file_stream = new FileInputStream(file);

        if (!file.exists()) {
            System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName()
                    + "\" does not exist. Please make sure you have the correct path to the file.");
            return null;
        }

        if (!file.canRead()) {
            System.err.println("Error: [TorrentFileHandler.java] Cannot decode from \"" + file.getName()
                    + "\". Please make sure the file permissions are set correctly.");
            return null;
        }

        file_size_long = file.length();

        if (file_size_long > Integer.MAX_VALUE) {
            System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName()
                    + "\" is too large to be decode by this class.");
            return null;
        }
        file_bytes = new byte[(int) file_size_long];
        int file_offset = 0;
        int bytes_read = 0;

        while (file_offset < file_bytes.length && (bytes_read = file_stream.read(file_bytes, file_offset,
                file_bytes.length - file_offset)) >= 0) {
            file_offset += bytes_read;
        }
        if (file_offset < file_bytes.length) {
            throw new IOException("Could not completely decode file \"" + file.getName() + "\".");
        }

        file_stream.close();

    } catch (FileNotFoundException e) {
        System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName()
                + "\" does not exist. Please make sure you have the correct path to the file.");
        return null;
    } catch (IOException e) {
        System.err.println(
                "Error: [TorrentFileHandler.java] There was a general, unrecoverable I/O error while reading from \""
                        + file.getName() + "\".");
        System.err.println(e.getMessage());
    }

    return file_bytes;

}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * Extracts the packageFile and writes its content in temporary directory
 *
 * @param packageFile the packageFile (zip format)
 * @param tempDir the tempDir directory// www . j av  a 2  s .c  o  m
 */
public static void extractPackage(File packageFile, File tempDir) throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("missing package file"));
    }

    ZipFile packageZip = null;
    try {
        packageZip = new ZipFile(packageFile);
        Enumeration<?> entries = packageZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String entryName = entry.getName();
            if (log.isDebugEnabled()) {
                log.debug("ZipEntry name: " + entryName);
            }
            if (entry.isDirectory()) {
                File dir = new File(tempDir, entryName);
                if (dir.mkdirs())
                    log.info("successfully created dir: " + dir.getAbsolutePath());
            } else {
                FileUtil.createFileFromInputStream(getPackageEntryStream(packageFile, entryName),
                        tempDir + File.separator + entryName);
            }
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        try {
            if (packageZip != null)
                packageZip.close();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}

From source file:apim.restful.importexport.utils.APIImportUtil.java

/**
 * This method imports an API/* w ww  .  j  av  a 2 s  .co m*/
 *
 * @param pathToArchive            location of the extracted folder of the API
 * @param currentUser              the current logged in user
 * @param isDefaultProviderAllowed decision to keep or replace the provider
 * @throws APIImportException     if there is an error in importing an API
 */
public static void importAPI(String pathToArchive, String currentUser, boolean isDefaultProviderAllowed)
        throws APIImportException {

    API importedApi;

    // If the original provider is preserved,
    if (isDefaultProviderAllowed) {

        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = new FileInputStream(pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            importedApi = new Gson().fromJson(bufferedReader, API.class);
        } catch (FileNotFoundException e) {
            log.error("Error in locating api.json file. ", e);
            throw new APIImportException("Error in locating api.json file. " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(bufferedReader);
        }
    } else {

        String pathToJSONFile = pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION;

        try {
            String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile));
            JsonElement configElement = new JsonParser().parse(jsonContent);
            JsonObject configObject = configElement.getAsJsonObject();

            //locate the "providerName" within the "id" and set it as the current user
            JsonObject apiId = configObject.getAsJsonObject(APIImportExportConstants.ID_ELEMENT);
            apiId.addProperty(APIImportExportConstants.PROVIDER_ELEMENT,
                    APIUtil.replaceEmailDomain(currentUser));
            importedApi = new Gson().fromJson(configElement, API.class);

        } catch (IOException e) {
            log.error("Error in setting API provider to logged in user. ", e);
            throw new APIImportException("Error in setting API provider to logged in user. " + e.getMessage());
        }
    }

    Set<Tier> allowedTiers;
    Set<Tier> unsupportedTiersList;

    try {
        allowedTiers = provider.getTiers();
    } catch (APIManagementException e) {
        log.error("Error in retrieving tiers of the provider. ", e);
        throw new APIImportException("Error in retrieving tiers of the provider. " + e.getMessage());
    }

    if (!(allowedTiers.isEmpty())) {
        unsupportedTiersList = Sets.difference(importedApi.getAvailableTiers(), allowedTiers);

        //If at least one unsupported tier is found, it should be removed before adding API
        if (!(unsupportedTiersList.isEmpty())) {
            for (Tier unsupportedTier : unsupportedTiersList) {

                //Process is continued with a warning and only supported tiers are added to the importer API
                log.warn("Tier name : " + unsupportedTier.getName() + " is not supported.");
            }

            //Remove the unsupported tiers before adding the API
            importedApi.removeAvailableTiers(unsupportedTiersList);
        }
    }

    try {
        int tenantId = APIUtil.getTenantId(currentUser);
        provider.addAPI(importedApi);
        addSwaggerDefinition(importedApi, pathToArchive, tenantId);
    } catch (APIManagementException e) {
        //Error is logged and APIImportException is thrown because adding API and swagger are mandatory steps
        log.error("Error in adding API to the provider. ", e);
        throw new APIImportException("Error in adding API to the provider. " + e.getMessage());
    }
    //Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation
    addAPIImage(pathToArchive, importedApi);
    addAPIDocuments(pathToArchive, importedApi);
    addAPISequences(pathToArchive, importedApi, currentUser);
    addAPIWsdl(pathToArchive, importedApi, currentUser);

}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///w w w . j  a  v  a2  s  .  c om
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }
    }
}

From source file:com.stimulus.archiva.service.MessageService.java

public static void storeMessage(Principal principal, InputStream in) throws ArchiveException {
    if (in == null)
        throw new ArchiveException("assertion failure: null message,username or remoteIP", logger,
                ArchiveException.RecoveryDirective.RETRYLATER);

    logger.debug("message received for archival {" + principal + "'}");

    boolean processMalformed = Config.getConfig().getArchiver().getProcessMalformedMessages();
    File tempFile = null;/*  ww w  .  j  ava  2s.  c om*/
    InputStream inStream = null;
    Email message = null;
    Config config = Config.getConfig();

    try {
        if (processMalformed) {
            try {
                tempFile = copyToTemp(in);
            } catch (Exception io) {
                throw new ArchiveException("failed to copy message to temp directory:" + io.getMessage(), io,
                        logger, ArchiveException.RecoveryDirective.RETRYLATER);
            }
            try {
                inStream = new BufferedInputStream(new FileInputStream(tempFile));
            } catch (FileNotFoundException fnfe) {
                throw new ArchiveException("failed to copy message to temp directory:" + fnfe.getMessage(),
                        fnfe, logger, ArchiveException.RecoveryDirective.RETRYLATER);
            }
            try {
                message = new Email(null, inStream);
            } catch (Exception e) {
                InputStream errorStream = null;
                try {
                    errorStream = new BufferedInputStream(new FileInputStream(tempFile));
                } catch (FileNotFoundException fnfe) {
                    throw new ArchiveException("failed to copy message to temp directory:" + fnfe.getMessage(),
                            fnfe, logger, ArchiveException.RecoveryDirective.RETRYLATER);
                }
                backupMessage(errorStream);
                throw new ArchiveException("archive message appears corrupted:" + e.getMessage(), e, logger,
                        ArchiveException.RecoveryDirective.ACCEPT);
            }
        } else {
            inStream = new BufferedInputStream(in);
            try {
                message = new Email(null, inStream);
            } catch (Exception e) {
                throw new ArchiveException("archive message is corrupted:" + e.getMessage() + ".", e, logger,
                        ArchiveException.RecoveryDirective.ACCEPT);
            }
        }

        if (!config.getArchiver().isDefaultPassPhraseModified()) {
            backupMessage(message);
            logger.error("failed to archive message. encryption password is not set.");
        }
        if (config.getArchiveFilter().shouldArchive(message,
                Config.getConfig().getDomains()) == ArchiveFilter.Action.ARCHIVE) {
            try {
                assignEmailID(message, Config.getConfig().getVolumes());
                if (message.getEmailID().getVolume().isEjected()) {
                    logger.debug(
                            "attempt to archive message to ejected volume. sending message to no archive queue.");
                    backupMessage(message);
                }
                archive(principal, message, false);
            } catch (Exception e) {
                logger.error(
                        "error occurred while archiving message. message will be reprocessed on server restart",
                        e);
                backupMessage(message);
            }

        } else {
            audit.info("skip email {" + message + ", " + principal + "}");
            logger.debug("skip email {" + message + ", " + principal + "}");
        }
    } finally {
        deleteTemp(tempFile);
        StreamUtil.emptyStream(in);
    }
}

From source file:com.continuent.tungsten.common.security.SecurityHelper.java

/**
 * Loads Security related properties from a file. File location =
 * {clusterhome}/conf/security.properties
 * //from w w w  .j av a 2s.  c o  m
 * @param propertiesFileLocation location of the security.properties file.
 *            If set to null will look for the default file.
 * @return TungstenProperties containing security parameters
 * @throws ConfigurationException
 */
private static TungstenProperties loadSecurityPropertiesFromFile(String propertiesFileLocation)
        throws ConfigurationException {
    TungstenProperties securityProps = null;
    FileInputStream securityConfigurationFileInputStream = null;

    // --- Get Configuration file ---
    if (propertiesFileLocation == null && ClusterConfiguration.getClusterHome() == null) {
        throw new ConfigurationException("No cluster.home found from which to configure cluster resources.");
    }

    File securityPropertiesFile;
    if (propertiesFileLocation == null) // Get from default location
    {
        File clusterConfDirectory = ClusterConfiguration
                .getDir(ClusterConfiguration.getGlobalConfigDirName(ClusterConfiguration.getClusterHome()));
        securityPropertiesFile = new File(clusterConfDirectory.getPath(),
                SecurityConf.SECURITY_PROPERTIES_FILE_NAME);
    } else
    // Get from supplied location
    {
        securityPropertiesFile = new File(propertiesFileLocation);
    }

    // --- Get properties ---
    try {
        securityProps = new TungstenProperties();
        securityConfigurationFileInputStream = new FileInputStream(securityPropertiesFile);
        securityProps.load(securityConfigurationFileInputStream, true);
        closeSecurityConfigurationFileInputStream(securityConfigurationFileInputStream);
    } catch (FileNotFoundException e) {
        String msg = MessageFormat.format("Cannot find configuration file: {0}",
                securityPropertiesFile.getPath());
        logger.debug(msg, e);
        throw new ConfigurationException(msg);
    } catch (IOException e) {
        String msg = MessageFormat.format("Cannot load configuration file: {0}.\n Reason: {1}",
                securityPropertiesFile.getPath(), e.getMessage());
        logger.debug(msg, e);
        throw new ConfigurationException(msg);
    } finally {
        closeSecurityConfigurationFileInputStream(securityConfigurationFileInputStream);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format(": {0}", securityPropertiesFile.getPath()));
    }

    // Update propertiesFileLocation with the location actualy used
    securityProps.put(SecurityConf.SECURITY_PROPERTIES_PARENT_FILE_LOCATION,
            securityPropertiesFile.getAbsolutePath());

    return securityProps;
}