Search on this blog

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, October 1, 2009

The MARS ROVER problem

The problem is stated below:
A squad of robotic rovers are to be landed by NASA on a plateau on Mars.
This plateau, which is curiously rectangular, must be navigated by the
rovers so that their on-board cameras can get a complete view of the
surrounding terrain to send back to Earth.

A rover's position and location is represented by a combination of x and y
co-ordinates and a letter representing one of the four cardinal compass
points. The plateau is divided up into a grid to simplify navigation. An
example position might be 0, 0, N, which means the rover is in the bottom
left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The
possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the rover spin 90
degrees left or right respectively, without moving from its current spot.
'M' means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:
The first line of input is the upper-right coordinates of the plateau, the
lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have
been deployed. Each rover has two lines of input. The first line gives the
rover's position, and the second line is a series of instructions telling
the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces,
corresponding to the x and y co-ordinates and the rover's orientation.

Each rover will be finished sequentially, which means that the second rover
won't start to move until the first one has finished moving.


OUTPUT
The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:
1 3 N
5 1 E
==========

The solution link: http://www.box.net/shared/av24fot8i5

The gist description: The source code is available in src folder.
JUnit test case is available inside test folder.
The JUnit testcases contain only test inputs given in the mail.
For inputs other than given input you can use the com.mars.rovers.Main class which takes the user inputs.
Read full history - The MARS ROVER problem

Wednesday, September 16, 2009

xstream: An intro

XStream is a unique open-source Java library for serializing objects into XML and deserializing that XML into objects. Unlike other APIs, such as David Megginson's XMLWriter or Elliotte Rusty Harold's XOM, which use specific classes and methods to produce XML, XStream relies on Java idioms such as object names to produce element names and strings within classes to produce element content. It also produces a kind of reflection of objects in XML.

XStream is being actively developed by a small project team with over a dozen contributors. It promises to become a very useful tool for persistence and transport; and I think it embraces, as does Joe Walnes, some virtues of agile programming.

Joe Walnes explained the following in private correspondence:
XStream's primary purpose is for serialization. It allows existing Java objects to be converted to clean XML and then restored again, without modifications. This is particularly useful as a form of persistence (no complicated database mappings required) or for sending objects over the wire. It has been optimized for this and is in heavy use on production systems.

XStream offers a two-minute tutorial and JavaDocs. Unfortunately, the XStream distribution doesn't yet provide example programs, though there is a test suite. This article demonstrates several example Java programs that should help you get started with XStream today.

The current, stable version of XStream is 1.0.1, which was released at the end of May 2004. This article, however, uses the latest snapshot available in late July 2004. Programs were compiled and run with Sun's Java 1.4.2_05 and included an XStream JAR (xstream-SNAPSHOT.jar) in the classpath at compile time. The examples also use Aleksander Slominski's speedy XML Pull Parser or XPP (xpp3-1.1.3.3_min.jar) at runtime. Both the stable and snapshot versions of XStream includes JARs. Download both the XStream archive and the example programs to a working directory.


A Simple Program

Let's start with a simple program that shows the basics of XStream serialization. The program Hello.java follows. It is available in the sample archive for this article. The program uses XStream to output a string in XML:

[sourcecode language="java"]import com.thoughtworks.xstream.XStream;

public class Hello {
public static void main(String[] args) {

XStream xstream = new XStream();

String salutation = "Hello, World!";

String xml = xstream.toXML(salutation);

System.out.print(xml);
}

}[/sourcecode]

The public class Hello imports only one class, com.thoughtworks.xstream.XStream. It calls a constructor for XStream, creating the object xstream. Then it uses the toXML method to store the string salutation as XML, and writes the XML to the console using the System.out.print method.

This shows the current directory and the XStream JAR in the classpath explicitly. (Of course, use colons instead of semicolons if you are on Unix.) Once Hello.java compiles successfully, run it with this line:

java -cp .;xstream-SNAPSHOT.jar;xpp3-1.1.3.3_min.jar Hello

This line adds the XPP JAR to the command line; it should output the following:

Hello, World!

XStream automatically wraps the Java String salutation in the XML element string. The string element appears to be an example of XStream's style of XML reflection. If you really want to see this in action, try Reflect.java:

[sourcecode language="java"]import com.thoughtworks.xstream.XStream;

