CS-Java

You can use this reference page as a cheatsheet while programming in java

A bit of Tomcat, a bit of Aspire, and a touch of master pages: and Microsoft Access comes to life. Having developed this simple minded content management system called AKC, when I look back I am given to think how well the web complements even the simplest and readily available of relational database systems. I use this site for my web logging, classified repository of articles, online documentation tool for the open sourced Aspire product, online educational tool for young children, a research aid for new technologies.

Available from IBM IT Skills Development center the following link provides a number of collected articles across the web. I am planning on reading them in my spare time.

See the list of articles.

I must warn you however that there is a couple of years old article from me that made the list. That should make this list suspect to its profoundness :). However there seem to be other topics of weightyness that I feel comfortable with the recommendation.

A computer language must pass its teach-ability test to a middle school-er!!

A construction pattern for dependent objects

java time slice duration performance

I have a medium to a large enterprise. The software we are producing is buggy. It is brittle. It often fails. It is often down. It often allows me to delete things that I shouldn't be able to. It takes too long to respond. It is slow. It gives unexpected results. It doesn't stop me from shooting myself in the foot. Why does this happen and how can I improve the state of code quality in my enterprise?

Notes on jazzy

Be wary of constructors invoking virtual methods directly or indirectly!

Build health monitors into your source code

http://java.sun.com/webservices/docs/1.3/tutorial/doc/WebI18N5.html#wp86518

briefly explains utf-8
Request encoding
Response encoding
JSP encoding

Weird but true

set CMD_LINE_ARGS=
:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs
:doneSetArgs

Concurrency and Hashmaps in Java

Coordinated flight pattern for Objects

19) CVS Notes

29-May-07

Notes to help with CVS

Does a default constructor call the baseclass constructor?

21) Dynamic Proxies

30-Aug-14

Dynamic Proxies

22) Eclipse shortcuts

9-Sep-20

Eclipse shortcuts

Expression language notes

24) Future of IDEs? Eclipse?

14-Jun-17

Future of IDEs? Eclipse?

StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
...write something to out
StringBuffer output = s.getBuffer();

Click on the item above to see more.

Class baseClass;
Class derivedClass;

if (baseClass.isAssignableFrom(derivedClass))
{
     System.out.println(
                 "derviedClass is derived from baseClass"
                 + "or assignable a bit more precisely");
}
1.ctrl-mm to start recording the t-macro
2.ctrl-ms to stop recording the t-macro
3.ctrl-mp to re-play the t-macro

1. ctrl-mr to start a named macro
2. ctrl-ms to stop
3. menu to play
4. ctrl-ml to repeat the last macro

How to explore android source code

Where is the source code web site?
Can I get java source for just the android.jar?
Can I browse sources online?
How can I debug into android java source code from eclipse?

Click on the link above for full details and other helpful links.


public static String getSystemTempDirectory()   
{
    return System.getProperty("java.io.tmpdir");
}
Rough draft sample code

1. How can I enable a site for crawling better?

2. How to use jsp forward?

3. How can I pass parameters to a forward?

4. How can I retrieve parameters from a forward?

5. what is the odd behavior of a request when it is forwarded?

6. Can I forward between two contexts?

7. How to simulate a forward between contexts?


<jsp:forward page="<%=targeturl%>"/>

You need the following jars


jawk.jar
regex12.jar

Write a batch file as follows


set pattern1="abc"
set pattern2="xyz"
set tempfile=c:\temp.txt

dir /b /s c:\dir\*.jsp 
| java com.ai.jawk.CmdSubst @call gres.bat $1 %pattern1% %pattern2% %tempfile% 
> execjsp.bat

@call execjsp.bat

This is what it does

  1. List all jsp files in that directory hierarchy
  2. For each line execute "gres.bat" with 4 arguments
  3. gres.bat replaces patter1 with pattern2 in file $1 which is the first argument from the previous pipe. It uses a tempfile in the process
  4. All the executable commands are collected in "execjsp.bat"
  5. As a final step execute the command
  6. You will have an entire directory/sub-directory worth of files replaced with the pattern

In version 1.2 of the JDK software, you can run JAR-packaged applications with the Java interpreter. The basic command is:

java -jar jar-file

To make this work the jar file must have a manifest identifying the classname to run. Click on the link above to see more details.

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html

