Example usage for java.io FileNotFoundException getLocalizedMessage

List of usage examples for java.io FileNotFoundException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Read the contents of a file.//from w w  w  .  j  av a2 s. c  o m
 * This is done in a background thread; the result is sent to the callback.
 *
 * @param filename          The name of the file.
 * @param start             Start position in the file.
 * @param end               End position to stop at (exclusive).
 * @param callbackContext   The context through which to send the result.
 * @param encoding          The encoding to return contents as.  Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
 * @param resultType        The desired type of data to send to the callback.
 * @return                  Contents of file.
 */
public void readFileAs(final String filename, final int start, final int end,
        final CallbackContext callbackContext, final String encoding, final int resultType) {
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                byte[] bytes = readAsBinaryHelper(filename, start, end);

                PluginResult result;
                switch (resultType) {
                case PluginResult.MESSAGE_TYPE_STRING:
                    result = new PluginResult(PluginResult.Status.OK, new String(bytes, encoding));
                    break;
                case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
                    result = new PluginResult(PluginResult.Status.OK, bytes);
                    break;
                case PluginResult.MESSAGE_TYPE_BINARYSTRING:
                    result = new PluginResult(PluginResult.Status.OK, bytes, true);
                    break;
                default: // Base64.
                    String contentType = FileHelper.getMimeType(filename, cordova);
                    byte[] base64 = Base64.encode(bytes, Base64.DEFAULT);
                    String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
                    result = new PluginResult(PluginResult.Status.OK, s);
                }

                callbackContext.sendPluginResult(result);
            } catch (FileNotFoundException e) {
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
            } catch (IOException e) {
                Log.d(LOG_TAG, e.getLocalizedMessage());
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
            }
        }
    });
}

From source file:org.apache.cordova.FileUtils.java

/**
 * Read the contents of a file.//from   w  w w  .j a va2  s .c  o m
 * This is done in a background thread; the result is sent to the callback.
 *
 * @param filename          The name of the file.
 * @param start             Start position in the file.
 * @param end               End position to stop at (exclusive).
 * @param callbackContext   The context through which to send the result.
 * @param encoding          The encoding to return contents as.  Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
 * @param resultType        The desired type of data to send to the callback.
 * @return                  Contents of file.
 */
public void readFileAs(final String filename, final int start, final int end,
        final CallbackContext callbackContext, final String encoding, final int resultType) {
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                byte[] bytes = readAsBinaryHelper(filename, start, end);

                PluginResult result;
                switch (resultType) {
                case PluginResult.MESSAGE_TYPE_STRING:
                    result = new PluginResult(PluginResult.Status.OK, new String(bytes, encoding));
                    break;
                case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
                    result = new PluginResult(PluginResult.Status.OK, bytes);
                    break;
                case PluginResult.MESSAGE_TYPE_BINARYSTRING:
                    result = new PluginResult(PluginResult.Status.OK, bytes, true);
                    break;
                default: // Base64.
                    String contentType = FileHelper.getMimeType(filename, cordova);
                    byte[] base64 = Base64.encode(bytes, Base64.NO_WRAP);
                    String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
                    result = new PluginResult(PluginResult.Status.OK, s);
                }

                callbackContext.sendPluginResult(result);
            } catch (FileNotFoundException e) {
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
            } catch (IOException e) {
                Log.d(LOG_TAG, e.getLocalizedMessage());
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
            }
        }
    });
}

From source file:dev.ukanth.ufirewall.Api.java

public static boolean saveSharedPreferencesToFile(Context ctx) {
    boolean res = false;
    File sdCard = Environment.getExternalStorageDirectory();
    if (isExternalStorageWritable()) {
        File dir = new File(sdCard.getAbsolutePath() + "/afwall/");
        dir.mkdirs();//  www .  ja v  a 2  s .  c o m
        File file = new File(dir, "backup.json");
        try {
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

            //default Profile - current one
            JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx));
            JSONArray jArray = new JSONArray("[" + obj.toString() + "]");

            myOutWriter.append(jArray.toString());
            res = true;
            myOutWriter.close();
            fOut.close();
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (JSONException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
    }

    return res;
}

From source file:dev.ukanth.ufirewall.Api.java