public class Reflect {
public static void main(String[] args) {

XStream xstream = new XStream();

String xml = xstream.toXML(xstream);

System.out.print(xml);
}
}[/sourcecode]

This program serializes the object xstream into XML, producing over 7,000 lines of "reflection." If you want to avoid the dependency on XPP, you can use DOM instead, like this (HelloDom.java):

[sourcecode language="java"]
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class HelloDom {
public static void main(String[] args) {

XStream xstream = new XStream(new DomDriver());

String salutation = "Hello, World!";

String xml = xstream.toXML(salutation);

System.out.print(xml);
}
}
[/sourcecode]

The differences between Hello.java and HelloDom.java are highlighted in bold: HelloDom.java imports the additional class com.thoughtworks.xstream.io.xml.DomDriver and then uses DomDriver in the XStream constructor. When you run HelloDom, you can drop the reference to the XPP JAR on your classpath.


Using Another Class

The next program, Instant.java, uses a non-public outer class, Date, to represent some data for a date:

import com.thoughtworks.xstream.XStream;

class Date {
int year;
int month;
int day;
}

public class Instant {
public static void main(String[] args) {

 XStream xstream = new XStream();

 Date date = new Date();
date.year = 2004;
date.month = 8;
date.day = 15;

 xstream.alias("date", Date.class);

 String decl = "\n";

 String xml = xstream.toXML(date);

 System.out.print(decl + xml);
}
}

The class Date holds three fields, all of which are integers. After the Date constructor, each of these fields is given a value, e.g. date.year = 2004;. The alias method creates an alias XML element name for the Date class, changing the default name from Date to date. XStream uses the fully qualified class name for the element name, including the package name, so the alias method will come in handy for tweaking names. The program also creates an XML declaration and uses it in its output.

Compile and run the program, and you will get this output:

2004
8
15

Deserializing XML to Objects

The final program, Deserialize.java, shows you how to deserialize XML to an object, and then to reuse it:

import com.thoughtworks.xstream.XStream;

class Date {
int year = 2004;
int month = 8;
int day = 15;
}

public class Deserialize {

 public static void main(String[] args) {

 XStream xstream = new XStream();

 Date date = new Date();

 xstream.alias("date", Date.class);

 String xml = xstream.toXML(date);

 System.out.print(xml);

 Date newdate = (Date)xstream.fromXML(xml);
newdate.month = 12;
newdate.day = 2;

 String newxml = xstream.toXML(newdate);

 System.out.print("\n\n" + newxml);
}
}

Note this line from Deserialize.java:

Date newdate = (Date)xstream.fromXML(xml);

The line creates a new object newdate using the fromXML method to convert the string xml back to an object (also casting it as Date).

After compiling and running Deserialize.java, you will see this output (two XML documents):
2004
8
15
2004
12
2

The second instance of date comes from the object created from deserialized XML.

Source: XML.com | original source
Read full history - xstream: An intro

Wednesday, November 12, 2008

Good article: Compiling servlet

Find here.
Read full history - Good article: Compiling servlet

Wednesday, October 22, 2008

Sample Java code for printing output on a printer


import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
 
 
public class PrintSample  implements Printable {
 
   static JTextArea textarea = new JTextArea(10,40);
   static JFrame   window = new JFrame("Print Sample");
 
