Sunday, 7 July 2013
Linux
Java Reflection
Private methods and Fields Access with Java Reflection
OK so the first thing first.
What is Java Reflection ?
Java Reflection can be used to dynamically find java classes , locating and execute methods, access fields at run time.
You can find More on : http://docs.oracle.com/javase/tutorial/reflect/index.html
Here is the sample project that I did.
First I create a class called dynamic test and add one private field and four methods including one private methods. Here is the code and its straight forward.
package rd.test;
public class DynamicTest {
private int count;
public void printStar() {
System.out.println("*");
}
public void printStarWithInt(int i) {
System.out.println("* Integer : " + i);
}
public void printStarWithString(String param) {
System.out.println("* String : " + param);
}
public void printStarWithStrings(String param1, String param2) {
System.out.println("* String : " + param1 + " , and " + param2);
}
private void printStarInPrivate() {
System.out.println("* Private : *");
}
}
and here is the class with main method.
package rd;
import rd.test.DynamicTest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class cls = Class.forName("rd.test.DynamicTest");
Object obj = cls.newInstance();
/**
* calling printstart method without passing any parameters
* */
Method method = cls.getDeclaredMethod("printStar", null);
method.invoke(obj, null);
/**
* calling printStarWithInt method with int parameter
*/
Class[] intParam = new Class[1];
intParam[0] = Integer.TYPE;
method = cls.getDeclaredMethod("printStarWithInt", intParam);
method.invoke(obj, 100);
/**
* calling printStarWithStrings methos with two string parameters
*/
Class[] stringParams = new Class[2];
stringParams[0]=String.class;
stringParams[1]=String.class;
method = cls.getDeclaredMethod("printStarWithStrings", stringParams);
method.invoke(obj, "hi","rajith");
/**
* calling private method in DynamicTest class
*/
method = cls.getDeclaredMethod("printStarInPrivate", null);
method.setAccessible(true);
method.invoke(obj, null);
/**
* setting and getting private fileds
*/
DynamicTest dynamicTest = new DynamicTest();
Field field = cls.getDeclaredField("count");
field.setAccessible(true);
field.setInt(dynamicTest,10);
System.out.println(field.get(dynamicTest));
}
}
Operating Systems Programming
Operating Systems Programming via Java Producer Consumer Problem with Blocking Queue
Before that I will give a quick introduction of Blocking Queue.
Blocking Queue is an interface locate in java concurrent package.It mainly support operations that wait for the queue to become non empty when retrieving and removing element and wait for space become available when adding an element. All the blocking queue implementation are thread-safe and methods are atomic.
In this demo I will use ArrayBlockingQueue as the implementation of BlockQueue.
So first we create domain model for this demo.
Message.java
package rd.domain;
public class Message {
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
then we create Producer.java
create 100 message and finish message and add in to the queue.
package rd.concurent;
import rd.domain.Message;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue<Message> queue;
public Producer(BlockingQueue<Message> queue) {
this.queue = queue;
}
@Override
public void run() {
// create messages and adding to queue
for (int i = 1; i <= 100; i++) {
Message message = new Message();
message.setDescription(" Message " + i);
try {
Thread.sleep(i);
queue.put(message);
System.out.println("Produced " + message.getDescription());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// adding exit message
Message message = new Message();
message.setDescription("finish");
try {
queue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Consumer.java
package rd.concurent;
import rd.domain.Message;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue<Message> queue;
public Consumer(BlockingQueue<Message> queue) {
this.queue = queue;
}
@Override
public void run() {
Message message = null;
try {
while (!(message = queue.take()).getDescription().endsWith("finish")){
Thread.sleep(10);
System.out.println("Consumed " + message.getDescription());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
So the basic implementation are done. Now its time to test it. Here I create Main.java and create producer consumer thread and start those threads.
Main.java
package rd;
import rd.concurent.Consumer;
import rd.concurent.Producer;
import rd.domain.Message;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String[] args) {
BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<>(10);
Producer producer = new Producer(blockingQueue);
Consumer consumer = new Consumer(blockingQueue);
new Thread(consumer).start();
new Thread(producer).start();
System.out.println("Started.................");
}
}
Hence we had solved the producer consumer problem.
Does Clean Code matters ?
Does Clean Code matters ?
And the other question is WHAT FOR ? That's what we talk about here..
OK lets go for it..
What is Clean code ? Actually we don't have the exact definition for this. But there are some definitions that create by geniuses. Below are some of these...
Bjarne Stroustrup, Inventor C++ and author of The C++ Programming Language
I like my code to be elegant and efficient. The logic should be straightforward to make it hard
for bugs to hide, the dependencies minimal to ease maintenance, error handling complete
according to an articulated strategy, and performance close to optimal so as not to tempt
people to make the code messy with unprincipled optimizations. Clean code does one thing
well.
Dave Thomas, founder of OTI, godfather of the Eclipse strategy,
Clean code can be read, and enhanced by a developer other than its original author. It has
unit and acceptance tests. It has meaningful names. It provides one way rather than many
ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.
Michael Feathers, author of working Effectively with Legacy Code,
I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought
about by the code’s author, and if you try to imagine improvements, you’re led back to
where you are, sitting in appreciation of the code someone left for you—code left by someone
who cares deeply about the craft.
WHY WE NEED CLEAN CODE ?
If your a programmer with more than one year you know what I mean..
First take a look at bad code or a mess code.
Suppose you get a new requirement and you need to add the new functionality to your existing code which is really bad and messy. Before adding any new thing to your code first you need to understand the exiting code. That means you need to READABILITY your existing code. Since its a bad code you will go through really pain full time to understand what the code says. For example imaging a code with no comments, no meaning full variables, no meaning full function definitions with hell of big line of codes that does too many things within single code block , this will drive you crazy.
So this will take more than time than your expecting(Or your PM) to read and understand only others code. Every programmer knows about the damn dead lines and our heads will bump up.
If it is a clean code it must full fill the READABILITY.
That's one of the basic thing that each and every code must have. But there are more. Formatting, Unit testing, avoid writing bad comments, Error handling are some of. So will talk about all of these things in near future.
Android Applications[Windows]
To Develop Android Applications[Windows] Setup required
Android is a software platform and operating system for mobile devices. It based on linux kernal and it written on Java language but not use JVM to execute the applications.
Here are the requirements to setup Android in your machine.
- Any Operating system
- Android SDK
- Java Development Kit
- Eclipse IDE (Optional, but has lot of advantages)
Here are the steps that you want to follow.
STEP 1
First you have to download the appropriate Android SDK from http://developer.android.com/sdk/index.html here.
Its free and anyone can download it. After downloading unzip it and install it.
Now you will get the Android SDK Manager.\
To get the full benefit go to Available packages and install the Third party add-ons . It includes the Google APIs.
STEP 2
In order to run your apps you want to set the Android Path in Environment variable.
For an Example:
suppose we have Java path and Android path. So PATH variable look like this
PATH = C:\Program Files\Java\jdk1.6.0_19\bin;C:\Program Files\Android\android-sdk-windows\tools
STEP 3
Now Every thing is set. But to develop applications you
need Eclipse IDE. You can use any IDEs that support Java. But using
eclipse you can get the lots of benefits.
Download Eclipse in here ---> http://www.eclipse.org/downloads/
Goto Help --> Install New Software
Click Add
Enter 'ADT Plugin' for the Name and enter 'https://dl-ssl.google.com/android/eclipse/' for the URL and Select OK.
Click Next in the windows and click Finish. After that restart the Eclipse to apply the changes.
To configure Eclipse follow these steps.
1.Windows --> Preferences
2.Select Android
3.Give the SDK location and click Apply.
Hence you all can enjoy Android Programming.
What is Cloud Computing ?
Cloud Computing
Cloud computing is location-independent computing, whereby shared servers provide resources, software, and data tocomputers and other devices on demand, as with the electricity grid.source : http://en.wikipedia.org/wiki/Cloud_computing
Cloud Computing as the term indicates implies using the cloud infrastructure or internet based shared infrastructure to host and access applications. That means hosting application and their data on a shared servers on the internet and access the applications through a browser.
Things that cloud computing change
- Completely shift from Desktop based model to Web based model. In cloud computing model applications are web based hosted on a cloud server and users can access the applications through a web browser.
- Hosting application and services. Today most business organizations host application on their servers and use their firewalls. So adding these things is a extra overhead for organizations. Moving to the cloud model make it easier to organizations.
- Security, a key implication in cloud computing is that security risk added by the third party provider.
Saas, Paas and Iaas
Cloud computer has various flavors of implementation. In
here we talk about SaaS(Software as a Service) , PaaS(Platform as a
service), IaaS(Infrastructure as a service).
Software as a Service (Saas)
This term describe software that is deployed over the
internet. The services are provided with typically payment charged on
monthly basis based on the number of users or services consumed.
Platform as a service (PaaS)
Provide the ability for building and deploying custom application on their platform.
Amazon EC2 , Microsoft Azure , Google App Engine are some of service providers.
Infrastructure as a service (Iaas)
Provide computer and server infrastructure as a virtualization environment.
Amazon Web Services and Rackspace are examples of service provides.
Here is the brief description about cloud computing.
In Linux Google App Engine in Eclipse
In Linux Google App Engine in Eclipse
STEP 1
First you have to install Eclipse IDE for that . Its free so anyone can download. Here is the link.
Eclipse IDE
STEP 2
Now install Java SDK. Here is the link..
Java SDK
STEP 3
Now install the Google Eclipse App Engine plugin.
Ref Link : http://code.google.com/eclipse/docs/install-from-zip.html
STEP 4
Install the Google web toolkit plugin.
Ref Link : http://code.google.com/webtoolkit/gettingstarted.html
- There is easiest way to follow Step 3 and 4. Click Help --> Eclipse Market Place
- Type Google App Engine
- install the plugin
STEP 5
Create Web Application.
File --> New --> Web application or Simply click the g icon (blue background).
- Enter the Project Name as GuestBook and Package name as guestbook.
- Make sure Google Web Toolkit checkbox and Google App Engine check box is selected.
- Click Finish.
Now it will create the project structure like this.
There are some files that Eclipse automatically created.
- src/GuestBookServlet.java
- war/WEB-INF/web.xml
- war/WEB-INF/appengine-web.xml
STEP 7
After that debug your app like this. Click Run ---> Debug as ---> Web Application
now it will create a server 8888 port so you can access it by browsing http://localhost:8888/
STEP 8
To deploy your app to Google App Engine right click the app select Google --> Deploy to App Engine
Before deploy get application ID from http://code.google.com/appengine/ .
So, These are the major steps that you want to follow to create and deploy Java App Engine application to Google App Engine.
mysql databases.
Restore & Backup Mysql Database using mysqldump Command
You have to use command prompt[Windows users] or kernel[Linux users,MacOS] to backup databases.
Backup Mysql Database
- Backup a single database
mysqldump -u root -p[root_mysql_password] [database_name] > [path_to_save_with_sql_extension]
ex:
mysqldump -u root -p123 test > D:/backups/test_backup.sql
- Backup Multiple databases
mysqldump -u root -p[root_mysql_password] --databases [database_name] [database_name] .. > [path_to_save_with_sql_extension]
ex:
suppose we have two databases called test and tutorial
mysqldump -u root -p123 --databases test tutorial > D:/backups/test_tutorial.sql
- Backup all the databases
mysqldump -u root -p[root_mysql_password] -all-databases > [path_to_save_with_sql_extension]
- Backup a specific table
Suppose we have a demo table in test database.
mysqldump -u root -p123 test demo \ > D:/backups/demotables.sql
Restore Mysql Database
To restore mysql database use following command.
mysql -u root -p[root_mysql_password] [database_name] < D:/backups/test.sql
Java 7 / Apache Click/ Apache Shiro
New in Java 7 ?
http://blog.eisele.net/2011/07/introducing-java-7-moving-forward-7711.html
Application Protection with Apache Shiro
Apache Shiro is a Java security framework that performs four kind of operations such as authentication, authorization, cryptography and session management. Can use in any kind of web applications or mobile applications. It provide a security API for perform the above tasks.
Advantages of Apache Shiro
- Easy to use
- Comprehensive
- Flexible
- Pluggable
Shiro was 5 years old and previously know as Jsecurity project. There were no other alternatives for java security but the Java Authentication and Authorization Service (JAAS). But in JAAS also have some issues with cryptographic. Java cryptographic architecture was hard to understand and it did not use as usual. But in Apache Shiro it gives flexible security for Java developers add security there applications.
Furtherer References : Apache Shiro Home Page
Apache Click
Apache Click is a Web application framework for Java language and built top of Java Servlet API. Its free and open source project under Apache foundation.
In the new version of Apache Click (version 2.3.0) it add some new features like AJAX support, Page Actions and stateful controls. Using Apache click we can build a web applications without using JSPs and MCV architecture.
Apache click use HTML templates an POJO for develop applications. It also include some unit testing features.
Ref : Apache Click Home
: Getting Started with apache click
: Examples
Subscribe to:
Posts (Atom)