public static boolean saveAllPreferencesToFile(Context ctx) {
    boolean res = false;
    File sdCard = Environment.getExternalStorageDirectory();
    if (isExternalStorageWritable()) {
        File dir = new File(sdCard.getAbsolutePath() + "/afwall/");
        dir.mkdirs();/*from   w  ww.  j  ava  2  s  .  c o m*/
        File file = new File(dir, "backup_all.json");

        try {
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

            JSONObject exportObject = new JSONObject();
            //if multiprofile is enabled
            if (G.enableMultiProfile()) {
                JSONObject profileObject = new JSONObject();
                //store all the profile settings
                for (String profile : G.profiles) {
                    Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>();
                    final SharedPreferences prefs = ctx.getSharedPreferences(profile, Context.MODE_PRIVATE);
                    updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT);
                    profileObject.put(profile, new JSONObject(exportMap));
                }
                exportObject.put("profiles", profileObject);

                //if any additional profiles
                int defaultProfileCount = 3;
                JSONObject addProfileObject = new JSONObject();
                for (String profile : G.getAdditionalProfiles()) {
                    defaultProfileCount++;
                    Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>();
                    final SharedPreferences prefs = ctx
                            .getSharedPreferences("AFWallProfile" + defaultProfileCount, Context.MODE_PRIVATE);
                    updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT);
                    addProfileObject.put(profile, new JSONObject(exportMap));
                }
                exportObject.put("additional_profiles", addProfileObject);
            } else {
                //default Profile - current one
                JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx));
                exportObject.put("default", obj);
            }

            //now gets all the preferences
            exportObject.put("prefs", getAllAppPreferences(ctx, G.gPrefs));

            myOutWriter.append(exportObject.toString());
            res = true;
            myOutWriter.close();
            fOut.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        } catch (JSONException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
    }

    return res;
}

From source file:dev.ukanth.ufirewall.Api.java

@Deprecated
private static boolean importRulesOld(Context ctx, File file) {
    boolean res = false;
    ObjectInputStream input = null;
    try {/*  w  ww . j  a va  2  s  .co  m*/
        input = new ObjectInputStream(new FileInputStream(file));
        Editor prefEdit = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit();
        prefEdit.clear();
        Map<String, ?> entries = (Map<String, ?>) input.readObject();
        for (Entry<String, ?> entry : entries.entrySet()) {
            Object v = entry.getValue();
            String key = entry.getKey();
            if (v instanceof Boolean)
                prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
            else if (v instanceof Float)
                prefEdit.putFloat(key, ((Float) v).floatValue());
            else if (v instanceof Integer)
                prefEdit.putInt(key, ((Integer) v).intValue());
            else if (v instanceof Long)
                prefEdit.putLong(key, ((Long) v).longValue());
            else if (v instanceof String)
                prefEdit.putString(key, ((String) v));
        }
        prefEdit.commit();
        res = true;
    } catch (FileNotFoundException e) {
        // alert(ctx, "Missing back.rules file");
        Log.e(TAG, e.getLocalizedMessage());
    } catch (IOException e) {
        // alert(ctx, "Error reading the backup file");
        Log.e(TAG, e.getLocalizedMessage());
    } catch (ClassNotFoundException e) {
        Log.e(TAG, e.getLocalizedMessage());
    } finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ex) {
            Log.e(TAG, ex.getLocalizedMessage());
        }
    }
    return res;
}

From source file:dev.ukanth.ufirewall.Api.java

private static boolean importRules(Context ctx, File file, StringBuilder msg) {
    boolean returnVal = false;
    BufferedReader br = null;/*from   w  w w.ja v a 2  s  .  c  om*/
    try {
        StringBuilder text = new StringBuilder();
        br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            text.append(line);
        }
        String data = text.toString();
        JSONArray array = new JSONArray(data);
        updateRulesFromJson(ctx, (JSONObject) array.get(0), PREFS_NAME);
        returnVal = true;
    } catch (FileNotFoundException e) {
        msg.append(ctx.getString(R.string.import_rules_missing));
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getLocalizedMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage());
            }
        }
    }
    return returnVal;
}

From source file:org.geotools.gce.imagemosaic.catalogbuilder.CatalogBuilder.java

/**
 * Creates the final properties file.//from   w w  w  .j  a  v  a 2 s . c  om
 */