  public static  void main(String args[])   {
 
    final Container cp = window.getContentPane();
    JButton buttonLPT = new JButton("Use LPT1");
    JButton buttonPA = new JButton("Use PrintAll");
    JButton buttonPJ = new JButton("Use Printable");
    LayoutManager lm = new FlowLayout(FlowLayout.CENTER, 20,20);
 
    // fill in text to display (and later print)
    textarea.append("Text here is going to be printed.\n");
    textarea.append("Next line to be output.\n");
    textarea.append("The end\n");
    textarea.setEditable(false);
 
     // set up layout and fill in sample
     cp.setLayout(lm);
     cp.add(new JScrollPane(textarea));
     cp.add(buttonLPT);
     cp.add(buttonPA);
     cp.add(buttonPJ);
 
     // add the button press response for buttons
     buttonLPT.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           printLPT();
        }
        });
 
     buttonPA.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           printPrintAll();
        }
     });
 
     buttonPJ.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           printPrinterJob();
        }
      });
 
     // set up WindowListener to close the program
     window.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
         System.exit(0);
     }
    });
 
    window.setSize(475,300);
    window.setVisible(true);                  // frame starts out invisible
 
   }
 
 
   // PrintJob and printAll implementation
   static void printPrintAll()  {
 
      PrintJob printjob = window.getToolkit().getPrintJob(window, "test", null);
 
      if (printjob != null) {
 
         Graphics printgraphics = printjob.getGraphics();          // get a graphics object that will draw to the next page.
         if (printgraphics != null) {                               // if user selects cancel on the print dialog, printgraphics will be null
            printgraphics.translate(100,100);                      // move the origin of the drawing area so there is a margin
            textarea.printAll(printgraphics);                       // output the text
            printgraphics.dispose();                                // the page is sent to the printer when dispose is called
         }
         printjob.end();                                                                  // ends the printjob and does any necessary cleanup
      }   // end if printjob
   }
 
 
   // PrinterJob implementation
   static void printPrinterJob() {
 
      PrinterJob printerjob = PrinterJob.getPrinterJob();            // get a printer job object
 
      // set the characteristics of the job to be printed - use setPageable and book if
      // outputing a document. Use setPrintable for "simple" printing - all pages formatted the same
      printerjob.setPrintable(new PrintSample());
 
      try {
         printerjob.print();            // print the page(s)  (this method with call the page painters)
      } catch (PrinterException exception) {
         System.err.println("Printing error: " + exception);
      }
  }
 
 
  // Use LPT1 as file implementation
  static void printLPT() {
     String strText = null;         // text string to output
     int lineStart;                 // start index of line in textarea
     int lineEnd;                   // end index of line in textarea
     int lineNumber;                // line number currently outputing
     int lineCount;                 // number of lines in textbox
 
      try {
               FileOutputStream os = new FileOutputStream("LPT1");
               PrintStream ps = new PrintStream(os);
 
              // get the text from the textarea one line at a time
              // in order for it to be output as it appears in the textbox
              lineNumber = 0;
              lineCount = textarea.getLineCount();
              strText = textarea.getText();
              while (lineNumber <>
 
                // parse off each line
                 lineStart = textarea.getLineStartOffset(lineNumber);
                 lineEnd = textarea.getLineEndOffset(lineNumber);
                 strText = textarea.getText(lineStart, lineEnd-lineStart);
                 // output the text via ps.println
                ps.println(strText);
                 lineNumber = lineNumber + 1;
              }
 
              ps.print("\f");             // form feed - print will stay in buffer if this is omitted
              ps.close();
      } catch(Exception exception) {
            System.out.println("Printing error:" + exception);
     }
 
  }
 
 
 
   // print  - draw the page
   // Parameters:    graphics - context in which to draw the page
   //                pageFormat - size and orientation of page being drawn
   //               pageIndex - zero-based index position of the  page in the print job
   //
   public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
      throws PrinterException {
 
       String strText =null;    // text string to output
      int lineStart;           // start index of line in textarea
       int lineEnd;             // end index of line in textarea
       int lineNumber;          // current line in textarea
       int lineCount;           // total number of lines in textarea
 
       if (pageIndex >= 1 ) return Printable.NO_SUCH_PAGE;
 
       // move the drawing origin to the imageable area ( makes sure its drawn where the printer can )
       graphics.translate((int)(pageFormat.getImageableX()), (int)(pageFormat.getImageableY()));
       graphics.setColor(Color.black);
 
       // get the text from the textarea one line at a time
       lineNumber = 0;
 
       lineCount = textarea.getLineCount();
       strText = textarea.getText();
       while (lineNumber <>
          try {
             lineStart = textarea.getLineStartOffset(lineNumber);
             lineEnd = textarea.getLineEndOffset(lineNumber);
             strText = textarea.getText(lineStart, lineEnd-lineStart);
          } catch( Exception exception) {
             System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
          }
 
          // determine drawing location of each successive line
          graphics.drawString(strText,0,(lineNumber + 1) *20);
          lineNumber = lineNumber + 1;
        }
 
        return Printable.PAGE_EXISTS;                      // page was drawn successfully (return NO_SUCH_PAGE if not)
   }
 
 
 
}
Read full history - Sample Java code for printing output on a printer

Getting output to the printer


There are several ways of accomplishing this task in Java. Depending on your needs, it can be as simple as opening LPT1 as a file and using file I/O methods, using the PrintJob class and the printAll() method, or getting more formatting capabilities with a solution such as the Java 2 Printing API. Here’s a look at each technique.

