In PlayN, how do I use the Storage interface to persist data? - playn

I'm looking for a code example that demonstrates practical real-world usage of the Storage interface. I'm especially interested in HTML5 implementation. I've just started working on my own proof-of-concept, so I'll post that if no better answers arrive before then.
The Storage interface is introduced in this Google presentation here:
http://playn-2011.appspot.com/

Here's some code that demonstrates the use of the storage interface together with PlayN's JSON interface:
private void loadStoredData() {
// storage parameters
String storageKey = "jsonData";
Json.Object jsonData = PlayN.json().createObject();
// to reset storage, uncomment this line
//PlayN.storage().removeItem(storageKey);
// attempt to load stored data
String jsonString = PlayN.storage().getItem(storageKey);
// if not loaded, create stored data
if ( jsonString == null ) {
DemoApi.log("stored data not found");
jsonData.put("firstWrite", new Date().toString());
// else display data
} else {
jsonData = PlayN.json().parse(jsonString);
DemoApi.log("stored data loaded");
DemoApi.log("data first written at " + jsonData.getString("firstWrite"));
DemoApi.log("data last read at " + jsonData.getString("lastRead"));
DemoApi.log("data last written at " + jsonData.getString("lastWrite"));
}
// update last read
jsonData.put("lastRead", new Date().toString());
// write data (this works in Java -- not in HTML)
// see https://stackoverflow.com/q/10425877/1093087
/*
Json.Writer jsonWriter = PlayN.json().newWriter();
jsonWriter.object(jsonData).done();
jsonString = jsonWriter.write();
*/
// alternative write routine
Json.Writer jsonWriter = PlayN.json().newWriter();
jsonWriter.object();
for ( String key : jsonData.keys() ) {
jsonWriter.value(key, jsonData.getString(key));
}
jsonWriter.end();
jsonString = jsonWriter.write();
// store data as json
PlayN.storage().setItem(storageKey, jsonString);
// confirm
if ( PlayN.storage().isPersisted() ) {
DemoApi.log("data successfully persisted");
} else {
DemoApi.log("failed to persist data");
}
}
There's one little hitch with the Json.Writer that seems a bit buggy that I document in this question here: In the HTML version of PlayN, why does the following JSON-handling code throw an exception?

Related

Haxe - SQLLite Crashing in Android target

