Example usage for android.content.res AssetManager ACCESS_BUFFER

List of usage examples for android.content.res AssetManager ACCESS_BUFFER

Introduction

In this page you can find the example usage for android.content.res AssetManager ACCESS_BUFFER.

Prototype

int ACCESS_BUFFER

To view the source code for android.content.res AssetManager ACCESS_BUFFER.

Click Source Link

Document

Mode for #open(String,int) : Attempt to load contents into memory, for fast small reads.

Usage

From source file:com.github.punkboy.ampdroid.ui.AMPDroidBaseActivity.java

private void copyConfigFromAssets(String fileName) {

    File isConf = new File(getHttpDirectory() + "/conf/" + fileName);

    if (!isConf.exists()) {

        try {// w  w  w  . jav  a  2s  .  c o m

            File mFile = new File(getHttpDirectory() + "/tmp/");

            if (!mFile.exists())
                mFile.mkdir();

            String mString;

            InputStream mStream = getAssets().open(fileName, AssetManager.ACCESS_BUFFER);

            BufferedWriter outputStream = new BufferedWriter(
                    new FileWriter(getHttpDirectory() + "/tmp/" + fileName));

            int c;
            while ((c = mStream.read()) != -1) {
                outputStream.write(c);
            }
            outputStream.close();
            mStream.close();

            mString = FileUtils.readFileToString(new File(getHttpDirectory() + "/tmp/" + fileName), "UTF-8");

            mString = mString.replace("%app_dir%", getAppDirectory());
            mString = mString.replace("%http_dir%", getHttpDirectory());
            FileUtils.writeStringToFile(new File(getHttpDirectory() + "/conf/" + fileName), mString, "UTF-8");
        } catch (Exception e) {
            Log.e(TAG_BASE, "Unable to copy " + fileName + " from assets", e);

        }
    } else {
        Log.d(TAG_BASE, "Config file " + fileName + " already exist no need to overwrite");
    }

}

From source file:com.rukman.emde.smsgroups.platform.GMSContactOperations.java

public static long addGroupToContacts(Context context, ContentProviderClient provider, Account account,
        JSONObject group, SyncResult result)
        throws RemoteException, OperationApplicationException, JSONException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE)
            .withValue(RawContacts.ACCOUNT_NAME, account.name)
            .withValue(RawContacts.SOURCE_ID, group.getString(JSONKeys.KEY_ID));
    ops.add(op.build());/*from w w  w. j  av  a 2s  . c o m*/
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, group.getString(JSONKeys.KEY_NAME));
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.Phone.NUMBER, group.get(JSONKeys.KEY_PHONE))
            .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MAIN);
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE).withYieldAllowed(true);
    ops.add(op.build());
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        is = context.getAssets().open("gms.png", AssetManager.ACCESS_BUFFER);
        baos = new ByteArrayOutputStream();
        int value = is.read();
        while (value != -1) {
            baos.write(value);
            value = is.read();
        }
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
                .withYieldAllowed(true);
        ops.add(op.build());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L;
}

From source file:com.github.DroidPHP.ServerUtils.java

final private static void restoreConfiguration(String fileName) {

    File isConf = new File(getHttpDirectory() + "/conf/" + fileName);
    if (!isConf.exists()) {

        try {//from   www .jav a2 s . c  o  m

            String mString;

            java.io.InputStream mStream = mContext.getAssets().open(fileName, AssetManager.ACCESS_BUFFER);

            java.io.BufferedWriter outputStream = new java.io.BufferedWriter(
                    new java.io.FileWriter(getHttpDirectory() + "/tmp/" + fileName));

            int c;
            while ((c = mStream.read()) != -1) {
                outputStream.write(c);
            }
            outputStream.close();
            mStream.close();

            mString = org.apache.commons.io.FileUtils
                    .readFileToString(new File(getHttpDirectory() + "/tmp/" + fileName), "UTF-8");

            mString = mString.replace("%app_dir%", getAppDirectory());
            mString = mString.replace("%http_dir%", getHttpDirectory());
            mString = mString.replace("%port%", serverPort);
            org.apache.commons.io.FileUtils
                    .writeStringToFile(new File(getHttpDirectory() + "/conf/" + fileName), mString, "UTF-8");
        } catch (java.lang.Exception e) {
            Log.e(TAG, "Unable to copy " + fileName + " from assets", e);

        }
    }

}

From source file:tv.ouya.sdk.CordovaOuyaPlugin.java