Open LPT1
The first solution, treating LPT1 as a file, is an easy way to output text strings from within a program. However, you must exercise caution, as LPT1’s availability is dependent on the host environment. Once you access LPT1 successfully, you need to pay attention to text formatting. If the lines are too long, the text that falls off the side of the page is truncated (there is no line wrap). You must also output a form feed (\f) at the end of outputting the data you want printed. If the form feed is left off, the data will stay in the print buffer until another print job comes along.

Use printAll()
The second possible solution is to use the printAll() method of a component in conjunction with the PrintJob class. PrintJob is a part of the java.awt package and is responsible for starting and executing a print job. The programmer has no control over the print dialog—it displays automatically when you call the PrintJob method getGraphics. If the user cancels, null is returned. If the user selects OK, a valid graphics object is returned. This object is then used to draw to the print device. The dispose method of the graphics object causes a form feed on the paper and frees up resources.

The printAll() method was introduced with JDK 1.1 and provides an easy way to draw to the print device. The method will cause the component used as an argument and its subcomponents to be printed. Each component’s print method is called to perform the actual drawing. If you don’t need the whole hierarchy printed, just call the printAll() method of the particular component you are interested in.

Printing API
The final solution is to use the Java 2 printing API. This is accomplished via the PrinterJob class. It is used to set up a print job, display a print dialog (if you want), and then print the pages of a job. PrinterJob is part of the java.awt.print package.

The Printable interface of PrinterJob defines how each page is drawn or painted via the print method. If you are printing a document with pages of different formats (e.g., a cover page and the table of contents), each format must have its own print method. The application tells PrinterJob how to print via setPrintable (all pages, one format) or setPageable (multiple pages, different formats).

An important item to note is that the print method may be called more than once. The clip region of the graphics parameter is set for the area of the page that is to be drawn. In the given example, all items are drawn regardless of the clip value. If the text falls outside of the clip area, nothing is rendered. The text output appears only once since it falls within a given clip region one time. If you want to be efficient (and help performance), you should modify the code to render only the areas that fall within the given clip region.
Read full history - Getting output to the printer

Tuesday, September 23, 2008

Connecting to Active Directory using LDAP


The below code can tell that what we can do with java, .NET guys please don't mind.




String userName = "username";
String passWord = "password";
String base = "cn=Users,dc=ssc,dc=mycompany,dc=com";

Hashtable env = new Hashtable();

public LDAPCrap() {
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,
"ldap://ssc-dc-01.ssc.mycompany.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=" + userName + "," + base);
env.put(Context.SECURITY_CREDENTIALS, passWord);

}

public void isAuth() {
try {
LdapContext authContext = new InitialLdapContext(env, null);

String filter = "(objectclass=*)";
String sbase = "";
SearchControls controls = new SearchControls();
                        UsernamePasswordHandler handler = new UsernamePasswordHandler(user,
pwd.toCharArray());
LoginContext loginContext = new LoginContext("TEST", handler);
loginContext.login();

// may be a scope change
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
DirContext ctxGC = new InitialDirContext(env);
NamingEnumeration answer = ctxGC.search(sbase, filter, controls);
SearchResult sr = (SearchResult) answer.next();
javax.naming.directory.Attributes attrs = sr.getAttributes();
System.out.println(" Naming Context: "
+ attrs.get("defaultNamingContext").get());
System.out.println("Bind Successful");
} catch (AuthenticationException authEx) {
System.out.println("Authentication failed!");
} catch (NamingException namEx) {
System.out.println("ERROR IN BIND: " + namEx);
namEx.printStackTrace();
}

}
Read full history - Connecting to Active Directory using LDAP

Tuesday, September 16, 2008

10 time-saving techniques in Eclipse Europa


This I got from IBM and it is really cool. Just go through the link : https://www6.software.ibm.com/developerworks/education/os-eclipse-europatimesave/.
Read full history - 10 time-saving techniques in Eclipse Europa

Tuesday, July 8, 2008

Sample JMS Queue program

Try this after setting up the environment for JMS. The programs are purely for Jboss environment.
SimpleQueueSender
package src;
import javax.naming.InitialContext;
import javax.jms.ConnectionFactory;
import javax.jms.Connection;