A very nice document on the usage and motivations behind assertions in JDK 1.4

how to use thread local in java

While programming in JSF one may need access to the request object and also its attributes. The managed beans of JSF are also available in the request or the session objects. The following utility class allows you work the request object and get to the managed beans directly if the need is there

37) How to work with arrays

29-Aug-14

How to work with arrays

How can I access a local java class or a soap representation of it at run time with out using any stubs. Assuming I have the interface of the class and the domain objects for it.

Need you help. What is a good approach for accessing java interfaces remotely and in a transparent fashion?

What is a good approach for accessing java interfaces remotely? The answer seems too obvious. Use EJB session beans, or web services or RMI. is that the best way? Could I not use dynamic proxies and not use any client side or serverside skeletons and stubs? Can I not do this by not generating any thing? Would some one recommend WSIF to do this? What else is out there?

Phrased differently, if I have a jar file that contains an interface and the domain objects that support that interface, can I access one of its implementations that is sitting on a remote machine using a dynamic proxy. The protocol can be SOAP or EJB or just a plain homegrown over http for that matter.

Stated differently, if I were to implement a service layer using plain java interfaces and implementations, can I break that layer apart at deployment time with out involving any compile time changes. Such an option will give me the ability to multi-tier an application with very little fan fare. Programmers need even not know about SOAP or EJB etc.

For instance WSIF (web services invocation framework) seem to advertise a functionality that is similar in intent. But someone expereienced with WSIT comment on whether all you need is interfaces and domain objects? Also WSDL seem to be necessary for WSIF to work. Can it work with out any xml artifacts and assume a certain SOAP implementation and provide a dynamic proxy for it.

I am hoping someone out there looked into this before and I would like to hear from them. Either you can post the answer here or if you don't have an account, could you email me your opinion? My email is "satya at activeintellect.com".

Thanks in advance for considering this.

Exceptions is one area where opinions differ considerably. Not only about the usage of exceptions but also about the need and utility of checked exceptions. I hear arguments from various sides. They all seem valid in their own right. I use interfaces heavily in my coding practice. Particularly in my J2EE tool Aspire. Over time I paid dearly for not declaring exceptions on these interfaces. Primarily because I would start out thinking that this interface is too simple and not declare an exception. Subsequent implementation of these interfaces will necessitate apis calls that throw checked exceptions. With out changing the interface either I need to throw a converted chained runtime exception or change the interface to include a politically correct middle of the road exceptions suitable for that interface

42) Jar finder: Pretty neat

28-Dec-10

Jar finder

Pretty neat

An example to find org.apache.xpath.XPathAPI.

43) Java and Browsers

23-Dec-10

Java and Browsers

Java API and references 2020

45) Java coding guidelines

4-Oct-14

Java coding guidelines

47) Java enums

6-Jun-14

Java enums

50) Java Logging API Notes

6-Jul-05

Notes on Java JSP Logging APIs

51) Java memory settings

14-Apr-11

Java memory settings

Java string substitution/formatting

/*
 * Created on Oct 1, 2005
 */
package com.ai.typefaces;

import java.util.Iterator;

import com.ai.common.IDictionary;
import com.ai.reflection.BeanInfo;
import com.ai.reflection.BeanInfoRegistry;
import com.ai.reflection.FieldInfo;
import com.ai.reflection.ReflectionException;

/**
 * @author Satya Komatineni
 *
 */
public class TypeFaceFacility implements ITypeFaceFacility 
{
   public Object castTo(Class objectClass, IDictionary dictionary) 
   throws ReflectionException
   {
      //Instantiate the object based on the class
      //instantiate a bean info for this object
      //For each public field infos
      //      get its name
      //      get its value from dictionary
      //      set the value using get or directly on the field info
      // return the object
      BeanInfo bi = BeanInfoRegistry.getBeanInfo(objectClass);
      Object targetObject = bi.constructObject();
      Iterator fieldInfoItr = bi.getFieldInfos();
      while(fieldInfoItr.hasNext())
      {
         //for each field info
         FieldInfo fi = (FieldInfo)fieldInfoItr.next();
         Object fieldValue = dictionary.get(fi.m_name);
         fi.setValueUsingString(targetObject,(String)fieldValue);
      }
      return null;
   }
}
Reflection related sample java code
Static initaliazation

