List of usage examples for android.content Context openFileOutput
public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;
From source file:com.android.leanlauncher.LauncherTransitionable.java
private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null;//from w ww . j ava 2 s. c o m try { out = new DataOutputStream(context.openFileOutput(LauncherFiles.LAUNCHER_PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { //noinspection ResultOfMethodCallIgnored context.getFileStreamPath(LauncherFiles.LAUNCHER_PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } }
From source file:org.wso2.emm.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *///from www. j a v a 2s . co m 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.emm.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 e) { Log.e(TAG, e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, 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: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 w w w . j av a 2s . co m*/ 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:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Saves data to the application internal folder. * /*w ww . ja va 2s .c o m*/ * @param context * @param fileName * @param data * @throws Exception */ public static synchronized void storage_storeDataInInternalStorage(Context context, String fileName, byte[] data) throws Exception { try { /* We have to use the openFileOutput()-method * the ActivityContext provides, to * protect your file from others and * This is done for security-reasons. * We chose MODE_WORLD_READABLE, because * we have nothing to hide in our file */ FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE); // Write the string to the file fOut.write(data); /* ensure that everything is really written out and close */ fOut.flush(); fOut.close(); } catch (Exception e) { throw new Exception("Error saving data to '" + fileName + "' (internal storage) : " + e.getMessage(), e); } }
From source file:com.android.mms.ui.MessageUtils.java
/** * M: read app drawable resource and create a new file in /data/data/com.android.mms/files path. * @param context/*from w w w . j a v a2s .com*/ * @param fileName * @return */ public static boolean createFileForResource(Context context, String fileName, int fileResourceId) { OutputStream os = null; InputStream ins = null; try { os = context.openFileOutput(fileName, Context.MODE_PRIVATE); ins = context.getResources().openRawResource(fileResourceId); byte[] buffer = new byte[2048]; for (int len = 0; (len = ins.read(buffer)) != -1;) { os.write(buffer, 0, len); } return true; } catch (FileNotFoundException e) { MmsLog.e(TAG, "create file failed.", e); return false; } catch (IOException e) { MmsLog.e(TAG, "create file failed.", e); return false; } finally { try { if (null != ins) { ins.close(); } if (null != os) { os.close(); } } catch (IOException e) { MmsLog.e(TAG, "createFileForResource:" + e.toString()); } } }
From source file:org.openintents.safe.CryptoHelper.java
/** * Dencrypt a file previously encrypted with * encryptFileWithSessionKey().//from ww w . j av a 2 s .c om * <p/> * The original file is not modified * * @param ctx Context of activity in order to store temp file * @param fileUri Uri to either a stream or a file to read from * @return If decryption is successful, returns Uri of a content * provider to read the plaintext file. Upon failure, * return null. * @throws Exception * @author Peli */ public Uri decryptFileWithSessionKeyThroughContentProvider(Context ctx, Uri fileUri) throws CryptoHelperException { if (debug) { Log.d(TAG, "fileUri=" + fileUri.toString()); } ContentResolver contentResolver = ctx.getContentResolver(); String sessionFile = ""; Uri resultUri = null; boolean result = false; try { InputStream is; if (fileUri.getScheme().equals("file")) { is = new java.io.FileInputStream(fileUri.getPath()); if (debug) { Log.d(TAG, "Decrypt: Input from " + fileUri.getPath()); } } else { is = contentResolver.openInputStream(fileUri); if (debug) { Log.d(TAG, "Decrypt: Input from " + fileUri.toString()); } } FileOutputStream os = null; String decryptSession; try { // create a random session name decryptSession = generateSalt(); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); String msg = "Decrypt error: " + e1.getLocalizedMessage(); throw new CryptoHelperException(msg); } sessionFile = CryptoContentProvider.SESSION_FILE + "." + decryptSession; if (debug) { Log.d(TAG, "Decrypt: Output to " + sessionFile); } // openFileOutput creates a file in /data/data/{packagename}/files/ // In our case, /data/data/org.openintents.safe/files/ // This file is owned and only readable by our application os = ctx.openFileOutput(sessionFile, Context.MODE_PRIVATE); // after writing the decrypted content to a temporary file, // pass back a Uri that can be used to read back the contents resultUri = Uri.withAppendedPath(CryptoContentProvider.CONTENT_URI, "decrypt/" + decryptSession); result = decryptStreamWithSessionKey(is, os); // Close the input stream is.close(); os.close(); } catch (FileNotFoundException e) { Log.e(TAG, "File not found", e); } catch (IOException e) { Log.e(TAG, "IOException", e); } if (result == false) { resultUri = null; // Unsuccessful. Clean up ctx.deleteFile(sessionFile); } return resultUri; }
From source file:com.android.launcher2.Launcher.java
private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null;//from w w w .j a v a 2s .c om try { out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { //noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String RunReboot(OutputStream out, String sCallBackIP, String sCallBackPort) { String sRet = ""; Context ctx = contextWrapper.getApplicationContext(); try {//from w ww .ja v a2 s.c o m if ((sCallBackIP != null) && (sCallBackPort != null) && (sCallBackIP.length() > 0) && (sCallBackPort.length() > 0)) { FileOutputStream fos = ctx.openFileOutput("update.info", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); String sBuffer = sCallBackIP + "," + sCallBackPort + "\rSystem rebooted\r"; fos.write(sBuffer.getBytes()); fos.flush(); fos.close(); fos = null; } } catch (FileNotFoundException e) { sRet = sErrorPrefix + "Callback file creation error [rebt] call failed " + e.getMessage(); e.printStackTrace(); } catch (IOException e) { sRet = sErrorPrefix + "Callback file error [rebt] call failed " + e.getMessage(); e.printStackTrace(); } try { // Tell all of the data channels we are rebooting ((ASMozStub) this.contextWrapper).SendToDataChannel("Rebooting ..."); pProc = Runtime.getRuntime().exec(this.getSuArgs("reboot")); RedirOutputThread outThrd = new RedirOutputThread(pProc, out); outThrd.start(); outThrd.joinAndStopRedirect(10000); } catch (IOException e) { sRet = e.getMessage(); e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return (sRet); }
From source file:com.cognizant.trumobi.PersonaLauncher.java
private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null;/* w w w . jav a2 s .c om*/ try { out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String StrtUpdtOMatic(String sPkgName, String sPkgFileName, String sCallBackIP, String sCallBackPort) { String sRet = ""; Context ctx = contextWrapper.getApplicationContext(); PackageManager pm = ctx.getPackageManager(); Intent prgIntent = new Intent(); prgIntent.setPackage("com.mozilla.watcher"); try {//from w w w . j a va2 s. com PackageInfo pi = pm.getPackageInfo("com.mozilla.watcher", PackageManager.GET_SERVICES | PackageManager.GET_INTENT_FILTERS); ServiceInfo[] si = pi.services; for (int i = 0; i < si.length; i++) { ServiceInfo s = si[i]; if (s.name.length() > 0) { prgIntent.setClassName(s.packageName, s.name); break; } } } catch (NameNotFoundException e) { e.printStackTrace(); sRet = sErrorPrefix + "watcher is not properly installed"; return (sRet); } prgIntent.putExtra("command", "updt"); prgIntent.putExtra("pkgName", sPkgName); prgIntent.putExtra("pkgFile", sPkgFileName); prgIntent.putExtra("reboot", true); try { if ((sCallBackIP != null) && (sCallBackPort != null) && (sCallBackIP.length() > 0) && (sCallBackPort.length() > 0)) { FileOutputStream fos = ctx.openFileOutput("update.info", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); String sBuffer = sCallBackIP + "," + sCallBackPort + "\rupdate started " + sPkgName + " " + sPkgFileName + "\r"; fos.write(sBuffer.getBytes()); fos.flush(); fos.close(); fos = null; prgIntent.putExtra("outFile", ctx.getFilesDir() + "/update.info"); } else { if (prgIntent.hasExtra("outFile")) { System.out.println("outFile extra unset from intent"); prgIntent.removeExtra("outFile"); } } ComponentName cn = contextWrapper.startService(prgIntent); if (cn != null) sRet = "exit"; else sRet = sErrorPrefix + "Unable to use watcher service"; } catch (ActivityNotFoundException anf) { sRet = sErrorPrefix + "Activity Not Found Exception [updt] call failed"; anf.printStackTrace(); } catch (FileNotFoundException e) { sRet = sErrorPrefix + "File creation error [updt] call failed"; e.printStackTrace(); } catch (IOException e) { sRet = sErrorPrefix + "File error [updt] call failed"; e.printStackTrace(); } ctx = null; return (sRet); }