i want to use use Sqllite datbase in my Android Game i am developing with Haxe - OpenFl but the app keep crashing when i am trying to query the database. If this is not possible or have any other ways to deal with data in Android kindly let me know as the json and shared objects are not going to work with in my scenario.
i posted this question in the OpenFl community too - but i think it is more related to Haxe then OpenFL.
OpenFl Community Post
What i am doing :
Making a database using DB Browser and saving it to the assets/data/db/data.db
then when app starts i am making a copy of it to the lime.system.System.applicationStorageDirectory
it creates the file in the applicationStorageDirectory
Then i try to connect to the newly created db file and it just connects but right after connecting to it, try to get the name of the db it is connected to
trace("Connected to database " +_conn.dbName ); and it is not showing anything in the trace except the text connected to database.
Ignoring the name i tried to query the Database and it just closes my app without any error or anything i get to know what goes wrong.
My Project.xml
<android target-sdk-version="26" install-location="preferExternal" if="android" />
<android permission="android.permission.WRITE_EXTERNAL_STORAGE"/>
<android permission="android.permission.WRITE_INTERNAL_STORAGE"/>
<haxelib name="openfl" />
<haxelib name="hxcpp" />
<assets path="assets/data/db" rename="db" />
DBClass
package;
import haxe.io.Bytes;
import lime.Assets;
import openfl.system.System;
import sys.FileSystem;
import sys.db.Connection;
import sys.db.Sqlite;
import sys.io.File;
#if android
// Make SQLite work on android by statically compiling the library
import hxcpp.StaticSqlite;
#end
/**
* ...
* #author Sim
*/
class DBManager
{
private var CLONE:String = "db/asset_database.db";
private var NEW:String = "new_db.db";
private var _conn:Connection = null;
public function new()
{
}
public function openDatabase():Void
{
trace("CREATING FILE");
trace("targetPath: " +lime.system.System.applicationStorageDirectory);
//trace("targetPath: " +lime.system.System.applicationDirectory); //Crashing the app
trace("targetPath: " +lime.system.System.documentsDirectory);
trace("targetPath: " +lime.system.System.desktopDirectory);
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
trace("targetPath " + targetPath);
trace("FileSystem.exists(targetPath) " + FileSystem.exists(targetPath));
//Debugging
/*var bytes:Bytes = Assets.getBytes(CLONE);
trace("bytes are here "+bytes);
var content:String = bytes.toString();
trace("content "+content);
File.saveContent(targetPath, content);
trace("Saved");*/
//uncomment when done with errors
/*if (FileSystem.exists(targetPath) == false)
{
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
}*/
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
trace("Saved");
try
{
_conn = Sqlite.open(targetPath+NEW);
}
catch (e:Dynamic)
{
trace("Connection failed with error: "+e);
}
if (_conn != null)
{
trace("Connected to database " +_conn.dbName );
//not getting any database name trying to query
// and KaBoom app gone :D XD
var result = _conn.request("SELECT * FROM TEST");
trace("Query Result "+result.results());
//if i comment then it will go and close the connection too
//without breaking anything O_O
_conn.close();
}
}
}
I took a nap and got the fix in my dreams: :D
The problem is here
_conn = Sqlite.open(targetPath+NEW);
Fix:
_conn = Sqlite.open(targetPath);
Because database name is already in the path :P
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
That’s why always sleep for 8 hours otherwise will end up like me

How to post Special character tweet using asp.net API?

I m using Given below code to post the tweet on twitter. But when we upload it on the server then special character (!,:,$ etc) tweets not published on twitter. this code is working fine in the local system
string key = "";
string secret = "";
string token="";
string tokenSecret="";
try
{
string localFilename = HttpContext.Current.Server.MapPath("../images/").ToString();
using (WebClient client = new WebClient())
{
client.DownloadFile(imagePath, localFilename);
}
var service = new TweetSharp.TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
// Tweet wtih image
if (imagePath.Length > 0)
{
using (var stream = new FileStream(localFilename, FileMode.Open))
{
var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = message,
Images = new Dictionary<string, Stream> { { "name", stream } }
});
}
}
else // just message
{
var result = service.SendTweet(new SendTweetOptions
{
Status = HttpUtility.UrlEncode(message)
});
}
}
catch (Exception ex)
{
throw ex;
}
The statuses/update_with_media API endpoint is actually deprecated by Twitter and shouldn't be used (https://dev.twitter.com/rest/reference/post/statuses/update_with_media).
TweetSharp also has some issues with using this method when the tweet contains both a 'special character' AND an image (works fine with either, but not both). I don't know why and I haven't been able to fix it, it's something to do with the OAuth signature I'm pretty sure.
As a solution I suggest you use TweetMoaSharp (a fork of TweetSharp). It has been updated to support the new Twitter API's for handling media in tweets, and it will work in this situation if you use the new stuff.
Basically you upload each media item using a new UploadMedia method, and that will return you a 'media id'. You then use the normal 'SendTweet' method and provide a list of the media ids to it along with the other status details. Twitter will attach the media to the tweet when it is posted, and it will work when there are both special characters and images.
In addition to TweetMoaSharp you can use Tweetinvi with the following code:
var binary = File.ReadAllBytes(#"C:\videos\image.jpg");
var media = Upload.UploadMedia(binary);
var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
Medias = {media}
});

Read private dicom TAGS from various vendors - dcm4che2

