Archive

Posts Tagged ‘JAVA’

Portable REST using Spark Framework

9 January 2015 Leave a comment

Today, i will write some tiny-tutorial how to create a portable REST using Spark MVC Framework, http://sparkjava.com/. Spark is very lite and would be a good choice -and an alternative of SpringMVC- if you are developing a small project of MVC/REST.

  1. Create your Maven project and add this dependency. Notes here, i’m using Java 6 for my development and i’m too lazy to point to Java 8, so i’m using the version 0.9.9.3-SNAPSHOT of Spark. You are welcomed to use the newest version of Spark. Please refer to http://sparkjava.com/download.html.
    <dependency>
            <groupId>spark</groupId>
    	<artifactId>spark</artifactId>
    	<version>0.9.9.3-SNAPSHOT</version>
    </dependency>

    And this to your repository

    <repository>
    	<id>Spark repository</id>
    	<url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
    </repository>
  2. Code your application here.Dont forget to put the code inside of your main function, so it could be called from the command prompt.
    package com.namex.spark;
    
    import spark.Request;
    import spark.Response;
    import spark.Route;
    import spark.Spark;
    
    public class SparkHelloWorld {
    	public static void main(String[] args) {
    		Spark.get(new Route("/SparkHelloWorld/:name") {
    
    			@Override
    			public Object handle(Request req, Response res) {
    				// to get the parameter
    				String nameFromParam = req.params(":name");
    				String jsonString = "{\"message\": \"Spark Hello World\", \"name\": \"" + nameFromParam + "\"}";
    				return jsonString;
    			}
    		});
    	}
    }
    
  3. Run the SparkHelloWorld class, and open this url from your web browser http://localhost:4567/SparkHelloWorld/namingexception.

JbNIxZN

 

That’s all. It’s so simple and easy. Even though i have to admit Spark might not suitable for big-scale project, still it’s a good option to be considered.

Advertisements
Categories: Java Tags: , , ,

Calling private methods publicly ?

We Java developers, known 4 access modifiers in Java: private, protected, public, and package. Well, except for the private, the last three, can be called from outside of the class by inheritance, same package or from the instance.

Now, the common question, can private be called publicly (from outside class)? well the answer is NO and YES. No when you use ‘usual’ way to access it, and YES when you ‘hack’ into it using the Reflection API provided by Java itself.

Well okay, now just write the code that we will hack into. I called it as “TheVictim

package com.namex.hack;

public class TheVictim {
	private void hackTest() {
		System.out.println("hackTest called");
	}

	private static void hackTestStatic() {
		System.out.println("hackTestStatic called");
	}

}

Now after that, just follow my code and try to run it. I guarantee that if you followed it right, you will get TheVictim to call both of the hackTest and hackTestStatic. And you can see the output on your screen.

package com.namex.hack;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class HackTest {
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

		Class c = TheVictim.class;

		Method[] ms = c.getDeclaredMethods();

		for (Method each : ms) {
			String methodName = each.getName();
			each.setAccessible(true); // this is the key
			if (Modifier.isPrivate(each.getModifiers())) {
				
				if (Modifier.isStatic(each.getModifiers())) {
					// static doesnt require the instance to call it.
					each.invoke(TheVictim.class, new Object[] {});
				} else {
					each.invoke(new TheVictim(), new Object[] {});
				}
			}
		}

	}
}


Output example:

hackTestStatic called
hackTest called

Okay, this tutorial has met its purpose. Now you know the Reflection API of java is very powerful feature of programming language. And it’s all up to you to modify or even extend it for your own purpose. Have fun with Java 🙂

Categories: Java Tags: ,

How Easy to Make Your Own Twitter Client Using Java

12 September 2011 53 comments

Got inspired by my friend, whom built his own Twitter client for his company’s client. So, i tried to build one using Java. And im surprised that how easy to make Twitter client, of course i still use third-party API to make my job easier.

This simple client will only have 2 purposes: reading timeline and post status. Dont worry, you can expand this application later, it’s simple and easy once you have your app got authorized by Twitter.

First of all, you have to go to official Twitter Developer Registration at https://dev.twitter.com/apps/new , and register your application detail there. For this blog purpose, i will create a new application that called “Namex Tweet for Demo“. It’s simple, just fill in some required data and voila it’s done in seconds.

After you passed this registration step, dont forget the most important things in here are these Consumer and Consumer Secret key. Just say, it’s a signature to let Twitter knows your application. These things will be hardcoded at your application. In here, my Consumer key is DXjHgk9BHPmekJ2r7OnDg and my Consumer Secret key is u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0 . Dont use these keys in your application, it’s useless because i will turn off the application as short as this blogging purpose done.

consumer key

And after registration step dont forget to visit Setting page and adjust setting for your application access.

tab setting

app type

