com.codename1.io.Storage Java Examples
The following examples show how to use
com.codename1.io.Storage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParseObjectTest.java From parse4cn1 with Apache License 2.0 | 6 votes |
private void testSimpleParseObjectSerialization() throws ParseException { System.out.println("============== testSimpleParseObjectSerialization()"); assertEqual(ExternalizableParseObject.getClassName(), "ExternalizableParseObject"); final ParseObject gameScore = ParseObject.create(classGameScore); gameScore.put("score", 1337); gameScore.put("rating", 4.5); gameScore.put("playerName", "Sean Plott"); gameScore.put("cheatMode", false); gameScore.save(); final ParseObject retrieved = serializeAndRetrieveParseObject(gameScore); compareParseObjects(gameScore, retrieved, null); // Make object dirty object gameScore.put("score", 1378); System.out.println("-------------- Serialization of dirty ParseObject should fail"); assertFalse(Storage.getInstance().writeObject(gameScore.getObjectId(), gameScore.asExternalizable()), "Serialization of dirty ParseObject should be disallowed"); gameScore.delete(); }
Example #2
Source File: Purchase.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Gets all of the receipts for this app. Note: You should periodically * reload the receipts from the server to make sure that the user * hasn't canceled a receipt or renewed one. * @return List of receipts for purchases this app. */ public final List<Receipt> getReceipts() { synchronized (RECEIPTS_KEY) { if (receipts == null) { if (Storage.getInstance().exists(RECEIPTS_KEY)) { Receipt.registerExternalizable(); try { receipts = (List<Receipt>)Storage.getInstance().readObject(RECEIPTS_KEY); } catch (Exception ex) { Log.p("Failed to load receipts from "+RECEIPTS_KEY); Log.e(ex); receipts = new ArrayList<Receipt>(); } } else { receipts = new ArrayList<Receipt>(); } } return receipts; } }
Example #3
Source File: Login.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
public static void login(final Form form) { if (firstLogin()) { Login logForm = new Login(form); logForm.show(); } else { //token exists no need to authenticate TOKEN = (String) Storage.getInstance().readObject("token"); FaceBookAccess.setToken(TOKEN); //in case token has expired re-authenticate FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { NetworkEvent ne = (NetworkEvent) evt; int code = ne.getResponseCode(); //token has expired if (code == 400) { signIn(form); } } }); } }
Example #4
Source File: CloudStorage.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Commit works synchronously and returns one of the return codes above to indicate * the status. * @return status code from the constants in this class */ public synchronized int commit() { if(storageQueue.size() > 0) { if(CloudPersona.getCurrentPersona().getToken() == null) { CloudPersona.createAnonymous(); } StorageRequest req = new StorageRequest(); req.setContentType("multipart/form-data"); req.setUrl(SERVER_URL + "/objStoreCommit"); req.setPost(true); NetworkManager.getInstance().addToQueueAndWait(req); int i = req.getReturnCode(); if(i == RETURN_CODE_SUCCESS) { storageQueue.clear(); Storage.getInstance().deleteStorageFile("CN1StorageQueue"); } return i; } return RETURN_CODE_EMPTY_QUEUE; }
Example #5
Source File: Purchase.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Removes a receipt from pending purchases. * @param transactionId * @return */ private Receipt removePendingPurchase(String transactionId) { synchronized(PENDING_PURCHASE_KEY) { Storage s = Storage.getInstance(); List<Receipt> pendingPurchases = getPendingPurchases(); Receipt found = null; for (Receipt r : pendingPurchases) { if (r.getTransactionId() != null && r.getTransactionId().equals(transactionId)) { found = r; break; } } if (found != null) { pendingPurchases.remove(found); s.writeObject(PENDING_PURCHASE_KEY, pendingPurchases); return found; } else { return null; } } }
Example #6
Source File: StateMachine.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
@Override protected void onMain_AddTaskButtonAction(Component c, ActionEvent event) { TextField title = findTitleField(c.getParent()); TextField description = findDescriptionField(c.getParent()); Hashtable<String, String> entry = new Hashtable<String, String>(); entry.put("title", title.getText()); entry.put("description", description.getText()); if(photo != null) { entry.put("photo", photo); } title.setText(""); description.setText(""); findCaptureButton(c.getParent()).setIcon(null); MultiButton mb = createEntry(entry); photo = null; todos.add(entry); Storage.getInstance().writeObject("todos", todos); findTabs1(c.getParent()).setSelectedIndex(0); Container tasksContainer = findTasksContainer(c.getParent()); tasksContainer.addComponent(mb); tasksContainer.animateLayout(500); }
Example #7
Source File: StateMachine.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
@Override protected void beforeMain(Form f) { Image icon = fetchResourceFile().getImage("shai_100x125.jpg"); imageWidth = icon.getWidth(); imageHeight = icon.getHeight(); Container tasksContainer = findTasksContainer(f); tasksContainer.removeAll(); todos = (Vector<Hashtable<String,String>>)Storage.getInstance().readObject("todos"); if(todos == null) { todos = new Vector<Hashtable<String,String>>(); return; } for(Hashtable<String,String> entry : todos) { MultiButton mb = createEntry(entry); tasksContainer.addComponent(mb); } }
Example #8
Source File: FaceBookAccess.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Gets the picture of the given facebook object id * * @param id the object id to query * @param label place the image on the given label as an icon * @param toScale scale the image to the given dimension * @param tempStorage if true place the image in a temp storage */ public void getPicture(String id, final Label label, Dimension toScale, boolean tempStorage) throws IOException { checkAuthentication(); FacebookRESTService fb = new FacebookRESTService(token, id, FacebookRESTService.PICTURE, false); if(toScale != null){ fb.addArgument("width", "" + toScale.getWidth()); fb.addArgument("height", "" + toScale.getHeight()); }else{ fb.addArgument("type", "small"); } String cacheKey = id; //check if this image is a temporarey resource and it is not saved //already has a permanent image if (tempStorage && !Storage.getInstance().exists(id)) { cacheKey = TEMP_STORAGE + id; } ImageDownloadService.createImageToStorage(fb.requestURL(), label, cacheKey, toScale); }
Example #9
Source File: PhotoShare.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
public Image getItemAt(final int index) { if(images[index] == null) { images[index] = placeholder; Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() { public void actionPerformed(ActionEvent evt) { try { images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index])); listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED); } catch(IOException err) { err.printStackTrace(); } } }); } return images[index]; }
Example #10
Source File: SocialChat.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
@Override public void push(String value) { // its a JSON message, otherwise its a notice to the user if(value.startsWith("{") || value.startsWith("[")) { try { JSONObject obj = new JSONObject(value); // this is still early since we probably didn't login yet so add the messages to the list of pending messages java.util.List<Message> pendingMessages = (java.util.List<Message>)Storage.getInstance().readObject("pendingMessages"); if(pendingMessages == null) { pendingMessages = new ArrayList<>(); } Message m = new Message(obj); pendingMessages.add(m); Storage.getInstance().writeObject("pendingMessages", pendingMessages); addMessage(m); } catch(JSONException err) { err.printStackTrace(); } } }
Example #11
Source File: FaceBookAccess.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Gets the picture of the given facebook object id * * @param id the object id to query * @param callback the callback that should be updated when the data arrives * @param toScale picture dimension or null * @param tempStorage if true place the image in a temp storage */ public void getPicture(String id, final ActionListener callback, Dimension toScale, boolean tempStorage) throws IOException { checkAuthentication(); FacebookRESTService fb = new FacebookRESTService(token, id, FacebookRESTService.PICTURE, false); if(toScale != null){ fb.addArgument("width", "" + toScale.getWidth()); fb.addArgument("height", "" + toScale.getHeight()); }else{ fb.addArgument("type", "small"); } String cacheKey = id; //check if this image is a temporarey resource and it is not saved //already has a permanent image if (tempStorage && !Storage.getInstance().exists(id)) { cacheKey = TEMP_STORAGE + id; } ImageDownloadService.createImageToStorage(fb.requestURL(), callback, cacheKey); }
Example #12
Source File: StorageImage.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * {@inheritDoc} */ public byte[] getImageData() { if(data != null) { return data; } if(weak != null) { byte[] d = (byte[])Display.getInstance().extractHardRef(weak); if(d != null) { return d; } } byte[] imageData = (byte[])Storage.getInstance().readObject(fileName); if(keep) { data = imageData; } else { weak = Display.getInstance().createSoftWeakRef(imageData); } return imageData; }
Example #13
Source File: Logger.java From parse4cn1 with Apache License 2.0 | 6 votes |
/** * Retrieves the entire log content as a single long string to be used by * the application in any way it deems fit. * <p> * Note that if any buffered log is present (cf. {@link #logBuffered(java.lang.String)}), * it will be appended to the end of the string returned by this method. * * @return The log data if successfully retrieved or null. * @throws com.parse4cn1.ParseException if anything goes wrong. */ public String getLogContent() throws ParseException { String text = null; try { Reader r = new InputStreamReader(Storage.getInstance().createInputStream(LOG_FILENAME)); char[] buffer = new char[1024]; int size = r.read(buffer); while (size > -1) { text += new String(buffer, 0, size); size = r.read(buffer); } r.close(); } catch (Exception ex) { throw new ParseException("Retrieving log file contents failed:" + ex.getMessage(), ex); } if (bufferedLog != null) { text += "\n\n=================" + "\nBuffered logging:" + "\n=================\n" + bufferedLog; } return text; }
Example #14
Source File: PropertyIndex.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Loads JSON containing a list of property objects of this type * @param name the name of the storage * @return list of property objects matching this type */ public <X extends PropertyBusinessObject> List<X> loadJSONList(String name) { try { InputStream is = Storage.getInstance().createInputStream(name); JSONParser jp = new JSONParser(); JSONParser.setUseBoolean(true); JSONParser.setUseLongs(true); List<X> response = new ArrayList<X>(); Map<String, Object> result = jp.parseJSON(new InputStreamReader(is, "UTF-8")); List<Map> entries = (List<Map>)result.get("root"); for(Map m : entries) { X pb = (X)newInstance(); pb.getPropertyIndex().populateFromMap(m, parent.getClass()); response.add(pb); } return response; } catch(IOException err) { Log.e(err); throw new RuntimeException(err.toString()); } }
Example #15
Source File: FaceBookAccess.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
/** * Gets the picture of the given facebook object id and stores it in the given List in the offset index * * This assumes the GenericListCellRenderer style of * list which relies on a hashtable based model approach. * * @param id the object id to query * @param targetList the list that should be updated when the data arrives * @param targetOffset the offset within the list to insert the image * @param targetKey the key for the hashtable in the target offset * @param toScale the scale of the image to put in the List or null * @param tempStorage if true place the image in a temp storage */ public void getPicture(String id, final Component targetList, final int targetOffset, final String targetKey, Dimension toScale, boolean tempStorage) throws IOException { checkAuthentication(); FacebookRESTService fb = new FacebookRESTService(token, id, FacebookRESTService.PICTURE, false); if(toScale != null){ fb.addArgument("width", "" + toScale.getWidth()); fb.addArgument("height", "" + toScale.getHeight()); }else{ fb.addArgument("type", "small"); } String cacheKey = id; //check if this image is a temporarey resource and it is not saved //already has a permanent image if (tempStorage && !Storage.getInstance().exists(id)) { cacheKey = TEMP_STORAGE + id; } ImageDownloadService.createImageToStorage(fb.requestURL(), targetList, targetOffset, targetKey, cacheKey, toScale, ConnectionRequest.PRIORITY_LOW); }
Example #16
Source File: PropertyCross.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
/** * Toggles the favorite state and saves it to storage * @param currentListing the listing to toggle the state of * @param fav the new favorite state */ void setFavorite(Map<String, Object> currentListing, boolean fav) { if(fav) { favoritesList.add(currentListing); Storage.getInstance().writeObject("favoritesList", favoritesList); } else { String guid = (String)currentListing.get("guid"); for(Map<String, Object> c : favoritesList) { if(c.get("guid").equals(guid)) { favoritesList.remove(c); Storage.getInstance().writeObject("favoritesList", favoritesList); return; } } } }
Example #17
Source File: SocialChat.java From codenameone-demos with GNU General Public License v2.0 | 6 votes |
private void showPendingMessages(Form f) { if(Storage.getInstance().exists("pendingMessages")) { java.util.List<Message> pendingMessages = (java.util.List<Message>)Storage.getInstance().readObject("pendingMessages"); Message m = pendingMessages.get(0); pendingMessages.remove(0); respond(m); if(pendingMessages.size() == 0) { Storage.getInstance().deleteStorageFile("pendingMessages"); } else { Storage.getInstance().writeObject("pendingMessages", pendingMessages); UITimer uit = new UITimer(() -> { showPendingMessages(f); }); uit.schedule(3500, false, f); } } }
Example #18
Source File: PropertyIndex.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * Loads JSON for the object from storage with the given name * @param name the name of the storage */ public void loadJSON(String name) { try { InputStream is = Storage.getInstance().createInputStream(name); JSONParser jp = new JSONParser(); JSONParser.setUseBoolean(true); JSONParser.setUseLongs(true); populateFromMap(jp.parseJSON(new InputStreamReader(is, "UTF-8")), parent.getClass()); } catch(IOException err) { Log.e(err); throw new RuntimeException(err.toString()); } }
Example #19
Source File: CloudStorage.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * Adds the given object to the save queue, the operation will only take place once committed * @param object the object to save into the cloud, new objects are inserted. existing * objects are updated */ public synchronized void save(CloudObject object) { if(storageQueue.contains(object)) { storageQueue.remove(object); } storageQueue.addElement(object); Storage.getInstance().writeObject("CN1StorageQueue", storageQueue); object.setStatus(CloudObject.STATUS_COMMIT_IN_PROGRESS); }
Example #20
Source File: PropertyIndex.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * Writes the JSON string to storage, it's a shortcut for writing/generating the JSON * @param name the name of the storage file * @param objs a list of business objects */ public static void storeJSONList(String name, List<? extends PropertyBusinessObject> objs) { try { OutputStream os = Storage.getInstance().createOutputStream(name); os.write(toJSONList(objs).getBytes()); os.close(); } catch(IOException err) { Log.e(err); throw new RuntimeException(err.toString()); } }
Example #21
Source File: CloudStorage.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
protected void postResponse() { if(response != null) { if(returnCode == RETURN_CODE_SUCCESS) { storageQueue.clear(); Storage.getInstance().deleteStorageFile("CN1StorageQueue"); } response.onSuccess(new Integer(returnCode)); } }
Example #22
Source File: URLImage.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private void loadImageFromStorageURLToStorage(final String targetKey) { Display.getInstance().scheduleBackgroundTask(new Runnable() { public void run() { try { if (!Objects.equals(url, targetKey)) { InputStream input = Storage.getInstance().createInputStream(url); OutputStream output = Storage.getInstance().createOutputStream(targetKey); Util.copy(input, output); } CN.callSerially(new Runnable() { public void run() { try { Image value = Image.createImage(Storage.getInstance().createInputStream(targetKey)); DownloadCompleted onComplete = new DownloadCompleted(); onComplete.setSourceImage(value); onComplete.actionPerformed(new ActionEvent(value)); } catch (Exception ex) { if(exceptionHandler != null) { exceptionHandler.onError(URLImage.this, ex); } else { throw new RuntimeException(ex.toString()); } } } }); } catch (Exception t) { if(exceptionHandler != null) { exceptionHandler.onError(URLImage.this, t); } else { throw new RuntimeException(t.toString()); } } } }); }
Example #23
Source File: PropertyIndex.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * Writes the JSON string to storage, it's a shortcut for writing/generating the JSON * @param name the name of the storage file */ public void storeJSON(String name) { try { OutputStream os = Storage.getInstance().createOutputStream(name); os.write(toJSON().getBytes("UTF-8")); os.close(); } catch(IOException err) { Log.e(err); throw new RuntimeException(err.toString()); } }
Example #24
Source File: GeofenceManager.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private synchronized void saveFences() { if (fences != null) { Map<String,Map> out = new HashMap<String,Map>(); for (Map.Entry<String,Geofence> f : fences.entrySet()) { out.put(f.getValue().getId(), toMap(f.getValue())); } Storage.getInstance().writeObject(STORAGE_KEY, out); } }
Example #25
Source File: GeofenceManager.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private synchronized Map<String, Geofence> getActiveFences(boolean reload) { if (reload || activeFences == null) { activeFences = new HashMap<String,Geofence>(); Map<String,Map> tmp = (Map)Storage.getInstance().readObject(ACTIVE_FENCES_KEY); if (tmp != null) { for (Map.Entry<String,Map> e : tmp.entrySet()) { activeFences.put(e.getKey(), fromMap(e.getValue())); } } } return activeFences; }
Example #26
Source File: GeofenceManager.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private synchronized void saveActiveFences() { if (activeFences != null) { Map<String,Map> out = new HashMap<String,Map>(); for (Map.Entry<String,Geofence> f : activeFences.entrySet()) { out.put(f.getValue().getId(), toMap(f.getValue())); } Storage.getInstance().writeObject(ACTIVE_FENCES_KEY, out); } }
Example #27
Source File: GeofenceManager.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private synchronized Map<String, Geofence> getFences(boolean reload) { if (reload || fences == null) { fences = new HashMap<String,Geofence>(); Map<String,Map> tmp = (Map)Storage.getInstance().readObject(STORAGE_KEY); if (tmp != null) { for (Map.Entry<String,Map> e : tmp.entrySet()) { fences.put(e.getKey(), fromMap(e.getValue())); } } } return fences; }
Example #28
Source File: GeofenceManager.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
private synchronized List<String> getActiveKeys(boolean reload) { if (reload || activeKeys == null) { activeKeys = (List<String>)Storage.getInstance().readObject(CURRENT_ACTIVE_KEY); if (activeKeys == null) { activeKeys = new ArrayList<String>(); } } return activeKeys; }
Example #29
Source File: TestUtils.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * The screenshot test takes a screenshot of the screen and compares it to * a prior screenshot, if both are 100% identical the test passes. If not * the test fails.<br> * If this is the first time the test is run then the screenshot is taken * and saved under the given name in the devices storage. The test passes * for this case but a warning is printed to the console. The name will have * .png appended to it so it will be identified.<br> * This test will only work on devices that support the ImageIO API with PNG * file format. * * @param screenshotName the name to use for the storage, must be unique! * @return true if the screenshots are identical or no prior screenshot exists * or if the test can't be run on this device. False if a screenshot exists and * it isn't 100% identical. */ public static boolean screenshotTest(String screenshotName) { if(verbose) { log("screenshotTest(" + screenshotName + ")"); } try { ImageIO io = ImageIO.getImageIO(); if(io == null || !io.isFormatSupported(ImageIO.FORMAT_PNG)) { log("screenshot test skipped due to no image IO support for PNG format"); return true; } Image mute = Image.createImage(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayHeight()); Display.getInstance().getCurrent().paintComponent(mute.getGraphics(), true); screenshotName = screenshotName + ".png"; if(Storage.getInstance().exists(screenshotName)) { int[] rgba = mute.getRGBCached(); Image orig = Image.createImage(Storage.getInstance().createInputStream(screenshotName)); int[] origRgba = orig.getRGBCached(); orig = null; for(int iter = 0 ; iter < rgba.length ; iter++) { if(rgba[iter] != origRgba[iter]) { log("screenshots do not match at offset " + iter + " saving additional image under " + screenshotName + ".fail"); io.save(mute, Storage.getInstance().createOutputStream(screenshotName + ".fail"), ImageIO.FORMAT_PNG, 1); return false; } } } else { io.save(mute, Storage.getInstance().createOutputStream(screenshotName), ImageIO.FORMAT_PNG, 1); } return true; } catch(IOException err) { log(err); return false; } }
Example #30
Source File: StorageImageAsync.java From CodenameOne with GNU General Public License v2.0 | 5 votes |
/** * {@inheritDoc} */ public byte[] getImageData() { if(imageData != null) { return imageData; } synchronized(LOCK) { if(queued) { return null; } queued = true; Display.getInstance().scheduleBackgroundTask(new Runnable() { public void run() { InputStream i = null; try { final byte[] imageDataLocal = (byte[])Storage.getInstance().readObject(fileName); // we need to change the image on the EDT to avoid potential race conditions Display.getInstance().callSerially(new Runnable() { public void run() { imageData = imageDataLocal; resetCache(); changePending = true; imageCreated = false; } }); } catch (Throwable ex) { Log.e(ex); } finally { queued = false; Util.cleanup(i); } } }); } return null; }