private void createPropertiesFiles() {

    //
    // FINAL STEP
    //
    // CREATING GENERAL INFO FILE
    //

    fireEvent(Level.INFO, "Creating final properties file ", 99.9);

    // envelope
    final Properties properties = new Properties();
    properties.setProperty(Utils.Prop.ABSOLUTE_PATH, Boolean.toString(mosaicConfiguration.isAbsolutePath()));
    properties.setProperty(Utils.Prop.LOCATION_ATTRIBUTE, mosaicConfiguration.getLocationAttribute());
    final String timeAttribute = mosaicConfiguration.getTimeAttribute();
    if (timeAttribute != null) {
        properties.setProperty(Utils.Prop.TIME_ATTRIBUTE, mosaicConfiguration.getTimeAttribute());
    }
    final String elevationAttribute = mosaicConfiguration.getElevationAttribute();
    if (elevationAttribute != null) {
        properties.setProperty(Utils.Prop.ELEVATION_ATTRIBUTE, mosaicConfiguration.getElevationAttribute());
    }

    final String additionalDomainAttribute = mosaicConfiguration.getAdditionalDomainAttributes();
    if (additionalDomainAttribute != null) {
        properties.setProperty(Utils.Prop.ADDITIONAL_DOMAIN_ATTRIBUTES,
                mosaicConfiguration.getAdditionalDomainAttributes());
    }

    final int numberOfLevels = mosaicConfiguration.getLevelsNum();
    final double[][] resolutionLevels = mosaicConfiguration.getLevels();
    properties.setProperty(Utils.Prop.LEVELS_NUM, Integer.toString(numberOfLevels));
    final StringBuilder levels = new StringBuilder();
    for (int k = 0; k < numberOfLevels; k++) {
        levels.append(Double.toString(resolutionLevels[0][k])).append(",")
                .append(Double.toString(resolutionLevels[1][k]));
        if (k < numberOfLevels - 1)
            levels.append(" ");
    }
    properties.setProperty(Utils.Prop.LEVELS, levels.toString());
    properties.setProperty(Utils.Prop.NAME, mosaicConfiguration.getName());
    properties.setProperty(Utils.Prop.TYPENAME, mosaicConfiguration.getName());
    properties.setProperty(Utils.Prop.EXP_RGB, Boolean.toString(mustConvertToRGB));
    properties.setProperty(Utils.Prop.HETEROGENEOUS, Boolean.toString(mosaicConfiguration.isHeterogeneous()));

    if (cachedReaderSPI != null) {
        // suggested spi
        properties.setProperty(Utils.Prop.SUGGESTED_SPI, cachedReaderSPI.getClass().getName());
    }

    // write down imposed bbox
    if (imposedBBox != null) {
        properties.setProperty(Utils.Prop.ENVELOPE2D, imposedBBox.getMinX() + "," + imposedBBox.getMinY() + " "
                + imposedBBox.getMaxX() + "," + imposedBBox.getMaxY());
    }
    properties.setProperty(Utils.Prop.CACHING, Boolean.toString(mosaicConfiguration.isCaching()));
    OutputStream outStream = null;
    try {
        outStream = new BufferedOutputStream(new FileOutputStream(runConfiguration.getRootMosaicDirectory()
                + "/" + runConfiguration.getIndexName() + ".properties"));
        properties.store(outStream, "-Automagically created from GeoTools-");
    } catch (FileNotFoundException e) {
        fireEvent(Level.SEVERE, e.getLocalizedMessage(), 0);
    } catch (IOException e) {
        fireEvent(Level.SEVERE, e.getLocalizedMessage(), 0);
    } finally {
        if (outStream != null) {
            IOUtils.closeQuietly(outStream);
        }

    }
}

From source file:org.apache.pig.PigServer.java

/**
 * Register a pig script file.  The parameters in the file will be substituted with the values in the map and the parameter files
 * The values in params Map will override the value in parameter file if they have the same parameter
 * @param fileName  pig script/* w  ww  . j  a v  a 2 s .  c o m*/
 * @param params  the key is the parameter name, and the value is the parameter value
 * @param paramsFiles   files which have the parameter setting
 * @throws IOException
 */