import javax.jms.Session;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;
import javax.jms.Queue;
import java.util.Properties;
import javax.jms.*;
import javax.naming.*;
import java.io.*;
public class SimpleQueueSender{
public static void main(String[] args) throws IOException { String queueName = null; Context jndiContext = null; QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue queue = null; QueueSender queueSender = null; TextMessage message = null; // Message message = null; FileUpload fload=null; File f=null; /*f=new File("d:/ex.zip"); fload=new FileUpload(); fload.setFile(f); ByteArrayOutputStream byteOut=fload.getByteStream();*/ try { Properties p=new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory"); p.put(Context.PROVIDER_URL,"jnp://192.168.192.109:1099"); p.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); //Context ctx=new InitialContext(p); jndiContext = new InitialContext(p); } catch (NamingException e) { System.out.println("Could not create JNDI API " + "context: " + e.toString()); System.exit(1); } try { queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("ConnectionFactory"); queue = (Queue) jndiContext.lookup("queue/IncomingMessageQueue"); } catch (NamingException e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1); }
/* * Create connection. * Create session from connection; false means session is * not transacted. * Create sender and text message. * Send messages, varying text slightly. * Send end-of-messages message. * Finally, close connection. */ try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); /* message.writeBytes(byteOut.toByteArray()); message.setText("This is message from Preeti guguoguoguoguoguoguog");*/ System.out.println("Sending message: "); message.setText("This is message from Abhinaba guguoguoguoguoguoguog"); queueSender.send(message,DeliveryMode.PERSISTENT,4,1000*60*10); System.out.println("Message sent");
/* * Send a non-text control message indicating end of * messages. */// queueSender.send(queueSession.createMessage()); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) {} } } }}

Queue Receiver

package src;
import java.util.Properties;
import javax.jms.*;import javax.naming.*;
public class SimpleQueueReceiver {
public static void main(String[] args) { String queueName = null; Context jndiContext = null; QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue queue = null; QueueSender queueSender = null; TextMessage message = null; QueueReceiver queueReceiver=null; try { Properties p=new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory"); p.put(Context.PROVIDER_URL,"jnp://192.168.192.109:1099"); p.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); //Context ctx=new InitialContext(p); jndiContext = new InitialContext(p); } catch (NamingException e) { System.out.println("Could not create JNDI API " + "context: " + e.toString()); System.exit(1); } try { queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("ConnectionFactory"); queue = (Queue) jndiContext.lookup("queue/SSX-SSEIncomingMessageQueue"); } catch (NamingException e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1); }
/* * Create connection. * Create session from connection; false means session is * not transacted. * Create sender and text message. * Send messages, varying text slightly. * Send end-of-messages message. * Finally, close connection. */ try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueConnection.start(); //queueSender = queueSession.createSender(queue); queueReceiver = queueSession.createReceiver(queue); message = (TextMessage)queueReceiver.receive(5000); if(message!=null) System.out.println(message.getText()); else System.out.println("No messages for u"); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) {} } } }}
Read full history - Sample JMS Queue program

Monday, May 12, 2008

Migrating Messages from JBoss MQ to JBoss Messaging

This configuration will allow you to migrate your systems using JBossMQ to JBM(JBoss Messaging). Many Enterprise systems are complex and have multiple applications and can't be migrated from JBossMQ to JBM all at one time.

Made up Use Case: For instance, your business is selling items, some you make directly and some you farm out to other distributors. Your ordering system is JBossMQ based. Customers place orders that are then queued up to be processed(via JBossMQ). You also use MQ to queue up the orders that you need to produce and you also queue up the orders that will go to your other distributors. You use MDB's in three separate places in your operation. You want to do a staged migration from JBossMQ to JBM. That requires that JBossMQ and JBM work together. This is exactly what the JBM bridge was meant to do. It's meant to take messages from one queue/topic and transfer them to another queue/topic. This helps with the migration by allowing you to pull messages from your JBossMQ queues automatically and push them into your JBM Queues. You can also do the opposite, you can push messages from your JBM system to your JBossMQ system. In our example, we want to replace the ordering side(producer) with JBM. We push messages into the JBM Order queue, but we set the bridge up to send all of those messages to the JBossMQ Order queue. The rest of your processing happens as normal. Lets say you want to leave your ordering system intact, but you want to have JBM and EJB3 MDBs process the orders. You can have your old client put messages in JBossMQ as normal, but you set the bridge up to pull the messages from JBossMQ Order queue and push them into the JBM Order queue.

This allows JBM and JBossMQ to interact together by pushing messages back and forth between different systems.

Assumptions:

1. You have one JBoss instance set up for JBoss Messaging and One Jboss instance set up that has your old JBoss MQ on it.

2. We are copying messages from JBossMQ(Source) to JBM(Target)

Steps to Set up the bridge

Step 1 Copy the jbossmq.jar from the Source Machine(JBossMQ) under the server/default/lib/ to the messaging configuration on the Target JBM machine(server/messaging/lib)

note: substitute what ever your messaging server configuration is above. I used the default stand alone messaging server configuration note: This is required to dereference the JBossMQ objects that are dereferenced on the JBM side. If you don't copy the jar over, you will get a "java.lang.ClassCastException?: javax.naming.Reference" exception and the bridge will not be able to start

Step 2 Add the remote JBossMQ provider to the jms-ds.xml file in the server/messaging/deploy directory on your target(JBM) machine.

Here is an example of the provider to add.

RemoteXAConnectionFactory
org.jboss.jms.jndi.JNDIProviderAdapter

XAConnectionFactory

XAConnectionFactory

XAConnectionFactory

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=192.168.0.199:1099

Please note that you will need to change the java.naming.provider.url so that it points to your JBossMQ machine. Everything else should remain the same. Keep your jms-ds.xml file open, because you will be addning another entry in it for the next step.

Step 3 Add the Bridge provider to the jms-ds.xml file in the server/messaging/deploy directory on your target(JBM) machine.

Here is an example bridge configuration

jboss.messaging:service=JMSProviderLoader,name=MyRemoteJMSProvider
jboss.messaging:service=JMSProviderLoader,name=JMSProvider
/queue/testQueue
/queue/A
0
5
-1
5000
-1
false

Please note that my target is the current JBM JMS Provider and the source is the JBossMQ remote provider. If you have a pretty stock system and you want to move messages from JBossMQ to JBM, you will not have to change this example except for the queue Names. If you wish to move from JBM to JBossMQ, just switch the soure and target definitions.

Start the JBossMQ system and then just start the JBM system and the messages will begin to move over.

Note: I have attached the example jms-ds.xml file that I used for the test. If you want to test the brige first and you have a stock JBM system(JBM has been installed using the default configuration), then you can just copy the jms-ds.xml file over the one in server/messaging/deploy and begin to put messages in the JBossMQ system under the /queue/TestQueue. The messages will then be moved over to your JBM queue /queue/A. Both of these queues exist in the stock versions of JBM and JBossMQ.

Note: You can also merge topics back and forth from JBM to JBossMQ, by setting the subscription name and client id. You can see these arguments in the JBM Bridge information link.

Read full history - Migrating Messages from JBoss MQ to JBoss Messaging

Friday, May 9, 2008

Creating oracle data-source for jboss

To create a data source for the Oracle JDBC driver, edit the jboss.jcml file which is located in the JBoss/conf/ directory. For example:
C:\\jboss\conf\catalina

There is one modification, and one addition to make to this file.

  1. Replace this entry:
        
    org.hsqldb.jdbcDriver

    With this entry:

        
    oracle.jdbc.driver.OracleDriver,org.hsqldb.jdbcDriver

  2. Add the following entry just below the that was just modified. Change the properties of the URL, JDBCUser, and Password to match your database configuration.
                  name="DefaultDomain:service=XADataSource,name=OracleDS">
    OracleDS

    org.jboss.pool.jdbc.xa.wrapper.XADataSourceImpl


    jdbc:oracle:thin:@rcleveng-sun:1521:RCLEVENG

    scott
    tiger
    0
    10

The first modification allows the Oracle JDBC driver to be loaded and thus registered with the JDBC DriverManager class.

The second modification creates a JDBC data source bound to the JNDI name of java:/OracleDS.

Read full history - Creating oracle data-source for jboss

Monday, November 5, 2007

Encryption is not only from plain text to cipher text

The encryption definition you read in the text book, I cant say that is wrong but that is old. Basically what we mean by encryption is change a readble file to unreadable format and in text book you will see plain-text->Cipher-text etc. But have you ever tried to encrypt a binary file. This is not so tough use the same algorithm and it will produce a encrypted file. Try it yourself and if you stuck up do a google and search for the algos and codes. This is very much important for data transferring in this generation through internet. A sample java code is given below, dont copy it ;).



private void doEncryption(final StringfilePath, final String outString,
final byte[] keyBytes) throws EncryptException {
FileOutputStream fos = null;
CipherOutputStream cOut = null;

try {

final File file = new File(filePath);
final byte[] fileByte = getBytesFromFile(file);
final String transformation = EncryptUtilConst.TRANSFORMATION;
final Cipher encrypt = Cipher.getInstance(transformation);

final SecretKeySpec skeySpec = new SecretKeySpec(keyBytes,
EncryptUtilConst.JAR_ENC_ALG);

final byte[] ivByte = new byte[] { (byte) 0x2A, (byte) 0x98,
(byte) 0xB2, (byte) 0xBA, (byte) 0x99, (byte) 0xC0,
(byte) 0xF1, (byte) 0x22, (byte) 0x72, (byte) 0x54,
(byte) 0xBC, (byte) 0xB5, (byte) 0x34, (byte) 0x2F,
(byte) 0xBA, (byte) 0xC4 };

encrypt.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
ivByte));

fos = new FileOutputStream(outString);

cOut = new CipherOutputStream(fos, encrypt);

// Your plaintext MUST be multiple of 16 bytes because NoPadding
// requires your input text
// to be a multiple of block size.
cOut.write(fileByte);

// check for successful encryption of the algorithm
cOut.close();

} catch (Exception e) {
throw new EncryptException(e.getMessage());
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new EncryptException(e.getMessage());
}
}
if (cOut != null) {
try {
cOut.close();
} catch (IOException e) {
throw new EncryptException(e.getMessage());
}
}
}
}
Read full history - Encryption is not only from plain text to cipher text