I am wondering on which is the most efficient way to setup & build a JAVA application (using dcm4che2 toolkit) for being able to indentify and parse in a proper way DICOMs from various vendors.
For example at the moment i need to parse private tags from MRIs manufactured by Siemens, GE and Philips. I can see that even for the same vendor there are differences in the VR of the same private tags.
At the moment i am trying to parse these private TAGs by using code as the one listed below:
//get acquisitionMatrixX of a DICOM file
public String getAcquisitionMatrixX(File file) throws IOException {
String acquisitionMatrixX =null;
String manufacturer = null;
CheckIfIsDicom checkFile = new CheckIfIsDicom();
if(checkFile.checkIfDicomObjectFileB(file)) {
try {
DicomObject dcmObj4;
DicomInputStream din4 = null;
din4 = new DicomInputStream(file);
dcmObj4 = din4.readDicomObject();
manufacturer = dcmObj4.getString(Tag.Manufacturer);
if(manufacturer.contains("GE")) {
acquisitionMatrixX = dcmObj4.getString(0X00181310, VR.US);
log.info("GE machine |acquisitionMatrixX| --------- Value for tag: " + acquisitionMatrixX);
} else if (manufacturer.contains("SIEMENS")) {
//IN CASE OF some models VR.SH & UN
acquisitionMatrixX = dcmObj4.getString(0X0051100b, VR.LO);
log.info("SIEMENS machine |acquisitionMatrixX| --------- Value for tag: " + acquisitionMatrixX);
} else if (manufacturer.toLowerCase().contains("PHILIPS".toLowerCase())) {
acquisitionMatrixX = dcmObj4.getString(0X00189058, VR.US);
log.info("PHILIPS machine |acquisitionMatrixX| --------- Value for tag: " + acquisitionMatrixX);
} else {
acquisitionMatrixX = "";
}
din4.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if("".equals(acquisitionMatrixX) || acquisitionMatrixX==null) {
acquisitionMatrixX="-100000";
} else {
}
}
} else {
log.info("### IS NOT DICOM! ####");
log.info("Selected file is not a DICOM Object");
}
return acquisitionMatrixX;
}
However i do not think that such a way of parsing DICOM tags from different vendors is the most efficient in terms of consistency and maintenance of code/logic!
For example in many cases there is a different VR among different models of the same vendor.
Does anybody has developed an application with such a requirement? Are there any other ways to try and automate this process (e.g. by using data dictionaries per vendor/model?)
Anybody has some rough propositions or guideliness on that?
Thanks!
If you've added the private tags to your dictionary (see http://www.dcm4che.org/confluence/display/d2/Adding+private+tags+to+the+dictionary), you should be able to do something like the following to get the acquisition matrix:
short[] acq = dcmObj4.getShorts( Tag.AcquisitionMatrix, null );
if( null == acq ) {
// Try Siemens Private Attribute
int tagTest = dcmObj4.resolveTag( PrivateTag.SiemensAcquistionMatrix, dcmObj4.getPrivateCreator( PrivateTag.SiemensAcquistionMatrix) );
if( tagTest == PrivateTag.SiemensAcquisitionMatrix ) {
acq = dcmObj4.getShorts( PrivateTag.SiemensAcquistionMatrix, null );
break;
}
// Try Philips Private Attribute
:
}
return acq;
Above, I've assumed a PrivateTag class that holds the appropriate attribute values. Also, check your tags - does Philips really keep the x value of the acquisition matrix in the DICOM attribute MR Acquisition Frequency Encoding Steps?

Application Cache and Slow Process

