Tired of Jackson are you?
Do you want to serialize a POJO and not have to add all those annotations?
Just want to try a different way to deal with Json?
The I have an answer for you: Google Gson.
Gson is the Google library to deal with JSON and serialization, but in a easier way.
For starters you don't need to use annotations for the properties or the methods, it uses (out of the box) the POJO convention and introspection to serialize the class.
So for example if you just want to serialize some Java class you have you'll have to do the following:
Gson gson = new GsonBuilder().create();
gson.toJson(anObject);
And to de-serialize it you'll do:
Gson gson = new GsonBuilder().create();
gson.fromJson(aJsonString, anObject.getClass());
Now one thing I just keep forgetting how to do (hence the name of the blog) is how to deserialize a plain old collections let say a List of Strings, and here is how:
import java.lang.reflect.Type;
Type type = new TypeToken<List<String>>() { }.getType();
List<String> aList = new Gson().fromJson(jsonData, type);
As you can see it is quite simple to use, and of course this is just a really really really small port of what you can do with it, but it was a nice excuse for me to post how to deserialize a collection :P.
For more information just check the Gson site here :
https://sites.google.com/site/gson/gson-user-guide
Any way I hope you can use it.
Haven't you always find your self googling the same old thing you used to do always when coding? Well that's what ForgettableDev is for: a compound of really stupid stuff that we always forget HOW TO DO and it takes hours to find.
martes, 16 de abril de 2013
Dealing with GZIP Content
So .... Long time no see eh?
Oh well there are many reasons for that but truth is "you don't care about that".
Let's jump then into this post topic, which is ZIPED content.
As you may or may not know web servers can send you the content you are requesting in a compress way. Main reason for this is, of course, cause you save bandwidth.
Problem being, you have to deal with that content.
As it turns out you usually come across this when you are creating some sort of HTTP client to consume something and when you try to print the data you can no read it (this is what happened to me).
Easiest way to know for sure that the server is doing this is, checking the following HTTP header:
Content-Encoding: gzip
This tells you that the "content" has been "gziped", quite obvious rigtht?
Now lets talk about code, how do I deal with this.
Well if you are a smart chap and you are using Jersey Client, this is how:
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
List<ClientFilter> clientFilters = new ArrayList<ClientFilter>();
clientFilters.add(new GZIPContentEncodingFilter(false));
if (clientFilters != null) {
for (ClientFilter clientFilter : clientFilters) {
client.addFilter(clientFilter);
}
}
As you can imagine the client is the Jersey Client, and basically what this code does is to add a filter.
For Jersey filters are plugin of code that in the end knows how to do certain stuff with the payload you send.
In this case this filter "GZIPContentEncodingFilter" knows how to add the HTTP header I showed you before BUT ALSO, it knows how to zip the payload you're seeing.
Now that I've showed you how to handle this with Jersey I've also thought it'll be a good idea to show you just how to decode and encode any content in the same way, and this is how:
Decode:
InputStream io = (InputStream) someInputStreamYouHad;
String payload = new String(IOUtils.toByteArray(new GZIPInputStream(io)));
Encode:
OutputStream os = new ByteArrayOutputStream();
OutputStream realOs = new GZIPOutputStream(os);
realOs.write(payload.getBytes());
realOs.close();
payload = os.toString();
And that's it, hope it helps you/me.
Oh well there are many reasons for that but truth is "you don't care about that".
Let's jump then into this post topic, which is ZIPED content.
As you may or may not know web servers can send you the content you are requesting in a compress way. Main reason for this is, of course, cause you save bandwidth.
Problem being, you have to deal with that content.
As it turns out you usually come across this when you are creating some sort of HTTP client to consume something and when you try to print the data you can no read it (this is what happened to me).
Easiest way to know for sure that the server is doing this is, checking the following HTTP header:
Content-Encoding: gzip
This tells you that the "content" has been "gziped", quite obvious rigtht?
Now lets talk about code, how do I deal with this.
Well if you are a smart chap and you are using Jersey Client, this is how:
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
List<ClientFilter> clientFilters = new ArrayList<ClientFilter>();
clientFilters.add(new GZIPContentEncodingFilter(false));
if (clientFilters != null) {
for (ClientFilter clientFilter : clientFilters) {
client.addFilter(clientFilter);
}
}
As you can imagine the client is the Jersey Client, and basically what this code does is to add a filter.
For Jersey filters are plugin of code that in the end knows how to do certain stuff with the payload you send.
In this case this filter "GZIPContentEncodingFilter" knows how to add the HTTP header I showed you before BUT ALSO, it knows how to zip the payload you're seeing.
Now that I've showed you how to handle this with Jersey I've also thought it'll be a good idea to show you just how to decode and encode any content in the same way, and this is how:
Decode:
InputStream io = (InputStream) someInputStreamYouHad;
String payload = new String(IOUtils.toByteArray(new GZIPInputStream(io)));
Encode:
OutputStream os = new ByteArrayOutputStream();
OutputStream realOs = new GZIPOutputStream(os);
realOs.write(payload.getBytes());
realOs.close();
payload = os.toString();
And that's it, hope it helps you/me.
viernes, 11 de enero de 2013
Maven Archetype from Existing Project
Hi there,
So this weeks I've been having to mess around with Maven, in particular with archetypes.
Being new at this particular aspect of the Maven world I started where almost anyone will the Maven documentation page.
Any way.......
Thing is, this helped me a lot to understand the structure of a Maven archetype project but it didn't get me to create an archetype in an easy way.
In the end I found this blog.
As it turns out, the easiest way to create a Maven archetype is using an existing maven project.
Which makes senses.
As with anything in life if you like to create a template for something it's easier to create that something an then extract the template.
So this is the case, and the way to achieve this is:
mvn archetype:create-from-project
This will create a maven archetype from a project and will leave this new archetype project in:
target/generated-sources/archetype/
Now that you have you're base archetype you can start to tune it, and when you're ready to go just do:
mvn install
This will install the archetype in your local m2 repo.
Finally for those of you who don't know how to use this archetype one it's in place, this is the way:
mvn archetype:generate -DarchetypeGroupId={group.id.defined.in.the.archetype} -DarchetypeArtifactId={artifact-id-defined-in-the-archetype}
And that's it, have fun
So this weeks I've been having to mess around with Maven, in particular with archetypes.
Being new at this particular aspect of the Maven world I started where almost anyone will the Maven documentation page.
Any way.......
Thing is, this helped me a lot to understand the structure of a Maven archetype project but it didn't get me to create an archetype in an easy way.
In the end I found this blog.
As it turns out, the easiest way to create a Maven archetype is using an existing maven project.
Which makes senses.
As with anything in life if you like to create a template for something it's easier to create that something an then extract the template.
So this is the case, and the way to achieve this is:
mvn archetype:create-from-project
This will create a maven archetype from a project and will leave this new archetype project in:
target/generated-sources/archetype/
Now that you have you're base archetype you can start to tune it, and when you're ready to go just do:
mvn install
This will install the archetype in your local m2 repo.
Finally for those of you who don't know how to use this archetype one it's in place, this is the way:
mvn archetype:generate -DarchetypeGroupId={group.id.defined.in.the.archetype} -DarchetypeArtifactId={artifact-id-defined-in-the-archetype}
And that's it, have fun
martes, 8 de enero de 2013
Out of Memory with Maven & MAVEN_OPTS
Have you ever got an error like this:
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2786)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
at java.util.jar.JarVerifier.update(JarVerifier.java:194)
at java.util.jar.JarFile.initializeVerifier(JarFile.java:322)
at java.util.jar.JarFile.getInputStream(JarFile.java:388)
at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:69
Well this is the easy solution, increase the memory of the JVM.
BUT HOW IF I'M BUILDING WITH MAVEN???
God question, and the answer is:
export MAVEN_OPTS=-Xmx512m
Of course this will follow the same rules as for the vm arguments for the JVM, so please modify your memory limit accordingly.
Also this export command, for you Mac users, will only set the env var for the current terminal not for all the future ones.
Hope you find this useful I know I'll keep coming back to this post just to remember this.
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2786)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
at java.util.jar.JarVerifier.update(JarVerifier.java:194)
at java.util.jar.JarFile.initializeVerifier(JarFile.java:322)
at java.util.jar.JarFile.getInputStream(JarFile.java:388)
at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:69
Well this is the easy solution, increase the memory of the JVM.
BUT HOW IF I'M BUILDING WITH MAVEN???
God question, and the answer is:
export MAVEN_OPTS=-Xmx512m
Of course this will follow the same rules as for the vm arguments for the JVM, so please modify your memory limit accordingly.
Also this export command, for you Mac users, will only set the env var for the current terminal not for all the future ones.
Hope you find this useful I know I'll keep coming back to this post just to remember this.
viernes, 14 de septiembre de 2012
Once upon a time CURL
Have you had the chance to work with REST???
Something that I've come to learn working with REST is that people working with it are fond of the CURL command line.
Wikipedia defines CURL as:
"is a computer software project providing a library and command-line tool for transferring data using various protocols."
Thing is, I really don't like it. Not because it's a bad tool but because I just don't want to learn yet another command line, let's face it I'm lazy. Any way this people I was talking about have so much faith in CURL that may come to demand you to post the output of a CURL execution to validate what ever you're saying about a REST call.
Providing all this I thought it may be worth to write a small post about the really basic things that you can do with CRUL.
Now the prototype of the command it's quite simple:
Something that I've come to learn working with REST is that people working with it are fond of the CURL command line.
Wikipedia defines CURL as:
"is a computer software project providing a library and command-line tool for transferring data using various protocols."
Thing is, I really don't like it. Not because it's a bad tool but because I just don't want to learn yet another command line, let's face it I'm lazy. Any way this people I was talking about have so much faith in CURL that may come to demand you to post the output of a CURL execution to validate what ever you're saying about a REST call.
Providing all this I thought it may be worth to write a small post about the really basic things that you can do with CRUL.
Now the prototype of the command it's quite simple:
The options portion is the one that really matters.
Here is a list that I found useful, but keep an eye on the post for I may keep updating it:
-H this is for header. Any valid HTTP may be used here.
It's useful for things like Authorization.
-X this can be used for for HTTP verbs
Like so -X DELETE, -X POST
So this would be how a valid call looks like:
curl -H "Authorization: Basic sdaqwrdsfdsfafdszadsafdsafdsfad3" -X DELETE http://somehost.com/something?queryparam=somethingelese
Any way, for now this suits me but would you need more data please refer to:
Of course over there you'll find all there is to find about CURL, but I just like to post here things that I tend to forget.
Enjoy
viernes, 7 de septiembre de 2012
Retry Strategy Implementation
Hi, this small portion of code is to be used when ever you need to perform a task that may fail and in which event you should retry a predefined amount of times.
I won't be explaining the code in detail but if you have questions please to comment :D.
RetriableTask Class:
I won't be explaining the code in detail but if you have questions please to comment :D.
RetriableTask Class:
public class RetriableTask<V> implements Callable<V> {
private static final int DEFAULT_RETRY_ATTEMPTS = 3;
private static final int DEFAULT_TIME_BETWEEN_RETRIES = 1000;
private Callable<V> task;
private int retryAttempts;
private int timeBetweenRetries;
private int retryCount;
public RetriableTask(Callable<V> task) {
this(task, DEFAULT_RETRY_ATTEMPTS, DEFAULT_TIME_BETWEEN_RETRIES);
}
public RetriableTask(Callable<V> task, int retryAttempts, int timeBetweenRetries) {
this.task = task;
this.retryAttempts = retryAttempts;
this.timeBetweenRetries = timeBetweenRetries;
this.retryCount = retryAttempts;
}
@Override
public V call() throws Exception {
while (true) {
try {
return task.call();
} catch (InterruptedException e) {
throw e;
} catch (CancellationException e) {
throw e;
} catch (Exception e) {
retryCount--;
if (retryCount == 0) {
throw new RetryException(retryAttempts + " attempts to retry failed at " + timeBetweenRetries
+ "ms interval", e);
}
Thread.sleep(timeBetweenRetries);
}
}
}
}
How to use the class above:
Put this code in a method of your choosing. Of course this can be perfected and used in such way as to change what ever task you want to perform in runtime.
Callable<T> task = new Callable<T>() {
@Override
public T call() throws Exception {
return // WHAT EVER YOU NEED TO ACTUALLY DO;
}
};
String response = "";
try {
response = new RetriableTask<String>(task).call();
} catch (RetryException e) {
// THIS WILL BE CATCH WHEN:
// The call to the task fails and all the retries were exausted
// So do what ever you need to do when your operation fails:
// HERE
} catch (Exception e) {
// If you reach this point something else
// besides the actuall retry failed
throw new RuntimeException(e);
}
Attach existing directory to a new GIT Hub Repo
So........
This one may sound familiar to you right?
You started working on something and at some point some one tells you: "oh!!!! brilliant upload it Git Hub so I can take a look at it"
And ad that point is when the problem starts.
So how do you update code you are working on (this is an existing project) to a repo you are about to create.
Well this is basically solved in StackOverflow BUT allow me to replicate it here ok?
1. Create the remote repository, and get the URL such asgit://github.com/youruser/somename.git
If your local GIT repo is already set up, skips steps 2 and 3
2. Locally, at the root directory of your source, git init
3. Locally, add and commit what you want in your initial repo (for everything, git add . git commit -m 'initial commit comment')to attach your remote repo with the name 'origin' (like cloning would do)
4. to attach your remote repo with the name 'origin' (like cloning would do) git remote add origin [URL From Step 1]
5. git pull origin master
6. to push up your master branch (change master to something else for a different branch): git push origin master
So this worked pretty well for me to have a look at it.
I case you wander this is the StackOverflow link
This one may sound familiar to you right?
You started working on something and at some point some one tells you: "oh!!!! brilliant upload it Git Hub so I can take a look at it"
And ad that point is when the problem starts.
So how do you update code you are working on (this is an existing project) to a repo you are about to create.
Well this is basically solved in StackOverflow BUT allow me to replicate it here ok?
1. Create the remote repository, and get the URL such asgit://github.com/youruser/somename.git
If your local GIT repo is already set up, skips steps 2 and 3
2. Locally, at the root directory of your source, git init
3. Locally, add and commit what you want in your initial repo (for everything, git add . git commit -m 'initial commit comment')to attach your remote repo with the name 'origin' (like cloning would do)
4. to attach your remote repo with the name 'origin' (like cloning would do) git remote add origin [URL From Step 1]
5. git pull origin master
6. to push up your master branch (change master to something else for a different branch): git push origin master
So this worked pretty well for me to have a look at it.
I case you wander this is the StackOverflow link
Suscribirse a:
Entradas (Atom)