Tuesday, June 26, 2007

Technolgy mail... All forwarded mails are not garbage

This mail I got from one of my colleague, Kishore. He is working as a TL in our company. Thank him for this, it is really helpful.

Abstract Class A class that does not have objects instantiated from it
Abstraction The identification of the essential characteristics of an item
Aggregation Represents “is part of” or “contains” relationships between two classes or components
Association Objects are related to other objects
Attribute Something that a class knows (data/information)
Cohesion The degree of relatedness of an encapsulated unit (such as a component or a class)
Collaboration Classes work together to fulfill their responsibilities
Composition A strong form of aggregation in which the “whole” is completely responsible for its parts and each “part” object is only associated to the one “whole” object
Concrete class A class that has objects instantiated from it
Coupling The degree of dependence between two items
Encapsulation The grouping of related concepts into one item, such as a class or component
Information Hiding The restriction of external access to attributes
Inheritance Represents “is a”, “is like”, and “is kind of” relationships. When class “B” inherits from class “A” it automatically has all of the attributes and operations that “A” implements (or inherits from other classes)
Multiple Inheritance When a class directly inherits from more than one class
Operation Something a class does
Polymorphism Different objects can respond to the same message in different ways, enable objects to interact with one another without knowing their exact type
Transient object An object that is not saved to permanent storage
Read full history - Technolgy mail... All forwarded mails are not garbage