I am able to debug a remote process such as tomcat once the tomcat is running. How can I monitor the tomcat when it is starting up?

This is necessary to observe the behavior of startup servlets.

Or is there any way to launch a remote debugging program while it is being observed?

Description to be entered

62) Jaxb 2.0 tutorial

15-Jun-17

Goal

  1. Realize the reflection based architecture of Jaxb
  2. Plan a sample project for exercising Jaxb
  3. Prerequisites
  4. Resources and how best to use them

Reflection based architecture

jaxb 2.x architecture supports metadata based marshalling and unmarshalling of xml. This makes xsd optional unlike the jaxb 1.x architecture

Tutorial Project

The project is a simple project where an xml file is marshalled and unmarshalled using jaxb 2.x. All of the files needed to accomplish this are provided on the right hand side of the menu.

http://jtds.sourceforge.net/

Microsoft jdbc driver seem to be extreemly slow. This is an alternative

65) JDK 1.4 Features

2-Dec-03

http://java.sun.com/j2se/1.4.2/docs/relnotes/features.html

Summary of New Features and Enhancements

Important day to day programming features 1

Logging API
Assertions
Preferences
Chained Exceptions
Collections
Regular Expressions

Next set of Important features

JDBC 3.0
Java Web Start
Endorsed Standards Override

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html

Very detailed article on sun site about various guidelines on using Java assertions.

http://www-106.ibm.com/developerworks/java/library/j-prefapi.html?ca=dgr-lnxw01PrefAPI

Emphasis on storing objects
Very good set of references
But does not cover the implementation available for a given preference api

http://java.sun.com/features/2003/05/bloch_qa.html

New Language Features for Ease of Development in the Java 2 Platform, Standard Edition 1.5: A Conversation with Joshua Bloch

Discusses

Generics
Enhanced for loop
Autoboxing/unboxing
Typesafe enums
static import
Metadata

70) json and java

12-Aug-20

json and java

These notes illustrate an interesting way of developing and using capture tags in jsp to accomodate masterpages or tiles. This specific example talks about how this is done in AspireWeb but the ideas can be easily extended to any java based server side framework.

The notes will explore a) how to define a jsp page in response to an incoming url in an MVC fashion b) it then goes into identifying a tiles or masterpage pertaining to that URL c) an example of the master page d) an example of the jsp page with capture tags e) the resulting out put combining the master page and the url specific jsp page. f) what the incoming url will look like

72) jsp caching expire tag

28-Jul-09

jsp caching expire tag

73) JSP Notes

4-Mar-06

Notes to help with JSP

74) Language files

11-May-19

Language files

75) Life and Careers

26-May-12

Life and Careers

How to get a list of files from a directory


/*
********************************************************
* GetFiles
********************************************************
*/
List FileUtils.GetFiles(String directory)
{
	File dir = new File(directory);
	return ConvertArrayToList(dir.list());
}

Multiple class inheritance in Java

78) On Guava

14-Jun-17

On Guava

Pattern of constraining an object construction

http://java-virtual-machine.net/tech-faq.html

jdk 1.2.2 earlier versions won't run with pentium 4
Requires bug fixes for 1.2.2
Problem with the jit
You can disable it by deleting the symcjit.dll 
from the jre bin directory.

82) Questions on WSAD

30-Aug-04

Enabling target servers in WSAD

  1. Switch to J2EE perspective
  2. Go to window/preferences
  3. Choose J2EE
  4. Look for Server Targeting Support
  5. Pick an option you like (enable or disable)

Wonder if you have come across these lines before:

"I fix myself an Omelete, sir,
Of fluffy clouds, and sky
...
I sew myself a warm cloak, sir,
of hope and daffodils."

Unlike this fanciful dilemma of "Poor Angus" of Shel Silverstein, in large IT corporations HTML prototypes can play a much more significant role. They can aid faster development times. They can secure budgets. They can encourage good architecture. They can directly lead to a number of development artifacts such as data models, and business services. I think prototypes offer another important aspect to the modern development process along with the Extreme Programming and RUP.

84) Regex XRef

1-Sep-20

Regex XRef

Research notes on Master Data Management, Common Data Models, Customer Data hubs.

