List of usage examples for android.content Context openFileInput
public abstract FileInputStream openFileInput(String name) throws FileNotFoundException;
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String UpdateCallBack(String sFileName) { String sRet = sErrorPrefix + "No file specified"; String sIP = ""; String sPort = ""; int nEnd = 0; int nStart = 0; if ((sFileName == null) || (sFileName.length() == 0)) return (sRet); Context ctx = contextWrapper.getApplicationContext(); try {//from w w w. j av a 2 s .co m FileInputStream fis = ctx.openFileInput(sFileName); int nBytes = fis.available(); if (nBytes > 0) { byte[] buffer = new byte[nBytes + 1]; int nRead = fis.read(buffer, 0, nBytes); fis.close(); ctx.deleteFile(sFileName); if (nRead > 0) { String sBuffer = new String(buffer); nEnd = sBuffer.indexOf(','); if (nEnd > 0) { sIP = (sBuffer.substring(0, nEnd)).trim(); nStart = nEnd + 1; nEnd = sBuffer.indexOf('\r', nStart); if (nEnd > 0) { sPort = (sBuffer.substring(nStart, nEnd)).trim(); Thread.sleep(5000); sRet = RegisterTheDevice(sIP, sPort, sBuffer.substring(nEnd + 1)); } } } } } catch (FileNotFoundException e) { sRet = sErrorPrefix + "Nothing to do"; } catch (IOException e) { sRet = sErrorPrefix + "Couldn't send info to " + sIP + ":" + sPort; } catch (InterruptedException e) { e.printStackTrace(); } return (sRet); }
From source file:com.codename1.impl.android.AndroidImplementation.java
public static String[] getPendingPush(String type, Context a) { InputStream i = null;//from w ww .ja v a2 s .c o m try { i = a.openFileInput("CN1$AndroidPendingNotifications"); if (i == null) { return null; } DataInputStream is = new DataInputStream(i); int count = is.readByte(); Vector v = new Vector<String>(); for (int iter = 0; iter < count; iter++) { boolean hasType = is.readBoolean(); String actualType = null; if (hasType) { actualType = is.readUTF(); } final String t; final String b; if ("99".equals(actualType)) { // This was a rich push Map<String, String> vals = splitQuery(is.readUTF()); t = vals.get("type"); b = vals.get("body"); //category = vals.get("category"); //image = vals.get("image"); } else { t = actualType; b = is.readUTF(); //category = null; //image = null; } long s = is.readLong(); if (t != null && ("3".equals(t) || "6".equals(t))) { String[] m = b.split(";"); v.add(m[0]); } else if (t != null && "4".equals(t)) { String[] m = b.split(";"); v.add(m[1]); } else if (t != null && "2".equals(t)) { continue; } else if (t != null && "101".equals(t)) { v.add(b.substring(b.indexOf(" ") + 1)); } else { v.add(b); } } String[] retVal = new String[v.size()]; for (int j = 0; j < retVal.length; j++) { retVal[j] = (String) v.get(j); } return retVal; } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (i != null) { i.close(); } } catch (IOException ex) { } } return null; }
From source file:com.codename1.impl.android.AndroidImplementation.java
public static void firePendingPushes(final PushCallback c, final Context a) { try {// w w w .j a v a 2s . c o m if (c != null) { InputStream i = a.openFileInput("CN1$AndroidPendingNotifications"); if (i == null) { return; } DataInputStream is = new DataInputStream(i); int count = is.readByte(); for (int iter = 0; iter < count; iter++) { boolean hasType = is.readBoolean(); String actualType = null; if (hasType) { actualType = is.readUTF(); } final String t; final String b; final String category; final String image; if ("99".equals(actualType)) { // This was a rich push Map<String, String> vals = splitQuery(is.readUTF()); t = vals.get("type"); b = vals.get("body"); category = vals.get("category"); image = vals.get("image"); } else { t = actualType; b = is.readUTF(); category = null; image = null; } long s = is.readLong(); Display.getInstance().callSerially(new Runnable() { @Override public void run() { Display.getInstance().setProperty("pendingPush", "true"); Display.getInstance().setProperty("pushType", t); initPushContent(b, image, t, category, a); if (t != null && ("3".equals(t) || "6".equals(t))) { String[] a = b.split(";"); c.push(a[0]); c.push(a[1]); } else if (t != null && ("101".equals(t))) { c.push(b.substring(b.indexOf(" ") + 1)); } else { c.push(b); } Display.getInstance().setProperty("pendingPush", null); } }); } a.deleteFile("CN1$AndroidPendingNotifications"); } } catch (IOException err) { } }
From source file:com.codename1.impl.android.AndroidImplementation.java
/** * Gets the service properties. Will read properties from file so that * they are available even if CN1 is not initialized. * @param a/*from w ww .j a v a 2 s .c o m*/ * @return */ public static Map<String, String> getServiceProperties(Context a) { if (serviceProperties == null) { InputStream i = null; try { serviceProperties = new HashMap<String, String>(); i = a.openFileInput("CN1$AndroidServiceProperties"); if (i == null) { return serviceProperties; } DataInputStream is = new DataInputStream(i); int count = is.readInt(); for (int idx = 0; idx < count; idx++) { String key = is.readUTF(); String value = is.readUTF(); serviceProperties.put(key, value); } } catch (IOException ex) { Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (i != null) i.close(); } catch (Throwable ex) { Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex); } } } return serviceProperties; }
From source file:com.codename1.impl.android.AndroidImplementation.java
public static void appendNotification(String type, String body, String image, String category, Context a) { try {/* w ww. j a v a2s. c o m*/ String[] fileList = a.fileList(); byte[] data = null; for (int iter = 0; iter < fileList.length; iter++) { if (fileList[iter].equals("CN1$AndroidPendingNotifications")) { InputStream is = a.openFileInput("CN1$AndroidPendingNotifications"); if (is != null) { data = readInputStream(is); sCleanup(a); break; } } } DataOutputStream os = new DataOutputStream(a.openFileOutput("CN1$AndroidPendingNotifications", 0)); if (data != null) { data[0]++; os.write(data); } else { os.writeByte(1); } String bodyType = type; if (image != null || category != null) { type = "99"; } if (type != null) { os.writeBoolean(true); os.writeUTF(type); } else { os.writeBoolean(false); } if ("99".equals(type)) { String msg = "body=" + java.net.URLEncoder.encode(body, "UTF-8") + "&type=" + java.net.URLEncoder.encode(bodyType, "UTF-8"); if (category != null) { msg += "&category=" + java.net.URLEncoder.encode(category, "UTF-8"); } if (image != null) { image += "&image=" + java.net.URLEncoder.encode(image, "UTF-8"); } os.writeUTF(msg); } else { os.writeUTF(body); } os.writeLong(System.currentTimeMillis()); } catch (IOException err) { err.printStackTrace(); } }
From source file:processing.core.PApplet.java
/** * Call createInput() without automatic gzip decompression. *//*from w ww . ja v a 2 s . c o m*/ public InputStream createInputRaw(String filename) { // Additional considerations for Android version: // http://developer.android.com/guide/topics/resources/resources-i18n.html InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function // System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.indexOf(":") != -1) { // at least smells like URL try { // Workaround for Android bug 6066 // http://code.google.com/p/android/issues/detail?id=6066 // http://code.google.com/p/processing/issues/detail?id=629 // URL url = new URL(filename); // stream = url.openStream(); // return stream; HttpGet httpRequest = null; httpRequest = new HttpGet(URI.create(filename)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); return entity.getContent(); // can't use BufferedHttpEntity because it may try to allocate a // byte // buffer of the size of the download, bad when DL is 25 MB... // [0200] // BufferedHttpEntity bufHttpEntity = new // BufferedHttpEntity(entity); // return bufHttpEntity.getContent(); } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for // 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); // System.err.println("Error downloading from URL " + filename); return null; // throw new RuntimeException("Error downloading from URL " + // filename); } } /* * // Moved this earlier than the getResourceAsStream() checks, because * // calling getResourceAsStream() on a directory lists its contents. * // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First * see if it's in a data folder. This may fail by throwing // a * SecurityException. If so, this whole block will be skipped. File file * = new File(dataPath(filename)); if (!file.exists()) { // next see if * it's just in the sketch folder file = new File(sketchPath, filename); * } if (file.isDirectory()) { return null; } if (file.exists()) { try { * // handle case sensitivity check String filePath = * file.getCanonicalPath(); String filenameActual = new * File(filePath).getName(); // make sure there isn't a subfolder * prepended to the name String filenameShort = new * File(filename).getName(); // if the actual filename is the same, but * capitalized // differently, warn the user. //if * (filenameActual.equalsIgnoreCase(filenameShort) && * //!filenameActual.equals(filenameShort)) { if * (!filenameActual.equals(filenameShort)) { throw new * RuntimeException("This file is named " + filenameActual + " not " + * filename + ". Rename the file " + "or change your code."); } } catch * (IOException e) { } } * * // if this file is ok, may as well just load it stream = new * FileInputStream(file); if (stream != null) return stream; * * // have to break these out because a general Exception might // catch * the RuntimeException being thrown above } catch (IOException ioe) { } * catch (SecurityException se) { } */ // Using getClassLoader() prevents Java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) /* * // this works, but requires files to be stored in the src folder * ClassLoader cl = getClass().getClassLoader(); stream = * cl.getResourceAsStream(filename); if (stream != null) { String cn = * stream.getClass().getName(); // this is an irritation of sun's java * plug-in, which will return // a non-null stream for an object that * doesn't exist. like all good // things, this is probably introduced * in java 1.5. awesome! // * http://dev.processing.org/bugs/show_bug.cgi?id=359 if * (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } * } */ // Try the assets folder AssetManager assets = this.getActivity().getAssets(); try { stream = assets.open(filename); if (stream != null) { return stream; } } catch (IOException e) { // ignore this and move on // e.printStackTrace(); } // Maybe this is an absolute path, didja ever think of that? File absFile = new File(filename); if (absFile.exists()) { try { stream = new FileInputStream(absFile); if (stream != null) { return stream; } } catch (FileNotFoundException fnfe) { // fnfe.printStackTrace(); } } // Maybe this is a file that was written by the sketch on another // occasion. File sketchFile = new File(sketchPath(filename)); if (sketchFile.exists()) { try { stream = new FileInputStream(sketchFile); if (stream != null) { return stream; } } catch (FileNotFoundException fnfe) { // fnfe.printStackTrace(); } } // Attempt to load the file more directly. Doesn't like paths. Context context = this.getActivity().getApplicationContext(); try { // MODE_PRIVATE is default, should we use something else? stream = context.openFileInput(filename); if (stream != null) { return stream; } } catch (FileNotFoundException e) { // ignore this and move on // e.printStackTrace(); } return null; }
From source file:com.processing.core.PApplet.java
/** * Call createInput() without automatic gzip decompression. *///from www. j a va2s . com public InputStream createInputRaw(String filename) { // Additional considerations for Android version: // http://developer.android.com/guide/topics/resources/resources-i18n.html InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.indexOf(":") != -1) { // at least smells like URL try { // Workaround for Android bug 6066 // http://code.google.com/p/android/issues/detail?id=6066 // http://code.google.com/p/processing/issues/detail?id=629 // URL url = new URL(filename); // stream = url.openStream(); // return stream; HttpGet httpRequest = null; httpRequest = new HttpGet(URI.create(filename)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); return entity.getContent(); // can't use BufferedHttpEntity because it may try to allocate a byte // buffer of the size of the download, bad when DL is 25 MB... [0200] // BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); // return bufHttpEntity.getContent(); } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } /* // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = new File(sketchPath, filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } */ // Using getClassLoader() prevents Java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) /* // this works, but requires files to be stored in the src folder ClassLoader cl = getClass().getClassLoader(); stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } */ // Try the assets folder AssetManager assets = getAssets(); try { stream = assets.open(filename); if (stream != null) { return stream; } } catch (IOException e) { // ignore this and move on //e.printStackTrace(); } // Maybe this is an absolute path, didja ever think of that? File absFile = new File(filename); if (absFile.exists()) { try { stream = new FileInputStream(absFile); if (stream != null) { return stream; } } catch (FileNotFoundException fnfe) { //fnfe.printStackTrace(); } } // Maybe this is a file that was written by the sketch on another occasion. File sketchFile = new File(sketchPath(filename)); if (sketchFile.exists()) { try { stream = new FileInputStream(sketchFile); if (stream != null) { return stream; } } catch (FileNotFoundException fnfe) { //fnfe.printStackTrace(); } } // Attempt to load the file more directly. Doesn't like paths. Context context = getApplicationContext(); try { // MODE_PRIVATE is default, should we use something else? stream = context.openFileInput(filename); if (stream != null) { return stream; } } catch (FileNotFoundException e) { // ignore this and move on //e.printStackTrace(); } return null; }
From source file:com.codename1.impl.android.AndroidImplementation.java
/** * Retrieves the app's available push action categories from the XML file in which they * should have been installed on the first load. * @param context//from w w w .j av a 2s .c o m * @return * @throws IOException */ private static PushActionCategory[] getInstalledPushActionCategories(Context context) throws IOException { // NOTE: This method may be called from the PushReceiver when the app isn't running so we can't access // the main activity context, display properties, or any CN1 stuff. Just native android File categoriesFile = new File( context.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES); if (!categoriesFile.exists()) { return new PushActionCategory[0]; } javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder docBuilder; try { docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex); throw new IOException( "Faield to create document builder for creating notification categories XML document", ex); } org.w3c.dom.Document doc; try { doc = docBuilder.parse(context.openFileInput(FILE_NAME_NOTIFICATION_CATEGORIES)); } catch (SAXException ex) { Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex); throw new IOException("Failed to parse instaled push action categories", ex); } org.w3c.dom.Element root = doc.getDocumentElement(); java.util.List<PushActionCategory> out = new ArrayList<PushActionCategory>(); org.w3c.dom.NodeList l = root.getElementsByTagName("category"); int len = l.getLength(); for (int i = 0; i < len; i++) { org.w3c.dom.Element el = (org.w3c.dom.Element) l.item(i); java.util.List<PushAction> actions = new ArrayList<PushAction>(); org.w3c.dom.NodeList al = el.getElementsByTagName("action"); int alen = al.getLength(); for (int j = 0; j < alen; j++) { org.w3c.dom.Element actionEl = (org.w3c.dom.Element) al.item(j); String textInputPlaceholder = actionEl.hasAttribute("textInputPlaceholder") ? actionEl.getAttribute("textInputPlaceholder") : null; String textInputButtonText = actionEl.hasAttribute("textInputButtonText") ? actionEl.getAttribute("textInputButtonText") : null; PushAction action = new PushAction(actionEl.getAttribute("id"), actionEl.getAttribute("title"), actionEl.getAttribute("icon"), textInputPlaceholder, textInputButtonText); actions.add(action); } PushActionCategory cat = new PushActionCategory((String) el.getAttribute("id"), actions.toArray(new PushAction[actions.size()])); out.add(cat); } return out.toArray(new PushActionCategory[out.size()]); }