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:mv.Main.java

/**
 * Opens the ASM source code file and checks for any errors on it.
 * Returns false if the user did not specify a file path, if it doesn't exist or if it's empty
 *
 * @param asmFileString ASM source code filename
        /*from   www . j  a  v a2 s .  c o m*/
 * @return the success of the operation
 */
private static boolean setupProgramFile(String asmFileString) {

    boolean success = false;
    Path inFilePath;
    File asmFile;

    if (asmFileString != null) {
        try {
            inFilePath = Paths.get(asmFileString);
            asmFile = new File(inFilePath.toString());
            if (Files.exists(inFilePath)) {
                if (asmFile.length() != 0) {
                    success = true;
                } else {
                    throw new EmptyFileException(asmFile);
                }
            } else {
                throw new FileNotFoundException();
            }
        } catch (FileNotFoundException e) {
            System.err.println(ERR_ASM_NOT_FOUND);
            success = false;

        } catch (EmptyFileException e) {
            System.err.println(e.getMessage());
            success = false;
        }
    }

    return success;
}

From source file:com.shieldsbetter.sbomg.Cli.java

private static ProjectDescriptor parseProjectDescriptor(File f) throws OperationException {
    ProjectDescriptor result;/*from  w  w  w  .  j ava  2  s  . c  o  m*/
    try (InputStream fis = new FileInputStream(f)) {
        result = parseProjectDescriptor(f, fis);
    } catch (FileNotFoundException fnfe) {
        throw new OperationException(f.getPath() + " could not be opened: " + fnfe.getMessage());
    } catch (IOException ioe) {
        throw new OperationException(f.getPath() + " could not be opened: " + ioe.getMessage() + ".");
    }

    return result;
}

From source file:com.cws.esolutions.security.utils.DAOInitializer.java

/**
 * @param properties - The <code>AuthRepo</code> object containing connection information
 * @param isContainer - A <code>boolean</code> flag indicating if this is in a container
 * @param bean - The {@link com.cws.esolutions.security.SecurityServiceBean} <code>SecurityServiceBean</code> that holds the connection
 * @throws SecurityServiceException {@link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs opening the connection
 *//*from   w  w  w.j  a  v a2 s.c om*/
public synchronized static void configureAndCreateAuthConnection(final InputStream properties,
        final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException {
    String methodName = DAOInitializer.CNAME
            + "#configureAndCreateAuthConnection(final String properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("InputStream: {}", properties);
        DEBUGGER.debug("isContainer: {}", isContainer);
        DEBUGGER.debug("SecurityServiceBean: {}", bean);
    }

    try {
        Properties connProps = new Properties();
        connProps.load(properties);

        if (DEBUG) {
            DEBUGGER.debug("Properties: {}", connProps);
        }

        AuthRepositoryType repoType = AuthRepositoryType
                .valueOf(connProps.getProperty(DAOInitializer.REPO_TYPE));
        RepositoryConnectionType connType = RepositoryConnectionType
                .valueOf(connProps.getProperty(DAOInitializer.CONN_TYPE));

        if (DEBUG) {
            DEBUGGER.debug("AuthRepositoryType: {}", repoType);
            DEBUGGER.debug("RepositoryConnectionType: {}", connType);
        }

        switch (repoType) {
        case LDAP:
            SSLUtil sslUtil = null;
            LDAPConnection ldapConn = null;
            LDAPConnectionPool connPool = null;
            LDAPConnectionOptions connOpts = new LDAPConnectionOptions();

            connOpts.setAutoReconnect(true);
            connOpts.setAbandonOnTimeout(true);
            connOpts.setBindWithDNRequiresPassword(true);
            connOpts.setConnectTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.CONN_TIMEOUT)));
            connOpts.setResponseTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.READ_TIMEOUT)));

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionOptions: {}", connOpts);
            }

            switch (connType) {
            case CONNECTION_TYPE_INSECURE:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_SSL:
                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory();

                if (DEBUG) {
                    DEBUGGER.debug("SSLSocketFactory: {}", sslSocketFactory);
                }

                ldapConn = new LDAPConnection(sslSocketFactory, connOpts,
                        connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_TLS:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLContext sslContext = sslUtil.createSSLContext();

                if (DEBUG) {
                    DEBUGGER.debug("SSLContext: {}", sslContext);
                }

                StartTLSExtendedRequest startTLS = new StartTLSExtendedRequest(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSExtendedRequest: {}", startTLS);
                }

                ExtendedResult extendedResult = ldapConn.processExtendedOperation(startTLS);

                if (DEBUG) {
                    DEBUGGER.debug("ExtendedResult: {}", extendedResult);
                }

                BindRequest bindRequest = new SimpleBindRequest(
                        connProps.getProperty(DAOInitializer.REPOSITORY_USER),
                        PasswordUtils.decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                connProps.getProperty(DAOInitializer.TRUST_SALT),
                                secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                if (DEBUG) {
                    DEBUGGER.debug("BindRequest: {}", bindRequest);
                }

                BindResult bindResult = ldapConn.bind(bindRequest);

                if (DEBUG) {
                    DEBUGGER.debug("BindResult: {}", bindResult);
                }

                StartTLSPostConnectProcessor tlsProcessor = new StartTLSPostConnectProcessor(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSPostConnectProcessor: {}", tlsProcessor);
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)), tlsProcessor);

                break;
            }

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionPool: {}", connPool);
            }

            if ((connPool == null) || (connPool.isClosed())) {
                throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
            }

            bean.setAuthDataSource(connPool);
            break;
        case SQL:
            // the isContainer only matters here
            if (isContainer) {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(DAOInitializer.DS_CONTEXT);

                bean.setAuthDataSource(envContext.lookup(DAOInitializer.REPOSITORY_HOST));
            } else {
                BasicDataSource dataSource = new BasicDataSource();
                dataSource.setInitialSize(
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)));
                dataSource
                        .setMaxActive(Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));
                dataSource.setDriverClassName(connProps.getProperty(DAOInitializer.CONN_DRIVER));
                dataSource.setUrl(connProps.getProperty(DAOInitializer.REPOSITORY_HOST));
                dataSource.setUsername(connProps.getProperty(DAOInitializer.REPOSITORY_USER));
                dataSource.setPassword(PasswordUtils.decryptText(
                        connProps.getProperty(DAOInitializer.REPOSITORY_PASS),
                        connProps.getProperty(DAOInitializer.REPOSITORY_SALT), secConfig.getSecretAlgorithm(),
                        secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                        secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                bean.setAuthDataSource(dataSource);
            }

            break;
        case NONE:
            return;
        default:
            throw new SecurityServiceException("Unhandled ResourceType");
        }
    } catch (LDAPException lx) {
        throw new SecurityServiceException(lx.getMessage(), lx);
    } catch (GeneralSecurityException gsx) {
        throw new SecurityServiceException(gsx.getMessage(), gsx);
    } catch (NamingException nx) {
        throw new SecurityServiceException(nx.getMessage(), nx);
    } catch (FileNotFoundException fnfx) {
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new SecurityServiceException(iox.getMessage(), iox);
    }
}

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