86) Sample code for arrays

27-Jun-09

Sample code for arrays


   public static String htmlEncode(String inHtmlString)
   {
	   String fromCharString="<>&";
	   String[] toStringArray = { "&lt;", "&gt;", "&amp;" };
	   return encode(inHtmlString, fromCharString, toStringArray);
   }

Escape Special Characters from Java Best Practices

Description to be entered

89) Security Notes

23-Jun-05

Dealing with webservices, http, and application security in general
public class SingleFileUploadPart extends ATurbinePart
{
      protected Object execute(String requestName, RunData rundata, Map inArgs)
         throws RequestExecutionException
      {
         try
         {
            String fileuploadFieldName = AppObjects.getValue(requestName + ".fileUploadFormFieldName","filename");
            FileItem fi = rundata.getParameters().getFileItem(fileuploadFieldName);
            //Get file item details
            String fiName = fi.getName();
            String fiFileName = fi.getFileName();
            long fiSize = fi.getSize();

            inArgs.put("fileitem_name",fiName);
            inArgs.put("fileitem_filename",fiFileName);
            inArgs.put("fileitem_size",Long.toString(fiSize));

            String targetFilename = AppObjects.getValue(requestName + ".targetFilename_WS");
            String finalFilename = SubstitutorUtils.generalSubstitute(targetFilename,inArgs);
            String fullFilename = com.ai.common.FileUtils.translateFileName(finalFilename);

            fi.write(fullFilename);
            return fullFilename;
         }
         catch(ConfigException x)
         {
            throw new RequestExecutionException("Error:Config error",x);
         }
         catch(Exception x)
         {
            throw new RequestExecutionException("Error:filewrite error",x);
         }

      }//eof-method
}//eof-class

So where are the java clouds

Description to be entered

94) Struts questions

8-May-06

Description to be entered

95) Taglib examples

10-Nov-05

Taglib examples

http://java.sun.com/docs/books/effective/toc.html

For a quick run down of the principles as laid out by Joshua Bloch

In bouts of romanticism (I am prone) and expediency I do like type less languages, but for maintenance and sure-footing and transparency typed languages like Java, when paired (may-be-must) with a right tool like eclipse, are a pleasure to program in.

There will be times in the near future one may be able to see objects as both typed or open ended structures (such as type less arrays) to provide just-in-time objects.

Understand javax.activation.DataSource etc...

Description to be entered
private int getNumberOfParameters(String ps)
   {
   		int count=0;
   		StringCharacterIterator sci = new StringCharacterIterator(ps);
   		for(char c=sci.first();c != CharacterIterator.DONE; sci.next())
   		{
   			if (c == '?')
   			{
   				count++;
   			}
   		}
   		return count;
   }//eof-function

walking through java enumeration

What are the Java projects in Apache?

what does Azure has for Java?

What is a static java class?

107) What is a weak reference?

14-Aug-12

What is a weak reference?

108) What is Refinery CMS?

19-Jun-12

What is Refinery CMS?

109) What is Stripe?

19-Jun-12

What is Stripe?

Description to be entered

What is the state of Java Serialization in Java 8 and up?

What is volatile in Java?

113) Whats up with Cloud IDEs?

17-May-12

Whats up with Cloud IDEs?

whats up with go?

For some time now Java compilers allow you indicate some methods in your class definition as overridden methods.

You do this by annotating the method signature with a code snippet such as


@Override
public void somemethod(){}

By doing so you tell the compiler to see if this annotated method exists in base classes or in the inheritance hierarchy. If it is, nothing happens. If it isn't you, the programmer, have made a mistake, because you expected it to be there. So perhaps misspelled it.

In JDK 1.5 this annotation will throw an error if the method is abstract in the base class.

Either it is corrected or deemed more useful in later JDKs and you can now safely provide this annotation on methods whose baseclass representations are abstract.

this annotation will also guard against some of the base class changes where a method is removed which is overridden in derived classes. You now will know that that happened.

this protection is especially important in frameworks where lot of callbacks are used like the container managed Android components.

bottom line, say @override if you expect this method to be in the base class and you are overriding it.

116) Whats up with OpenData?

17-May-12

Whats up with OpenData?

Majority of the JSF controls have a "rendered" property. If you set this to false, then that component and its children JSF components will not be rendered. Here is an example