JAVA pointer ;)

Pointer in java? Some in telling there is no pointer concept in java. Is it so? What is null pointer exception then? Don't tell there is no pointer concept, you can say that java does not provide devs to access memory directly. In java we basically call pointer as reference. More details regarding this,
All variables that refer to objects (values of a class type) are reference variables. They refer to the object indirectly and are implemented with something like a machine address (though it could be more sophisticated). From an implementation viewpoint, objects are just "cells" on the "free store" and are always allocated with the new operator. They are deallocated automatically by the garbage collector when no active variable in the program references them any longer.
Pointer and reference variables give the programmer great flexibility, but they can lead to difficult to find and correct errors in your programs. In this section we will examine the common problems and give hints about how to avoid them. This should be useful to novice Java programmers.
In the following we will suppose the following types and variables
abstract class Animal
{...
}
class Lion extends Animal
{...
}
class Tiger extends Animal
{
public Tiger() {...}
public void growl(){...}
}
Tiger first = null;
Tiger second = new Tiger();
Tiger third;
Dereference null
It is an error to dereference null. This is the safest error to make, since the system will catch the error at run time.
first.growl(); // ERROR, first is null.
A null pointer does not point to anything. Dereferencing obtains the thing the pointer points to. This error is caught and will result in a NullPointerException being thrown. If it not caught the program will be halted with an error message pointing to the line with the error.
Note that
third.growl(); // ERROR, third has not been initialized.
is a different kind of error. We haven't initialized third with any value, not even null. The Java compiler will insist that we initialize each variable before we use it. This error would be caught by the compiler.
Aliasing Problems
Having more than one name for the same cell can also add flexibility to our programs, but there are some dangers. For example, after executing
third = new Tiger();
first = third;
we will eventually want to send messages to the object referred to by first. As long as we are aware that variables third and first reference the same object, all will be well. However, if we send third a message which results in the object changing its internal state, then we need to be aware that these state changes are visible via all variables that reference that object.
This is actually a benefit of object-oriented programming. For example, if you have a vector that contains Tigers and you need to modify a tiger, you don't need to remove it from the vector, then modify it, and then replace it. Any reference to it can be used to modify it and all references will be able to then take advantage of the changes.
Losing Cells
It may be an error to give a new value to a pointer that references an object unless you either first (a) create an alias of the cell, or (b) are willing to abandon the cell.
This is an error that is not caught by the system and may not even be an error, depending on the logic of the program. It simply results in free store cells that are reclaimed by the garbage collector. The program may make no further use of these cells.
second = third; // Possible ERROR. The old value of second is lost.
You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.
first = second;
second = third; //OK
Note that giving second a value in other ways (NULL, new...) is just as much a potential error.
The Java system will throw an exception (OutOfMemoryError) when you call new and the allocator cannot allocate the requested cell.
Note that, from a language point of view, these kind of errors are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them.
Novices often make the following error.
Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.
What you probably meant to say was:
Tiger tony = null;
tony = third; // OK.
Improper Casting
It is illegal to cast a reference variable to a class when the object to which the variable then points is not a member of that class or a subclass. It is illegal to cast a reference to an interface type when the object to which the variable then points does not implement that interface.
It is possible to cast a variable of one reference type to another reference type if the cast is valid. The cast is checked.
Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.
The above is never legal since a Tiger can never refer to a Lion object and a cast doesn't change the type of an object, just affirms that it has a type.
Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.
The first statement above is legal since a variable of a superclass type can refer to a variable of any subclass type. The second is illegal, but won't be caught until runtime (by most compilers) since the compiler may not do enough analysis of the program to determine that whatever isn't a Tiger. The third is legal, but a run time check will be used to verify the fact. The variable whatever really is a Lion.
An improper cast caught at runtime will result in a ClassCastException being thrown.
Read full history - JAVA pointer ;)