/**
 * Store custom sequences in the archive directory
 *
 * @param sequenceDetails   Details of the sequence
 * @param direction      Direction of the sequence "in", "out" or "fault"
 * @param apiIdentifier  ID of the requesting API
 * @throws APIExportException If an error occurs while serializing XML stream or storing in
 *                            archive directory
 *//*  www .  jav  a 2  s. c o  m*/
private static void writeSequenceToFile(AbstractMap.SimpleEntry<String, OMElement> sequenceDetails,
        String direction, APIIdentifier apiIdentifier) throws APIExportException {
    OutputStream outputStream = null;
    String archivePath = archiveBasePath
            .concat(File.separator + apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion())
            + File.separator + "Sequences" + File.separator;

    String pathToExportedSequence = archivePath + direction + "-sequence" + File.separator;
    String sequenceFileName = sequenceDetails.getKey();
    OMElement sequenceConfig = sequenceDetails.getValue();
    String exportedSequenceFile = pathToExportedSequence + sequenceFileName;
    try {
        createDirectory(pathToExportedSequence);
        outputStream = new FileOutputStream(exportedSequenceFile);
        sequenceConfig.serialize(outputStream);

        if (log.isDebugEnabled()) {
            log.debug("Sequence retrieved successfully");
        }

    } catch (FileNotFoundException e) {
        log.error("Unable to find file" + e.getMessage());
        throw new APIExportException("Unable to find file: " + exportedSequenceFile, e);
    } catch (XMLStreamException e) {
        log.error("Error while processing XML stream" + e.getMessage());
        throw new APIExportException("Error while processing XML stream", e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:ispyb.client.common.util.FileUtil.java

/**
 * Gunzip a local file//from w  w  w  . ja v a  2 s  . c  o m
 * 
 * @param sourceFileName
 * @return
 */

public static byte[] readBytes(String sourceFileName) {

    ByteArrayOutputStream outBuffer = null;
    FileInputStream inFile = null;
    BufferedInputStream bufInputStream = null;

    try {
        outBuffer = new ByteArrayOutputStream();
        inFile = new FileInputStream(sourceFileName);
        bufInputStream = new BufferedInputStream(inFile);

        byte[] tmpBuffer = new byte[8 * 1024];
        int n = 0;
        while ((n = bufInputStream.read(tmpBuffer)) >= 0)
            outBuffer.write(tmpBuffer, 0, n);
    } catch (FileNotFoundException fnf) {
        LOG.error("[readBytes] File not found :" + fnf.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inFile != null) {
            try {
                inFile.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
        if (outBuffer != null) {
            try {
                outBuffer.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
        if (bufInputStream != null) {
            try {
                bufInputStream.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
    }
    return outBuffer.toByteArray();
}

From source file:net.pms.external.ExternalFactory.java

/**
 * This method scans the plugins directory for ".jar" files and processes
 * each file that is found. First, a resource named "plugin" is extracted
 * from the jar file. Its contents determine the name of the main plugin
 * class. This main plugin class is then loaded and an instance is created
 * and registered for later use.//from  w ww. j  a  v a2s  .c o m
 */
public static void lookup() {
    // Start by purging files
    purgeFiles();
    File pluginsFolder = new File(configuration.getPluginDirectory());
    LOGGER.info("Searching for plugins in " + pluginsFolder.getAbsolutePath());

    try {
        FilePermissions permissions = new FilePermissions(pluginsFolder);
        if (!permissions.isFolder()) {
            LOGGER.warn("Plugins folder is not a folder: " + pluginsFolder.getAbsolutePath());
            return;
        }
        if (!permissions.isBrowsable()) {
            LOGGER.warn("Plugins folder is not readable: " + pluginsFolder.getAbsolutePath());
            return;
        }
    } catch (FileNotFoundException e) {
        LOGGER.warn("Can't find plugins folder: {}", e.getMessage());
        return;
    }

    // Find all .jar files in the plugin directory
    File[] jarFiles = pluginsFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
        }
    });

    int nJars = (jarFiles == null) ? 0 : jarFiles.length;

    if (nJars == 0) {
        LOGGER.info("No plugins found");
        return;
    }

    // To load a .jar file the filename needs to converted to a file URL
    List<URL> jarURLList = new ArrayList<>();

    for (int i = 0; i < nJars; ++i) {
        try {
            jarURLList.add(jarFiles[i].toURI().toURL());
        } catch (MalformedURLException e) {
            LOGGER.error("Can't convert file path " + jarFiles[i] + " to URL", e);
        }
    }

    URL[] jarURLs = new URL[jarURLList.size()];
    jarURLList.toArray(jarURLs);

    // Load the jars
    loadJARs(jarURLs, false);

    // Instantiate the early external listeners immediately.
    instantiateEarlyListeners();
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static boolean checkFileBackupNFCEncrypted(String fileName) {
    boolean result = false;

    try {//w  ww  .jav  a  2 s  . c o  m
        if (Constants.WALLET_BACKUP_DIRECTORY.exists() && Constants.WALLET_BACKUP_DIRECTORY.isDirectory()) {

            File file = new File(Constants.WALLET_BACKUP_DIRECTORY, fileName);

            FileInputStream fileInputStream = new FileInputStream(file);
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(fileInputStream, Constants.UTF_8));

            while (true) {
                final String line = in.readLine();
                if (line == null)
                    break; // eof

                if (line.startsWith("#ENCTYPE:NFC")) {
                    return true;
                }
            }
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IO Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "some other exception: " + e.getMessage());
    }

    return result;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.epfl.ExportPhdIndividualProgramProcessesInHtml.java

static byte[] createZip(final PhdProgramPublicCandidacyHashCode hashCode) {

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = null;// www . ja v a  2 s. c om
    try {
        zip = new ZipOutputStream(outputStream);

        int count = 1;
        for (final PhdProgramProcessDocument document : hashCode.getIndividualProgramProcess()
                .getCandidacyProcessDocuments()) {
            final ZipEntry zipEntry = new ZipEntry(count + "-" + document.getFilename());
            zip.putNextEntry(zipEntry);

            // TODO: use in local context copy(new ByteArrayInputStream(new
            // byte[20]), zip);
            copy(document.getStream(), zip);

            zip.closeEntry();
            count++;
        }
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (zip != null) {
            try {
                zip.flush();
                zip.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return outputStream.toByteArray();
}

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

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///from   w  ww .  j a  v  a 2  s  . c  o m
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.emm.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 e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, 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.aegiswallet.utils.WalletUtils.java

/**
 * This file will check the password provided when importing a backup file. If the password is correct,
 * it will return true, if not, false.//  w w  w  .ja v a 2 s .co m
 *
 * @param fileName
 * @param password
 * @return
 */
public static boolean checkPasswordForBackupFile(String fileName, String password) {
    boolean result = false;

    try {
        if (Constants.WALLET_BACKUP_DIRECTORY.exists() && Constants.WALLET_BACKUP_DIRECTORY.isDirectory()) {

            File file = new File(Constants.WALLET_BACKUP_DIRECTORY, fileName);

            FileInputStream fileInputStream = new FileInputStream(file);
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(fileInputStream, Constants.UTF_8));

            while (true) {
                final String line = in.readLine();
                if (line == null)
                    break; // eof

                if (line.startsWith("#X2:")) {

                    String[] splitStr = line.split(":");
                    String x2Base64 = splitStr[1];

                    String x2Encrypted = new String(Base64.decode(x2Base64.getBytes(), Base64.NO_WRAP));
                    String x2Decrypted = WalletUtils.decryptString(x2Encrypted, password);
                    x2Decrypted = x2Decrypted.split(":")[1];

                    if (x2Decrypted != null) {
                        return true;
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IO Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "some other exception: " + e.getMessage());
    }

    return result;
}