Choose Read, Write and Access direct messages to get your application at full functional. you now can download additional java API for twitter, im using Twitter4J . Here, you have to download several jars,

  • twitter4j-async-<a.b.c>
  • twitter4j-core-<a.b.c>
  • twitter4j-media-support-<a.b.c>
  • twitter4j-stream-<a.b.c>

Notes: Dont use twitter4j-appengine.jar, it will cause your application thrown to exception on authorizing process.

In my version a is 2, b is 2 and c is 4. So it would look like twitter4j-async-2.2.4 etc. After these jars being downloaded at your machine, our downloading job has not done yet. We still have to download Apache Commons Codec as Twitter4J dependencies. After all of the jars downloaded, now we can start to code. Open your fave IDE and start it with me.

package com.namex.tweet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class NamexTweet {
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET = "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
	RequestToken requestToken = twitter.getOAuthRequestToken();
	System.out.println("Authorization URL: \n"
		+ requestToken.getAuthorizationURL());

	AccessToken accessToken = null;

	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	while (null == accessToken) {
	    try {
		System.out.print("Input PIN here: ");
		String pin = br.readLine();

		accessToken = twitter.getOAuthAccessToken(requestToken, pin);

	    } catch (TwitterException te) {

		System.out.println("Failed to get access token, caused by: "
			+ te.getMessage());

		System.out.println("Retry input PIN");

	    }
	}

	System.out.println("Access Token: " + accessToken.getToken());
	System.out.println("Access Token Secret: "
		+ accessToken.getTokenSecret());

	twitter.updateStatus("hi.. im updating this using Namex Tweet for Demo");

    }

    public static void main(String[] args) throws Exception {
	new NamexTweet().start();// run the Twitter client
    }
}

Compile and run the code, it will create permission for “Namex Tweet for Demo” to be linked with your Twitter account. Just open the “Authorization URL” shown at the screen and input the PIN shown by the website. Your application will send back the pin to Twitter, if it’s match your account will be linked with this new application and you can see you just posted a new status using “Namex Tweet for Demo “. Congratulation!

Notes: Authorization URL and PIN will generated differently each time it’s run.

auth url

auth pin

update tweet

In here you can see, we input no username and password of Twitter account but we can use our account within application. Yeah it’s possible because of OAuth . It “transformed” password-input-process to sending-receive-token. So dont worry, Third-party Twitter client application cant read and store no password of your Twitter account. In simple, it’s safer and prevent password thieving.

Now we still have a tiny problem, at this point, your program still need to open Twitter’s website and input pin back to the application. So, maybe you are asking on the cloud, do i need this annoying authorization on the future ? well, gladly the answer is NO. At the time your app being authorized by Twitter, you have no use to re-authorize it again — with a simple note you have to save the Access Token and Secret Access Token . What the hell is that, how could i get that. Well, you have it already, see the image below, i put it in a big red rectangle so it will be more eye-catchy. In here, our token is and our secret token is. These 2 tokens have to be saved somewhere, you can choose your own method to save it: Persistence, CSV, DBMS, etc. It’s all up to you.

access token

So, i saved the tokens! How do i reuse it? It’s simple, see below code. It’s how to use your tokens, so you wont have the re-authorization process again. Try to post and read your timeline now.

package com.namex.tweet;

import java.io.IOException;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class NamexTweet {
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET = "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);

	// here's the difference
	String accessToken = getSavedAccessToken();
	String accessTokenSecret = getSavedAccessTokenSecret();
	AccessToken oathAccessToken = new AccessToken(accessToken,
		accessTokenSecret);

	twitter.setOAuthAccessToken(oathAccessToken);
	// end of difference

	twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");

	System.out.println("\nMy Timeline:");

	// I'm reading your timeline
	ResponseList list = twitter.getHomeTimeline();
	for (Status each : list) {

	    System.out.println("Sent by: @" + each.getUser().getScreenName()
		    + " - " + each.getUser().getName() + "\n" + each.getText()
		    + "\n");
	}

    }

    private String getSavedAccessTokenSecret() {
	// consider this is method to get your previously saved Access Token
	// Secret
	return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
    }

    private String getSavedAccessToken() {
	// consider this is method to get your previously saved Access Token
	return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
    }

    public static void main(String[] args) throws Exception {
	new NamexTweet().start();
    }

}

post again

tl

Now our simple Twitter application has been -could be- done, we can read and post to Twitter. Of course, many things still on the task list if you want to make it professionally and -perhaps- sell it. A nice UI, reading and sending Direct Message, Searching Users, Follow and Unfollow. I put these jobs on your shoulder, cause i just want to share it’s easy to make a Twitter client and i hope this short tutorial can help you in developing Twitter client using Java.

Happy Code All !

Categories: Java, Miscellaneous Tags: , ,