Example usage for android.content Context openFileInput

List of usage examples for android.content Context openFileInput

Introduction

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

Prototype

public abstract FileInputStream openFileInput(String name) throws FileNotFoundException;

Source Link

Document

Open a private file associated with this Context's application package for reading.

Usage

From source file:net.sf.xfd.provider.PublicProvider.java

private static @Nullable Key getSalt(Context c) {
    if (cookieSalt == null) {
        synchronized (PublicProvider.class) {
            if (cookieSalt == null) {
                try {
                    try (ObjectInputStream oos = new ObjectInputStream(c.openFileInput(COOKIE_FILE))) {
                        cookieSalt = (Key) oos.readObject();
                    } catch (ClassNotFoundException | IOException e) {
                        LogUtil.logCautiously("Unable to read key file, probably corrupted or missing", e);

                        final File corrupted = c.getFileStreamPath(COOKIE_FILE);

                        //noinspection ResultOfMethodCallIgnored
                        corrupted.delete();
                    }//from  w ww.j  a v  a  2 s .  c o m

                    if (cookieSalt != null) {
                        return cookieSalt;
                    }

                    final KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA1");
                    keygen.init(COOKIE_SIZE * Byte.SIZE);

                    cookieSalt = keygen.generateKey();

                    try (ObjectOutputStream oos = new ObjectOutputStream(
                            c.openFileOutput(COOKIE_FILE, Context.MODE_PRIVATE))) {
                        oos.writeObject(cookieSalt);
                    } catch (IOException e) {
                        LogUtil.logCautiously("Failed to save key file", e);

                        return null;
                    }
                } catch (NoSuchAlgorithmException e) {
                    throw new AssertionError("failed to initialize hash functions", e);
                }
            }
        }
    }

    return cookieSalt;
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Get string version of HTML for a web page. Cache HTML for future acccess.
 * //from w w  w.ja va  2  s .  com
 * @param context
 * @param url
 * @param refresh
 * @return
 */
public synchronized static final String getCachedData(Context context, String url, boolean refresh) {
    Log.d(LOG_TAG, "getCachedData: " + url);
    String data = null;
    boolean exists = false;
    String cleanUrl = "cache." + clean(url);
    File file = context.getFileStreamPath(cleanUrl);
    if (file != null && file.exists()) {
        exists = true;
    }

    if (!refresh && exists) {
        try {
            FileInputStream fis = context.openFileInput(cleanUrl);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringBuffer buffer = new StringBuffer();
            for (String line; (line = br.readLine()) != null;) {
                buffer.append(line);
            }
            fis.close();
            data = buffer.toString();
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error getData: " + url, e);
        }
    } else {
        boolean found = false;
        StringBuilder builder = new StringBuilder();
        try {
            InputStream stream = new HttpRequestHelper().getHttpStream(url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            stream.close();
            found = true;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error getData: " + url, e);
        } catch (Exception e) {
            Log.e(LOG_TAG, "stream is NULL");
        }
        data = builder.toString();
        if (!found && exists) {
            try {
                FileInputStream fis = context.openFileInput(cleanUrl);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                StringBuffer buffer = new StringBuffer();
                for (String line; (line = br.readLine()) != null;) {
                    buffer.append(line);
                }
                fis.close();
                data = buffer.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            }
        }
        if (data != null && data.trim().length() > 0) {
            try {
                FileOutputStream fos = context.openFileOutput(cleanUrl, Context.MODE_PRIVATE);
                fos.write(data.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            }
        }
    }
    return data;
}

From source file:com.farmerbb.secondscreen.util.U.java

public static String getProfileTitle(Context context, String filename) throws IOException {
    // Open the file on disk
    FileInputStream input = context.openFileInput(filename);
    InputStreamReader reader = new InputStreamReader(input);
    BufferedReader buffer = new BufferedReader(reader);

    // Load the file
    String line = buffer.readLine();

    // Close file on disk
    reader.close();/*from   w w w . j a  v a2s .  c  om*/

    return (line);
}

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

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*from ww  w.  jav  a 2 s.c om*/
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.iot.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 | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, 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.thoughtmetric.tl.TLLib.java

public static Object[] tagNodeWithEditText(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {
    Object[] ret = new Object[2];

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (login) {//from   w w  w  . j a  v a  2s  .c  om
        httpclient.setCookieStore(cookieStore);
    }
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    InputStream is = response.getEntity().getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(context.openFileInput(TEMP_FILE_NAME)));
    ret[0] = TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
    ret[1] = parseTextArea(br);

    return ret;
}

From source file:net.fizzl.redditengine.impl.PersistentCookieStore.java

/**
 * Load Cookies from a file/* ww  w  .j ava 2  s .  c o m*/
 */
private void load() {
    RedditApi api = DefaultRedditApi.getInstance();
    Context ctx = api.getContext();
    try {
        FileInputStream fis = ctx.openFileInput(cookiestore);
        ObjectInputStream ois = new ObjectInputStream(fis);
        SerializableCookieStore tempStore = (SerializableCookieStore) ois.readObject();

        super.clear();
        for (Cookie c : tempStore.getCookies()) {
            super.addCookie(c);
        }

        ois.close();
        fis.close();
    } catch (FileNotFoundException e) {
        Log.w(getClass().getName(), e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }//from   w ww.  j  a  v  a  2s .c o  m

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:net.sileht.lullaby.Utils.java

public Object load(Context ctx, String name) {

    try {/*from  w w w. j ava  2 s  .  c o m*/
        FileInputStream pin = ctx.openFileInput(name);
        Object objs = (new ObjectInputStream(pin)).readObject();
        pin.close();
        return objs;
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.blanco.techmun.android.cproviders.MesasFetcher.java

private Mesas tryToLoadFromCache(Context context) {
    try {// w  ww  . j  a  v  a 2s  . c om
        FileInputStream mesasFIS = context.openFileInput("mesas.df");
        ObjectInputStream mesasOIS = new ObjectInputStream(mesasFIS);
        Mesas result = (Mesas) mesasOIS.readObject();
        mesasOIS.close();
        return result;
    } catch (IOException e) {
        Log.e("tachmun",
                "Error opening cache file for mesas in content provider. " + "No cache will be restored", e);
        return null;
    } catch (ClassNotFoundException e) {
        Log.e("tachmun", "Error in cache file for mesas in content provider. "
                + "Something is there but is not a Mesas object. Cache no restored", e);
        return null;
    }
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

public static String ReadSettings(Context context, String file) throws IOException {
    FileInputStream fis = null;/*ww  w. ja va 2  s .  c  om*/
    InputStreamReader isr = null;
    String data = null;
    fis = context.openFileInput(file);
    isr = new InputStreamReader(fis);
    char[] inputBuffer = new char[fis.available()];
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    isr.close();
    fis.close();
    return data;
}