Why is it not a bad idea to delete things at garbage collection time!

119) windows azure cloud

7-Jun-12

windows azure cloud

Working with date and time

121) Working with JUnit

12-Aug-20

Working with JUnit

working with regular expressions in Java

Aspire, the product that I developed over the last few years while I was working with java, servlets, jsp and XML, is being used on some SBIR projects involving JetSpeed and a few other open source tools. I have got a call the other day indicating that one of the forms is not accepting Vietnamese input. They are getting invalid characters placed into the MySQL database. The usage is pretty straight-forward. The user will see a form in a browser and will proceed to type Vietnamese (copy/paste perhaps from a Vietnamese app). This form will then be submitted to the server. The server is expected to parse the form input into parameters. Mahaveer suggested that perhaps I should be using some kind of character encoding to retrieve the parameters.

when it comes to complicated things such as setting digital watches, programming vcrs, ordering a sub for your spouse (Who always has a very discriminating taste), ordering at a local McDonalds drive through, self checkouts at Home Depot, and ofcourse software, I am a minimalist. If something is not hampering my imagination and productivity I usually don't upgrade. To exaggerate and make a point, I would be quite happy with windows 95, Tomcat 1.x, Frontpage, Jbuilder 3 for developing server side java applications that run in any container while David prods me all the time to upgrade to XP and how wonderful it is. (you can tell I am relegated to the auto pilot windows world). Anyway having made the point I still compile Aspire with servlets 2.1 although the current release may be at 2.4. Not that I don't like the new stuff in this particular instance but I want to be as backward compatible as possible as long as it is not crippling my style :-). For the curious I did upgrade to XP because I needed a better photo printing software.

Any way back to the encoding issue. I don't remember seeing any encoding issues while trying to read form submission parameters before. I remember porting one of our web sites to Japanese with out any problem last year. Based on that assumption I have advised Mahaveer that it should not be a problem and servlets probably will figure out the necessary details to retrieve the parameters. Ofcourse I am proven wrong.

Both of the following do the same

Option1

Given the following String somestring; void dosomething(){}

Consider the following code


if (somestring!=null&&!"".equals(somestring))
{
	//if the string is not empty
	dosomething();
}

Option 2

Create a function as follows


boolean isValid(String somestring)
{
	if (somestring == null) 
	{
		//the string is null. so it is not a valid string
		return false;
	}
	
	//the string is not null
	
	//eliminate empty characters at both ends
	String newstring = somestring.trim();
	if (newstring.equals(""))
	{
		//the string is an empty string
		//an empty string is (not) valid
		return false;
	}
	
	//it is a valid string because it is not null, it is not empty
	return true; 
}

Then you can do


if (isValid(somestring))
{
	//if the string is not empty
	dosomething();
}

To contrast


if (somestring!=null&&!"".equals(somestring))
{
	//if the string is not empty
	dosomething();
}

if (isValid(somestring))
{
	//if the string is not empty
	dosomething();
}

These days j2ee applications can be developed with out necessarily resorting to writing servlets. On the easiest of the paths one can use just JSPs to write their applications. Or if one were to use servlet controllers then also one rarely needs to write a servlet. Nevertheles even in those cases you have no servlets of your own other than what the frameworks provide, you may want to make sure certain parts of your application is initialized prior to accepting any requests from the clients. The following sample code will give you everything you need to do this quickly.

See instructions from Chris Adamson...

Copied and posted here by Satya Komatineni

Originally by Chris Adamson...

Copied and posted here by Satya Komatineni

Originally by Chris Adamson...

Copied and posted here by Satya Komatineni

Originally by Chris Adamson...

Copied and posted here by Satya Komatineni

Originally by Chris Adamson...

Copied and posted here by Satya Komatineni

Originally by Chris Adamson...

Copied and posted here by Satya Komatineni


@rem mystartup.bat
@set CATALINA_HOME=w:\satya\i\tomcat5028
@set JAVA_HOME=c:\java142
@set exe=%CATALINA_HOME%\bin\catalina.bat
@call %exe% run %1 %2 %3 %4
Description to be entered

How can I start and stop servers?

1. Web project is already there

2. The source code is assuming a different project context

3. How do you change the context name and also the directory of the context