public void initOuyaPlugin(final JSONArray jsonArray) {
    if (null == jsonArray) {
        JSONObject result = createError(0, "initOuyaPlugin jsonArray is null!");
        sCallbackInitOuyaPlugin.error(result);
        return;/*w  ww  . ja v  a  2 s .  c o m*/
    }

    if (sEnableLogging) {
        Log.i(TAG, "initOuyaPlugin jsonArray=" + jsonArray.toString());
    }

    sInitCompletedListener = new CancelIgnoringOuyaResponseListener<Bundle>() {
        @Override
        public void onSuccess(final Bundle info) {
            if (sEnableLogging) {
                Log.i(TAG, "sInitCompletedListener: onSuccess");
            }
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS");
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            if (sEnableLogging) {
                Log.i(TAG, "sInitCompletedListener: onFailure errorCode=" + errorCode + " errorMessage="
                        + errorMessage);
            }
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, result);
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }
    };

    sRequestGamerInfoListener = new CancelIgnoringOuyaResponseListener<GamerInfo>() {
        @Override
        public void onSuccess(final GamerInfo info) {
            Log.i(TAG, "sRequestGamerInfoListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("username", info.getUsername());
                        result.put("uuid", info.getUuid());
                    } catch (JSONException e) {
                        result = createError(0, "Failed to create results!");
                        sCallbackRequestGamerInfo.error(result);
                        return;
                    }
                    sCallbackRequestGamerInfo.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestGamerInfoListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestGamerInfo.error(result);
                }
            });
        }
    };

    sRequestProductsListener = new CancelIgnoringOuyaResponseListener<List<Product>>() {
        @Override
        public void onSuccess(final List<Product> products) {
            Log.i(TAG, "sRequestProductsListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONArray result = new JSONArray();
                    try {
                        int i = 0;
                        for (Product product : products) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("description", product.getDescription());
                            jsonObject.put("identifier", product.getIdentifier());
                            jsonObject.put("name", product.getName());
                            jsonObject.put("localPrice", product.getLocalPrice());
                            result.put(i, jsonObject);
                            ++i;
                        }
                    } catch (JSONException e) {
                        JSONObject error = createError(0, "Failed to create results!");
                        sCallbackRequestProducts.error(error);
                        return;
                    }
                    sCallbackRequestProducts.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestProductsListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestProducts.error(result);
                }
            });
        }
    };

    sRequestPurchaseListener = new OuyaResponseListener<PurchaseResult>() {

        @Override
        public void onSuccess(final PurchaseResult purchaseResult) {
            Log.i(TAG, "sRequestPurchaseListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("productIdentifier", purchaseResult.getProductIdentifier());
                    } catch (JSONException e) {
                        result = createError(0, "Failed to set productIdentifier!");
                        sCallbackRequestPurchase.error(result);
                        return;
                    }
                    sCallbackRequestPurchase.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestPurchaseListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestPurchase.error(result);
                }
            });
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "sRequestPurchaseListener: onCancel");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Purchase was cancelled!");
                    sCallbackRequestPurchase.error(result);
                }
            });
        }
    };

    sRequestReceiptsListener = new OuyaResponseListener<Collection<Receipt>>() {

        @Override
        public void onSuccess(final Collection<Receipt> receipts) {
            Log.i(TAG, "requestReceipts onSuccess: received " + receipts.size() + " receipts");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONArray result = new JSONArray();
                    try {
                        int i = 0;
                        for (Receipt receipt : receipts) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("currency", receipt.getCurrency());
                            jsonObject.put("generatedDate", receipt.getGeneratedDate());
                            jsonObject.put("identifier", receipt.getIdentifier());
                            jsonObject.put("localPrice", receipt.getLocalPrice());
                            result.put(i, jsonObject);
                            ++i;
                        }
                    } catch (JSONException e) {
                        JSONObject error = createError(0, "Failed to create results!");
                        sCallbackRequestReceipts.error(error);
                        return;
                    }
                    sCallbackRequestReceipts.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.e(TAG, "requestReceipts onFailure: errorCode=" + errorCode + " errorMessage=" + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestReceipts.error(result);
                }
            });
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "requestReceipts onCancel");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Request Receipts was cancelled!");
                    sCallbackRequestReceipts.error(result);
                }
            });
        }
    };

    Runnable runnable = new Runnable() {
        public void run() {

            Bundle developerInfo = new Bundle();

            try {
                for (int index = 0; index < jsonArray.length(); ++index) {
                    JSONObject jsonObject = jsonArray.getJSONObject(index);
                    String name = jsonObject.getString("key");
                    String value = jsonObject.getString("value");
                    if (null == name || null == value) {
                        continue;
                    }
                    if (name.equals("tv.ouya.product_id_list")) {
                        String[] productIds = value.split(",");
                        if (null == productIds) {
                            continue;
                        }
                        developerInfo.putStringArray("tv.ouya.product_id_list", productIds);
                    } else {
                        Log.i(TAG, "initOuyaPlugin name=" + name + " value=" + value);
                        developerInfo.putString(name, value);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "initOuyaPlugin Failed to read JSON data!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });

                return;
            }

            byte[] applicationKey = null;

            // load the application key from assets
            try {
                AssetManager assetManager = cordova.getActivity().getAssets();
                InputStream inputStream = assetManager.open("key.der", AssetManager.ACCESS_BUFFER);
                applicationKey = new byte[inputStream.available()];
                inputStream.read(applicationKey);
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to load signing key!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });

                return;
            }

            if (null == applicationKey) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to load signing key!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            developerInfo.putByteArray(OuyaFacade.OUYA_DEVELOPER_PUBLIC_KEY, applicationKey);

            try {
                sOuyaFacade = OuyaFacade.getInstance();
            } catch (Exception e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to get OUYA Facade instance!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            /*
            try {
            sOuyaFacade.registerInitCompletedListener(sInitCompletedListener);
            } catch (Exception e) {
            e.printStackTrace();
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Failed to register init completed listener!");
                    sCallbackInitOuyaPlugin.error(result);
                }
            });
            return;
            }
            */

            try {
                sOuyaFacade.init(cordova.getActivity(), developerInfo);
            } catch (Exception e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to initialize the OuyaFacade!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            /*
            cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "WAIT");
                pluginResult.setKeepCallback(true);
                sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
            }
            });
            */

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS");
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }
    };
    cordova.getActivity().runOnUiThread(runnable);
}