public void registerScript(String fileName, Map<String, String> params, List<String> paramsFiles)
        throws IOException {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileName);
        registerScript(fis, params, paramsFiles);
    } catch (FileNotFoundException e) {
        log.error(e.getLocalizedMessage());
        throw new IOException(e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:org.apache.zeppelin.interpreter.InterpreterSetting.java

private void loadInterpreterDependencies() {
    setStatus(Status.DOWNLOADING_DEPENDENCIES);
    setErrorReason(null);//from   ww  w.  j ava 2  s .c  om
    Thread t = new Thread() {
        public void run() {
            try {
                // dependencies to prevent library conflict
                File localRepoDir = new File(conf.getInterpreterLocalRepoPath() + "/" + id);
                if (localRepoDir.exists()) {
                    try {
                        FileUtils.forceDelete(localRepoDir);
                    } catch (FileNotFoundException e) {
                        LOGGER.info("A file that does not exist cannot be deleted, nothing to worry", e);
                    }
                }

                // load dependencies
                List<Dependency> deps = getDependencies();
                if (deps != null) {
                    for (Dependency d : deps) {
                        File destDir = new File(
                                conf.getRelativeDir(ZeppelinConfiguration.ConfVars.ZEPPELIN_DEP_LOCALREPO));

                        if (d.getExclusions() != null) {
                            dependencyResolver.load(d.getGroupArtifactVersion(), d.getExclusions(),
                                    new File(destDir, id));
                        } else {
                            dependencyResolver.load(d.getGroupArtifactVersion(), new File(destDir, id));
                        }
                    }
                }

                setStatus(Status.READY);
                setErrorReason(null);
            } catch (Exception e) {
                LOGGER.error(
                        String.format("Error while downloading repos for interpreter group : %s,"
                                + " go to interpreter setting page click on edit and save it again to make "
                                + "this interpreter work properly. : %s", getGroup(), e.getLocalizedMessage()),
                        e);
                setErrorReason(e.getLocalizedMessage());
                setStatus(Status.ERROR);
            }
        }
    };

    t.start();
}

From source file:org.gluu.super_gluu.app.ProcessManager.java

public void onOxPushRequest(final Boolean isDeny) {
    //        runOnUiThread(new Runnable() {
    //            @Override
    //            public void run() {
    //                if (isDeny) {
    //                    setFinalStatus(R.string.process_deny_start);
    //                } else {
    //                    setFinalStatus(R.string.process_authentication_start);
    //                }
    //            }
    //        });
    if (oxPush2Request != null) {
        final boolean oneStep = Utils.isEmpty(oxPush2Request.getUserName());

        final Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("application", oxPush2Request.getApp());
        if (!oneStep) {
            parameters.put("username", oxPush2Request.getUserName());
        }//  ww  w  . jav  a 2s.co m

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final U2fMetaData u2fMetaData = getU2fMetaData();

                    //                    dataStore = oxPush2RequestListener.onGetDataStore();
                    final List<byte[]> keyHandles = dataStore
                            .getKeyHandlesByIssuerAndAppId(oxPush2Request.getIssuer(), oxPush2Request.getApp());

                    final boolean isEnroll = StringUtils.equals(oxPush2Request.getMethod(), "enroll");//(keyHandles.size() == 0) ||
                    final String u2fEndpoint;
                    if (isEnroll) {
                        u2fEndpoint = u2fMetaData.getRegistrationEndpoint();
                        if (BuildConfig.DEBUG)
                            Log.i(TAG, "Authentication method: enroll");
                    } else {
                        u2fEndpoint = u2fMetaData.getAuthenticationEndpoint();
                        if (BuildConfig.DEBUG)
                            Log.i(TAG, "Authentication method: authenticate");
                    }

                    //Check if we're using cred manager - in that case "state"== null and we should use "enrollment" parameter
                    if (oxPush2Request.getState() == null) {//using cred-manager
                        parameters.put("enrollment_code", oxPush2Request.getEnrollment());
                    } else {//using standard workflow
                        //Check is old or new version of server
                        String state_key = u2fEndpoint.contains("seam") ? "session_state" : "session_id";
                        parameters.put(state_key, oxPush2Request.getState());
                    }

                    final String challengeJsonResponse;
                    if (oneStep && (keyHandles.size() > 0)) {
                        // Try to get challenge using all keyHandles associated with issuer and application

                        String validChallengeJsonResponse = null;
                        for (byte[] keyHandle : keyHandles) {
                            parameters.put("keyhandle", Utils.base64UrlEncode(keyHandle));
                            try {
                                validChallengeJsonResponse = CommunicationService.get(u2fEndpoint, parameters);
                                break;
                            } catch (FileNotFoundException ex) {
                                Log.i(TAG, "Found invalid keyHandle: " + Utils.base64UrlEncode(keyHandle));
                            }
                        }

                        challengeJsonResponse = validChallengeJsonResponse;
                        if (BuildConfig.DEBUG)
                            Log.d(TAG, "Get U2F JSON response: " + challengeJsonResponse);

                    } else {
                        challengeJsonResponse = CommunicationService.get(u2fEndpoint, parameters);
                        if (BuildConfig.DEBUG)
                            Log.d(TAG, "Get U2F JSON response: " + challengeJsonResponse);
                    }

                    if (Utils.isEmpty(challengeJsonResponse)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setFinalStatus(R.string.no_valid_key_handles);
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    onChallengeReceived(isEnroll, u2fMetaData, u2fEndpoint,
                                            challengeJsonResponse, isDeny);
                                } catch (Exception ex) {
                                    Log.e(TAG,
                                            "Failed to process challengeJsonResponse: " + challengeJsonResponse,
                                            ex);
                                    setFinalStatus(R.string.failed_process_challenge);
                                    if (BuildConfig.DEBUG)
                                        setErrorStatus(ex);
                                }
                            }
                        });
                    }
                } catch (final Exception ex) {
                    Log.e(TAG, ex.getLocalizedMessage(), ex);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setFinalStatus(R.string.wrong_u2f_metadata);
                            if (BuildConfig.DEBUG)
                                setErrorStatus(ex);
                        }
                    });
                }
            }
        }).start();
    }
}