Example usage for android.content Context getDir

List of usage examples for android.content Context getDir

Introduction

In this page you can find the example usage for android.content Context getDir.

Prototype

public abstract File getDir(String name, @FileMode int mode);

Source Link

Document

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

Usage

From source file:com.hunch.ImageManager.java

protected void addToInternalCache(Bitmap d, URL url, Context context) {
    final String fileName = fileNameFromURL(url);
    File hunchImagesDir = context.getDir(Const.INTERNAL_IMG_DIR, Context.MODE_PRIVATE);

    // directory is guaranteed to exist by getDir()
    File imageFile = new File(hunchImagesDir, fileName);

    /*if( !imageFile.canWrite() )
    {//from w  w  w.j  ava 2 s.  c  om
       Log.w( Const.TAG, "can't write to internal image cache! (" + imageFile.toString() + ")" );
       return;
    }*/

    FileOutputStream fOut = null;
    try {
        fOut = new FileOutputStream(imageFile);

    } catch (FileNotFoundException e) {
        Log.w(Const.TAG,
                "can't find or write to file in internal cache! (" + imageFile.getAbsolutePath() + ")");
        return;
    }

    boolean success = d.compress(Bitmap.CompressFormat.PNG, 0, fOut);
    if (!success) {
        Log.w(Const.TAG, "image compress for internal cache failed! (" + imageFile.getAbsolutePath() + ")");
    }

    try {
        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        Log.w(Const.TAG, "couldn't flush or close output stream for internal cache! ("
                + imageFile.getAbsolutePath() + ")");
    }

}

From source file:com.hunch.ImageManager.java

protected FileInputStream getImageFileStreamFromInternal(final Context context, final URL url) {
    final String fileName = fileNameFromURL(url);
    File internalImagesDir = context.getDir(Const.INTERNAL_IMG_DIR, Context.MODE_PRIVATE);

    // the directory is guaranteed to exist by getDir()

    File[] imageFileList = internalImagesDir.listFiles(new FilenameFilter() {

        @Override//from  www  .j  a  v a  2  s .  co m
        public boolean accept(File dir, String aFilename) {
            return fileName.equals(aFilename);
        }
    });

    if (imageFileList == null || imageFileList.length == 0) {
        return null;
    }

    if (imageFileList.length > 1) {
        Log.i(Const.TAG,
                "found " + imageFileList.length + " images for url in internal cache! " + "(" + fileName + ")");
    }

    FileInputStream iStream = null;
    try {
        iStream = new FileInputStream(imageFileList[0]);
    } catch (FileNotFoundException e) {
        return null;
    }

    //Log.v( Const.TAG, "found image in internal cache (" + url + ")" );

    return iStream;
}

From source file:org.opendatakit.properties.PropertiesSingleton.java

PropertiesSingleton(Context context, String appName, TreeMap<String, String> plainDefaults,
        TreeMap<String, String> deviceDefaults, TreeMap<String, String> secureDefaults) {
    mAppName = appName;/*from   ww  w.ja v a2 s .co  m*/
    mHasSecureStorage = context.getPackageName().equals(IntentConsts.AppProperties.APPLICATION_NAME);
    if (mHasSecureStorage) {
        mSecureStorageDir = context.getDir(mAppName, 0);
    } else {
        mSecureStorageDir = null;
    }
    // these strings are set as untranslateable
    CREDENTIAL_TYPE_NONE = context.getString(R.string.credential_type_none);
    CREDENTIAL_TYPE_USERNAME_PASSWORD = context.getString(R.string.credential_type_username_password);
    CREDENTIAL_TYPE_GOOGLE_ACCOUNT = context.getString(R.string.credential_type_google_account);

    mGeneralDefaults = plainDefaults;
    mDeviceDefaults = deviceDefaults;
    mSecureDefaults = secureDefaults;

    // initialize the cache of properties read from the sdcard
    mGeneralProps = new Properties();
    mGlobalDeviceProps = new Properties();
    mDeviceProps = new Properties();
    mSecureProps = new Properties();

    // call init
    init();
}

From source file:com.cloudant.sync.cordova.CloudantSyncPlugin.java

private void setDocumentStorePath(JSONArray args, final CallbackContext callbackContext) throws JSONException {
    final String path;
    if (JSONObject.NULL.equals(args.get(0))) {
        Context context = cordova.getActivity().getApplicationContext();
        File fp = context.getDir(DEFAULT_DOCUMENT_STORE_DIR_NAME, Context.MODE_PRIVATE);
        path = fp.getAbsolutePath();//from  w w w.  ja v  a 2s .  c o m
    } else {
        path = args.getString(0);
    }

    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
            int id = documentStorePaths.size();
            // Auto-boxing id.
            documentStorePaths.put(id, path);
            JSONObject response = new JSONObject();
            try {
                response.put("id", id);
            } catch (JSONException e) {
                // This should never happen, terminate
                throw new RuntimeException(e);
            }
            callbackContext.success(response);
        }
    });
}

