Wednesday, December 15, 2004

Sending and receiving objects over an HTTP connection

public static Object sendObject(Object obj) {
URLConnection conn = null;
Object reply = null;
try {
// open URL connection
conn = servletURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches( false );
// send object
ObjectOutputStream objOut = new ObjectOutputStream(
conn.getOutputStream() );
objOut.writeObject( obj );
objOut.flush();
objOut.close();
} catch ( IOException ex ) {
ex.printStackTrace();
return null;
}
// recieve reply
try{
ObjectInputStream objIn = new ObjectInputStream(
conn.getInputStream() );
reply = objIn.readObject();
objIn.close();
} catch ( Exception ex ) {
// it is ok if we get an exception here
// that means that there is no object being returned
if( !(ex instanceof EOFException))
ex.printStackTrace();
//System.err.println("*");
}
return reply;
}

ref: edu.upmc.opi.caBIG.caTIES.client.vr.utils.ncimetasearch.NCIMetaSearchComponent

On the servlet side :

ObjectInputStream objIn = new ObjectInputStream(req.getInputStream()); try { Object obj = objIn.readObject();

ref: edu.upmc.opi.caBIG.caTIES.server.mmtx.MMTxService

Wednesday, November 03, 2004

handling xml from string

u need jaxp.jar for this.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document xmldoc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

Monday, November 01, 2004

Signing your jar files

This is required when you want to deploy your application using webstart.

First step is to have a keystore. The following page describes how to create a self certified keystore.

http://mindprod.com/jgloss/keytool.html

--then you have to use the jarsigner tool

jarsigner -keystore targetFile.jar alias

See the mindprod page for full details

Tuesday, October 05, 2004

Of files and filepaths in Java

This is a major stumbling block for me every time. As I learn new methods I will keep updating .

For now here is the simplest :

FileReader f = new FileReader("tmp.txt");

Now where the hell do u place tmp.txt, you might ask. Well, to find where Java tries to look for tmp.txt, do this

System.out.println(System.getProperty("user.dir");

To open a file relative to the class file location is something that would really help. And it is supposed to work by using class.getClassLoader().getResourceAsStream(), but it didnt work for me, will post as soon as I know how it works.




Thursday, September 30, 2004

Changing name of Popup menu item based on a variable

The name of the menu item in the popup menu depends on the NAME attribute of AbstractAction of that menu item.

When you add some subclass of AbstractAction to the JPopupMenu, you can specify any name to be displayed in the menu by calling super.putValue(NAME, "yourname");

Shown below is an implementation of AbstractAction that does it in the constructor.

public class AddAction extends AbstractAction {

public AddAction(int type)
{
super("Add");

this.type = type;

if(type == 0)
super.putValue(NAME,"Type 0");
else
super.putValue(NAME,"Type 1");
}
}


and add it to the popup menu as follows


JPopupMenu popup = new JPopupMenu();

popup.add(new AddAction(0));
popup.add(new AddAction(1));

here I have added 2 menu items using the same Action but with different names. YOu can ofcourse take different actions based on which menu item is clicked by checking the type in AddAction.


Tuesday, September 28, 2004

Make a Swing component not take up all the space

Most common frustration when designing with Layouts is that your nice pretty layout gets all screwed up because the container panel blows up to take up all the space. Even if you try a setPreferred or setMaximumSize , it seems to have no effect.

A common trick I do to avoid that is to use a wrapperPanel with its layout manager as BorderLayout. and I dump the container panel in the NORTH area of the wrapperPanel.
How BorderLayout works is that, it allocates components in the border's their preferred sizes, and all the rest of the space is filled up by CENTER. So now by adding it to NORTH, the container panel's preferred sizes come in to play, and all left over space is gobbled up by CENTER.

--
When you have a similar problem with the other components, like buttons, text boxes etc, I prefer to use GridbagLayout which automatically assigns the space equivalent to the components preferred sizes. and using GridBagConstraints you can use insets and margins, to your hearts content to layout the components perfectly. Once you understand it , GridBagLayout kicks ass.

With JTree's or I think anything that is within a JScrollPane, adjusting the preferred size of the inner component doesnt have any effect. Adjust the preferred size of the scrollpane to achieve the desired effect.

See Swing, Second Edition by Matthew Robinson, Pavel Vorobiev, published by Manning for a good explanation of GridBagLayout.






Wednesday, September 01, 2004

Accessing a file relative to the class file location

BufferedReader bufferedreader =
new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("filename.txt")));

---------------------
Here filename.txt is assumed to exist in the same directory as the class file.
---------------
gate : edu.upmc.oip.utils.client.dialog.NCIMetaTreeViewerDialog

Monday, August 23, 2004

super() in Java

Dude,

super() has to be the first line in any function you use it in. Period. End of Discussion.

Wednesday, August 18, 2004

Tokenize strings, the StringTokenizer

Notice the different techniques to use tokenizer. StringTokenizer is self - explanatory,
RETokenizer tokenizes on regexs. The one in the example, treats and, AND, or and OR as
delims and also returns the delims as tokens. StringTokenizer doesnot return delims.

----------------------------------------------------------------------------------
String text;
StringTokenizer st = new StringTokenizer(text,",");
-----------
Iterator t = new RETokenizer(s,"\\s(and|AND|or|OR)\\s", returnDelims);
while(t.hasNext())
{
String cs = (String)t.next();

if(!(cs.equalsIgnoreCase(" and ") || cs.equalsIgnoreCase(" or ")))
conditionList.add(cs);
}
----------------------------------------------------------------------------------
ProtocolQuery : edu.upmc.database.SQLStatement

Server Side includes when your server doesnot support it

This works only with HTML. A typical use will be to place some piece of html code at the top of every page on the website, used when you have a menu bar on each page. A big pain is to modify the menu, because you have to go to each and every page and do the changes to make it uniform.

Ofcourse there are other solutions like using frames so that now there is only 1 file to modify.

But what if you dont want to use frames.... Javascript to the rescue.

Use Javascript document.write method to write out the html code to your page. Place this javascript code in a something.js file and include something.js in every page where you want to have that html code present.

Including for javascript is as simple as
<script language="javascript" src="something.js">

I typically write 2 functions in this file, namely writeHeader() and writeFooter(). At the exact location where I want the code to be written I call this function

Example :
<body class="main" onload="MM_preloadImages('images/mmenuhomeon.gif','images/mmenuabouton.gif','images/mmenueventson.gif','images/mmenugovernon.gif','images/mmenubbon.gif','images/mmenulinkson.gif','images/mmenucontactoff.gif')">

<script type="text/javascript">writeHeader()script>

<table width="100%" cellspacing="0" cellpadding="0">
<tr>
...
...
-----------------------------------------------------------------




Of ActionListeners and Popup menus

An example of how to use ActionListeners.
-------------------------------------------

class LoadAction extends AbstractAction {
LoadAction(){
super("Load"); //this is the menu item name in a popup

}

public void actionPerformed(ActionEvent e){
//do what you want to here
}

---------------
JPopupMenu popup = new JPopupMenu();
popup.add(new LoadAction());
---------------

You can also call the Action explicitly by

new LoadAction().actionPerformed(null);

-----

If you need access to members of the parent class pass them to the LoadAction constructor. when you create it.
--------
edu.upmc.opi.spin.client.SpinDataStoreTreeViewer



About this blog

Hi wanderer,

This blog wasnt created for your viewing pleasure. It just contains some random ideas and code snippets that I come across when I am at work. I need a place to store these so that I can get back to them when I need them. So if some posts dont make sense to you at all... well... they weren't meant to.