Example usage for android.content.res AssetManager open

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

Introduction

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

Prototype

public @NonNull InputStream open(@NonNull String fileName) throws IOException 

Source Link

Document

Open an asset using ACCESS_STREAMING mode.

Usage

From source file:com.photon.phresco.nativeapp.unit.test.testcases.A_MainActivityTest.java

/**
 * Read phresco-env-config.xml file to get to connect to web service
 *//*  w  w  w . j av a 2  s .c  om*/
public void readConfigXML() {
    try {

        String protocol = "protocol";
        String host = "host";
        String port = "port";
        String context = "context";
        Resources resources = this.mContext.getResources();
        AssetManager assetManager = resources.getAssets();
        Properties properties = new Properties();

        // Read from the /assets directory
        InputStream inputStream = assetManager.open(Constants.PHRESCO_ENV_CONFIG);

        ConfigReader confReaderObj = new ConfigReader(inputStream);

        PhrescoLogger.info(TAG + "Default ENV = " + confReaderObj.getDefaultEnvName());

        List<Configuration> configByEnv = confReaderObj.getConfigByEnv(confReaderObj.getDefaultEnvName());

        for (Configuration configuration : configByEnv) {
            properties = configuration.getProperties();
            PhrescoLogger.info(TAG + "config value = " + configuration.getProperties());
            String webServiceProtocol = properties.getProperty(protocol).endsWith("://")
                    ? properties.getProperty(protocol)
                    : properties.getProperty(protocol) + "://"; // http://

            String webServiceHost = properties.getProperty(port).equalsIgnoreCase("")
                    ? (properties.getProperty(host).endsWith("/") ? properties.getProperty(host)
                            : properties.getProperty(host) + "/")
                    : properties.getProperty(host); // localhost/
            // localhost

            String webServicePort = properties.getProperty(port).equalsIgnoreCase("") ? ""
                    : (properties.getProperty(port).startsWith(":") ? properties.getProperty(port)
                            : ":" + properties.getProperty(port)); // "" (blank)
            // :1313

            String webServiceContext = properties.getProperty(context).startsWith("/")
                    ? properties.getProperty(context)
                    : "/" + properties.getProperty(context); // /phresco

            Constants.setWebContextURL(
                    webServiceProtocol + webServiceHost + webServicePort + webServiceContext + "/");
            Constants.setRestAPI(Constants.REST_API);
            PhrescoLogger.info(
                    TAG + "Constants.webContextURL : " + Constants.getWebContextURL() + Constants.getRestAPI());
        }

    } catch (ParserConfigurationException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : ParserConfigurationException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (SAXException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : SAXException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (IOException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : IOException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (Exception ex) {
        PhrescoLogger.info(TAG + "readConfigXML : Exception: " + ex.toString());
        PhrescoLogger.warning(ex);
    }
}

From source file:com.littlepancake.glpk.HelpFragment.java

private void openGlpkPdf() {
    AssetManager assetManager = getActivity().getAssets();

    File file = new File(getActivity().getFilesDir(), glpkPdfName);

    if (!file.exists()) {
        InputStream in = null;/*w ww  . ja va 2  s. c o  m*/
        OutputStream out = null;
        try {
            in = assetManager.open(glpkPdfName);
            /* Note that "MODE_WORLD_READABLE" is "dangerous". It seems the alternative is
             * for me to write a few hundred more lines of code or something. Guess I'll
             * remain dangerous for this app.
             * See:
             *  https://github.com/commonsguy/cw-omnibus/tree/master/ContentProvider/Files
             * for the proper, code-intensive way to handle this.
             */
            out = getActivity().openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
            byte[] buffer = new byte[buff_size];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            out.flush();
            out.close();
            out = null;
            in = null;
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }
    } else {
        //Log.d("tag", glpkPdfName+" already exists.");
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + getActivity().getFilesDir() + "/" + glpkPdfName),
            "application/pdf");
    startActivity(intent);
}

From source file:com.littlepancake.glpk.HelpFragment.java

private void openGplTxt() {
    AssetManager assetManager = getActivity().getAssets();

    File file = new File(getActivity().getFilesDir(), gplv3FileName);

    if (!file.exists()) {
        InputStream in = null;//from   w ww.jav  a 2 s  .  co  m
        OutputStream out = null;
        try {
            in = assetManager.open(gplv3FileName);
            /* Note that "MODE_WORLD_READABLE" is "dangerous". It seems the alternative is
             * for me to write a few hundred more lines of code or something. Guess I'll
             * remain dangerous for this app.
             * See:
             *  https://github.com/commonsguy/cw-omnibus/tree/master/ContentProvider/Files
             * for the proper, code-intensive way to handle this.
             */
            out = getActivity().openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
            byte[] buffer = new byte[buff_size];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
                Log.d("tag", "Read and wrote " + read + " bytes.");
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }
    } else {
        //Log.d("tag", gplv3FileName+" already exists.");
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + getActivity().getFilesDir() + "/" + gplv3FileName),
            "text/plain");
    startActivity(intent);
}

From source file:com.bazaarvoice.test.SubmissionTests.VideoSubmissionTest.java

public void testVideoSubmit2() {

    //Your PC can't communicate with your device and access your sd card at the same time.  So for this test, lets
    //download a well know video that we don't think is going anywhere so the tests will successfully complete.  If
    //this fails just change the url to something that works
    OnBazaarResponseHelper bazaarResponse = new OnBazaarResponseHelper() {
        @Override/*from   w w w  .  j  a v a2  s .c o m*/
        public void onResponseHelper(JSONObject response) throws JSONException {
            Log.e(tag, "End of video submit transmission : END " + System.currentTimeMillis());

            Log.i(tag, "Response = \n" + response);

            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Video").getString("VideoUrl"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");

    AssetManager assets = this.mContext.getAssets();
    File dir = this.mContext.getDir("TEMP", 0);
    File file = new File(dir, "video.mp4");

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = assets.open("Android_Video.mp4");
        out = new FileOutputStream(file);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        mediaParams.setVideo(file);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.e(tag, "Begin of video submit transmission : BEGIN " + System.currentTimeMillis());
    submitMedia.postSubmission(RequestType.VIDEOS, mediaParams, bazaarResponse);
    bazaarResponse.waitForTestToFinish();
}

From source file:com.esri.arcgisruntime.sample.choosecameracontroller.MainActivity.java

/**
 * Copy the given file from the app's assets folder to the app's cache directory.
 *
 * @param fileName as String//from  ww w.j a va  2 s  .c  o  m
 */
private void copyFileFromAssetsToCache(String fileName) {
    AssetManager assetManager = getApplicationContext().getAssets();
    File file = new File(getCacheDir() + File.separator + fileName);
    if (!file.exists()) {
        try {
            BufferedInputStream bis = new BufferedInputStream(assetManager.open(fileName));
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(getCacheDir() + File.separator + fileName));
            byte[] buffer = new byte[bis.available()];
            int read = bis.read(buffer);
            while (read != -1) {
                bos.write(buffer, 0, read);
                read = bis.read(buffer);
            }
            bos.close();
            bis.close();
            Log.i(TAG, fileName + " copied to cache.");
        } catch (Exception e) {
            Log.e(TAG, "Error writing " + fileName + " to cache. " + e.getMessage());
        }
    } else {
        Log.i(TAG, fileName + " already in cache.");
    }
}

From source file:com.bazaarvoice.test.SubmissionTests.PhotoSubmissionTest.java

public void testPhotoSubmit4() {

    OnBazaarResponseHelper bazaarResponse = new OnBazaarResponseHelper() {
        @Override/*w w  w  . j  a v  a2s.  c o  m*/
        public void onResponseHelper(JSONObject response) throws JSONException {
            Log.e(tag, "End of photo submit transmission : END " + System.currentTimeMillis());

            Log.i(tag, "Response = \n" + response);
            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Photo"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW_COMMENT);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");

    AssetManager assets = this.mContext.getAssets();

    InputStream in = null;
    ByteArrayOutputStream out = null;

    try {
        in = assets.open("RalphRocks.jpg");
        out = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

        mediaParams.setPhoto(out.toByteArray(), "RalphRocks.jpg");

        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e(tag, "Begin of photo submit transmission : BEGIN " + System.currentTimeMillis());
    submitMedia.postSubmission(RequestType.PHOTOS, mediaParams, bazaarResponse);
    bazaarResponse.waitForTestToFinish();
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

private Bitmap getIconFromUri(String path) {
    try {//from   w ww  .  j  av a 2  s.  c  o  m
        AssetManager amgr = context.getAssets();
        String tmp_uri = "www/" + path;
        InputStream input = amgr.open(tmp_uri);

        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        LOG.e(NotificationPlugin.TAG, "cant load icon from " + "www/" + path);
        LOG.e(NotificationPlugin.TAG, e.getMessage());
        return null;
    }
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 * The URI for an asset.//from w  w  w .j  a  va2  s . co  m
 * 
 * @param path
 *            The given asset path
 * 
 * @return The URI pointing to the given path
 */
private Uri getUriForAssetPath(String path) {
    String resPath = path.replaceFirst("file:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    File dir = activity.getExternalCacheDir();
    if (dir == null) {
        Log.e("Asset", "Missing external cache dir");
        return Uri.EMPTY;
    }
    String storage = dir.toString() + STORAGE_FOLDER;
    File file = new File(storage, fileName);
    new File(storage).mkdir();
    try {
        AssetManager assets = activity.getAssets();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = assets.open(resPath);
        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (Exception e) {
        Log.e("Asset", "File not found: assets/" + resPath);
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.tvserial.plot.amazon.trailer.MainActivity.java

public void Fileread() {
    String line = "";
    AssetManager assetManager = MainActivity.context.getAssets();
    InputStream input = null;/*from   ww w .j a  v  a2s .  com*/
    try {
        input = assetManager.open("amazon.html");
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        if (input != null) {
            /*   BufferedReader br = new BufferedReader(new InputStreamReader(
                     input));*/
            int size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);

            // byte buffer into a string
            String text = new String(buffer);
            line = text;
            // String line;

            // read every line of the file into the line-variable, on line
            // at the time
            /*do {
               line = line + "\n" + br.readLine();
                    
               // do something with the line
            } while (br.readLine() != null);*/

        }
    } catch (Exception ex) {
        // print stack trace.
    } finally {
        // close the file.
        try {
            input.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    URLlist.Sdata = line;
}

From source file:se.rebootit.android.tagbiljetter.DataParser.java

/**
 * Return the list of loaded companies/*  ww w.j av a  2 s  .  c o  m*/
 */
@SuppressWarnings("unchecked")
public ArrayList<TransportCompany> getCompanies() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    DefaultHandler handler = new TransportCompanyHandler();
    AssetManager assetManager = context.getAssets();
    try {
        InputStream inputStream = assetManager.open("TransportCompanies.xml");
        SAXParser parser = factory.newSAXParser();
        parser.parse(inputStream, handler);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.lstCompanies.clear();
    this.lstCompanies.addAll((ArrayList) ((TransportCompanyHandler) handler).getCompanies());

    for (TransportCompany transportCompany : this.lstCompanies) {
        mapCompanies.put(transportCompany.getId(), transportCompany);
    }

    Collections.sort(this.lstCompanies, new Comparator<TransportCompany>() {
        public int compare(TransportCompany p1, TransportCompany p2) {
            return p1.getName().compareTo(p2.getName());
        }
    });

    return this.lstCompanies;
}