From source file:csh.cryptonite.Cryptonite.java

public static void setupReadDirs(boolean external, Context context) {
    if (DirectorySettings.INSTANCE.openDir != null) {
        Cryptonite.deleteDir(DirectorySettings.INSTANCE.openDir);
    }/*  w  ww .  ja v a2s. co m*/
    if (DirectorySettings.INSTANCE.readDir != null) {
        Cryptonite.deleteDir(DirectorySettings.INSTANCE.readDir);
    }

    if (external && Cryptonite.externalStorageIsWritable()) {
        context.getExternalCacheDir().mkdirs();
        DirectorySettings.INSTANCE.openDir = new File(
                context.getExternalCacheDir().getPath() + "/" + DirectorySettings.OPENPNT);
        DirectorySettings.INSTANCE.readDir = new File(
                context.getExternalCacheDir().getPath() + "/" + DirectorySettings.READPNT);
        DirectorySettings.INSTANCE.openDir.mkdirs();
        DirectorySettings.INSTANCE.readDir.mkdirs();
    } else {
        DirectorySettings.INSTANCE.openDir = context.getDir(DirectorySettings.OPENPNT, Context.MODE_PRIVATE);
        DirectorySettings.INSTANCE.readDir = context.getDir(DirectorySettings.READPNT,
                Context.MODE_WORLD_READABLE);
    }
}

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

public static String getKLogPath(Context ctx) {
    return ctx.getDir("bin", 0).getAbsolutePath() + "/klogripper ";
}

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

static String getNflogPath(Context ctx) {
    return ctx.getDir("bin", 0).getAbsolutePath() + "/nflog ";
}

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

static String customScriptHeader(Context ctx) {
    final String dir = ctx.getDir("bin", 0).getAbsolutePath();
    final String myiptables = dir + "/iptables";
    final String mybusybox = dir + "/busybox";
    return "" + "IPTABLES=" + myiptables + "\n" + "BUSYBOX=" + mybusybox + "\n" + "";
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

public static void setPcap(boolean enabled, Context context) {
    File pcap = (enabled ? new File(context.getDir("data", MODE_PRIVATE), "netguard.pcap") : null);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String r = prefs.getString("pcap_record_size", null);
    if (TextUtils.isEmpty(r))
        r = "64";
    String f = prefs.getString("pcap_file_size", null);
    if (TextUtils.isEmpty(f))
        f = "2";/*from w  ww .ja v  a 2s . c om*/
    int record_size = Integer.parseInt(r);
    int file_size = Integer.parseInt(f) * 1024 * 1024;
    jni_pcap(pcap == null ? null : pcap.getAbsolutePath(), record_size, file_size);
}

From source file:ca.psiphon.PsiphonTunnel.java

private String setupTrustedCertificates(Context context) throws Exception {

    // Copy the Android system CA store to a local, private cert bundle file.
    ////from   w ww  .  j  a v  a 2 s. c o m
    // This results in a file that can be passed to SSL_CTX_load_verify_locations
    // for use with OpenSSL modes in tunnel-core.
    // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
    //
    // TODO: to use the path mode of load_verify_locations would require emulating
    // the filename scheme used by c_rehash:
    // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
    // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs

    File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);

    final String errorMessage = "copy AndroidCAStore failed";
    try {

        File file = new File(directory, "certs.dat");

        // Pave a fresh copy on every run, which ensures we're not using old certs.
        // Note: assumes KeyStore doesn't return revoked certs.
        //
        // TODO: this takes under 1 second, but should we avoid repaving every time?
        file.delete();

        PrintStream output = null;
        try {
            output = new PrintStream(new FileOutputStream(file));

            KeyStore keyStore;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                keyStore = KeyStore.getInstance("AndroidCAStore");
                keyStore.load(null, null);
            } else {
                keyStore = KeyStore.getInstance("BKS");
                FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
                try {
                    keyStore.load(inputStream, "changeit".toCharArray());
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }

            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);

                output.println("-----BEGIN CERTIFICATE-----");
                String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
                // OpenSSL appears to reject the default linebreaking done by Base64.encode,
                // so we manually linebreak every 64 characters
                for (int i = 0; i < pemCert.length(); i += 64) {
                    output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
                }
                output.println("-----END CERTIFICATE-----");
            }

            mHostService.onDiagnosticMessage("prepared PsiphonCAStore");

            return file.getAbsolutePath();

        } finally {
            if (output != null) {
                output.close();
            }
        }

    } catch (KeyStoreException e) {
        throw new Exception(errorMessage, e);
    } catch (NoSuchAlgorithmException e) {
        throw new Exception(errorMessage, e);
    } catch (CertificateException e) {
        throw new Exception(errorMessage, e);
    } catch (IOException e) {
        throw new Exception(errorMessage, e);
    }
}