I want to create an application wide feed on my ASP.net 3.5 web site using the application cache. The data that I am using to populate the cache is slow to obtain, maybe up to 10 seconds (from a remote server's data feed). My question/confusion is, what is the best way to structure the cache management.
private const string CacheKey = "MyCachedString";
private static string lockString = "";
public string GetCachedString()
{
string data = (string)Cache[CacheKey];
string newData = "";
if (data == null)
{
// A - Should this method call go here?
newData = SlowResourceMethod();
lock (lockString)
{
data = (string)Cache[CacheKey];
if (data != null)
{
return data;
}
// B - Or here, within the lock?
newData = SlowResourceMethod();
Cache[CacheKey] = data = newData;
}
}
return data;
}
The actual method would be presented by and HttpHandler (.ashx).
If I collect the data at point 'A', I keep the lock time short, but might end up calling the external resource many times (from web pages all trying to reference the feed). If I put it at point 'B', the lock time will be long, which I am assuming is a bad thing.
What is the best approach, or is there a better pattern that I could use?
Any advice would be appreciated.
I add the comments on the code.
private const string CacheKey = "MyCachedString";
private static readonly object syncLock = new object();
public string GetCachedString()
{
string data = (string)Cache[CacheKey];
string newData = "";
// start to check if you have it on cache
if (data == null)
{
// A - Should this method call go here?
// absolut not here
// newData = SlowResourceMethod();
// we are now here and wait for someone else to make it or not
lock (syncLock)
{
// now lets see if some one else make it...
data = (string)Cache[CacheKey];
// we have it, send it
if (data != null)
{
return data;
}
// not have it, now is the time to look for it.
// B - Or here, within the lock?
newData = SlowResourceMethod();
// set it on cache
Cache[CacheKey] = data = newData;
}
}
return data;
}
Better for me is to use mutex and lock depended on the name CacheKey and not lock all resource and the non relative one. With mutex one basic simple example will be:
private const string CacheKey = "MyCachedString";
public string GetCachedString()
{
string data = (string)Cache[CacheKey];
string newData = "";
// start to check if you have it on cache
if (data == null)
{
// lock it base on resource key
// (note that not all chars are valid for name)
var mut = new Mutex(true, CacheKey);
try
{
// Wait until it is safe to enter.
// but also add 30 seconds max
mut.WaitOne(30000);
// now lets see if some one else make it...
data = (string)Cache[CacheKey];
// we have it, send it
if (data != null)
{
return data;
}
// not have it, now is the time to look for it.
// B - Or here, within the lock?
newData = SlowResourceMethod();
// set it on cache
Cache[CacheKey] = data = newData;
}
finally
{
// Release the Mutex.
mut.ReleaseMutex();
}
}
return data;
}
You can also read
Image caching issue by using files in ASP.NET

how can we store a html page into sqlite in blackberry on memory card / phone memory?

Below code specifies that we we can make http connection in blackberry and how to store html page as a string?
I am doing this but I am able to get that http request but when I get response i.e http_ok it is not correct so that I can save text oh html as a string and I can further store that into sqlite.
LabelField title = new LabelField("SQLite Create Database Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Creating a database."));
argURL="https://www.google.com:80";
try {
connDesc = connFact.getConnection(argURL);
if (connDesc != null) {
httpConn = (HttpConnection) connDesc.getConnection();
// //Send Data on this connection
// httpConn.setRequestMethod(HttpConnection.GET);
// //Server Response
StringBuffer strBuffer = new StringBuffer();
inStream = httpConn.openInputStream();
int chr;
int retResponseCode = httpConn.getResponseCode();
if (retResponseCode == HttpConnection.HTTP_OK) {
if (inStream != null) {
while ((chr = inStream.read()) != -1) {
strBuffer.append((char) chr);
}
serverResponceStr = strBuffer.toString();
// appLe.alertForms.get_userWaitAlertForm().append("\n"+serverResponceStr);
//returnCode = gprsConstants.retCodeSuccess;
}
} else {
//returnCode = gprsConstants.retCodeNOK;
}
}
} catch (Exception excp) {
//returnCode = gprsConstants.retCodeDisconn;
excp.printStackTrace();
} `enter code here`
The code does not perform any database functionality, however I tested and it does successfully perform an HttpRequest to an external URL. The data that comes back is based on the response of the server you are making the request to.
The code I used can be found here:
http://snipt.org/vrl7
The only modifications is to keep a running summary of various events, and the response is displayed in the RichTextField. Basically, this looks to be working as intended, and the resulting String should be able to be saved however you see fit; though you may need to be cautious of encoding when saving to a database so that special characters are not lost or misinterpreted.

Resources