Thursday, February 22, 2007

How to download securely from sftp server…


To use java you need some jar files to import.

Go to this url and get the files.

Next step is coding your program.

Go through the code given below,

package test;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import com.sshtools.j2ssh.SftpClient;

import com.sshtools.j2ssh.SshClient;

import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;

import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;

import com.sshtools.j2ssh.configuration.ConfigurationLoader;

import com.sshtools.j2ssh.sftp.FileAttributes;

import com.sshtools.j2ssh.sftp.SftpFile;

public class SFTPTest {

/**

* @param args

* @throws IOException

* @throws JSchException

*/

public static void main(String[] args) throws IOException {

ConfigurationLoader.initialize(true);

String hostname = "192.168.192.14";

// Make a client connection

SshClient ssh = new SshClient();

// Connect to the host

ssh.connect(hostname);

// Create a password authentication instance

PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();

pwd.setPassword("abc123");

pwd.setUsername("abhinaba");

int result = ssh.authenticate(pwd);

if (result == AuthenticationProtocolState.COMPLETE) {

System.out.println("connected");

SftpClient sftp = ssh.openSftpClient();

List fileList = sftp.ls(".");

for (Iterator iter = fileList.iterator(); iter.hasNext();) {

SftpFile file = (SftpFile) iter.next();

FileAttributes fileAttributes = file.getAttributes();

String fileName = file.getFilename();

System.out.println(fileName+" is directory: "+fileAttributes.isDirectory());

if(!fileAttributes.isDirectory()){

try{

sftp.get(fileName,"C:\\Temp\\"+fileName);

}

catch(FileNotFoundException fe){

}

}

}

sftp.quit();

}

ssh.disconnect();

}

}

I think you can understand and write the code now.

Read full history - How to download securely from sftp server…

Featured Video

Featured Article

Poems