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

May 21, 2008

Access HTTPS in Java

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

1. First of all you copy the URL that you are connecting to and paste it in your browser. Let us say you are using IE. Just paste the url in the address bar and press enter.

2. You will now probably see a dialog box warning you about the certificate. Now click on the 'View Certificate' and install the certificate. Ignore any warning messages.

3. Now that the server certificate is installed in your computer, your browser will not warn you when you visit the same site again. But however your JRE dumb as it is does not yet know about this certificate's existence until you add it to its keystore. Usually you will use the keytool to manage certificates. Keytool is a command-line utility with numerous arguments that allow you to create and manage keystores for housing digital certificates. For the complete documentation of keytool,http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html

4. You can list the current certificates contained within a keystore using they keytool -list command. The initial password for the cacerts keystore is changeit. For example:

    C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts

    Enter keystore password: changeit

    You will then see the something like this:

    Keystore type: jks

    Keystore provider: SUN

    Your keystore contains 11 entries:

    engweb, Wed Apr 11 16:22:49 EDT 2001, trustedCertEntry,

    Certificate fingerprint (MD5): 8C:24:DA:52:7A:4A:16:4B:8E:FB:67:44:C9:D2:E4:16

    thawtepersonalfreemailca, Fri Feb 12 15:12:16 EST 1999, trustedCertEntry,

    Certificate fingerprint (MD5): 1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9

    thawtepersonalbasicca, Fri Feb 12 15:11:01 EST 1999, trustedCertEntry,

    Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41

    verisignclass3ca, Mon Jun 29 13:05:51 EDT 1998, trustedCertEntry,

    Certificate fingerprint (MD5): 78:2A:02:DF:DB:2E:14:D5:A7:5F:0A:DF:B6:8E:9C:5D

    thawteserverca, Fri Feb 12 15:14:33 EST 1999, trustedCertEntry,

    Certificate fingerprint (MD5): C5:70:C4:A2:ED:53:78:0C:C8:10:53:81:64:CB:D0:1D

    thawtepersonalpremiumca, Fri Feb 12 15:13:21 EST 1999, trustedCertEntry,

    Certificate fingerprint (MD5): 3A:B2:DE:22:9A:20:93:49:F9:ED:C8:D2:8A:E7:68:0D

      verisignclass4ca, Mon Jun 29 13:06:57 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 1B:D1:AD:17:8B:7F:22:13:24:F5:26:E2:5D:4E:B9:10

      verisignclass1ca, Mon Jun 29 13:06:17 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 51:86:E8:1F:BC:B1:C3:71:B5:18:10:DB:5F:DC:F6:20

    verisignserverca, Mon Jun 29 13:07:34 EDT 1998, trustedCertEntry,

    Certificate fingerprint (MD5): 74:7B:82:03:43:F0:00:9E:6B:B3:EC:47:BF:85:A5:93

    thawtepremiumserverca, Fri Feb 12 15:15:26 EST 1999, trustedCertEntry,

    Certificate fingerprint (MD5): 06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A

    verisignclass2ca, Mon Jun 29 13:06:39 EDT 1998, trustedCertEntry,

    Certificate fingerprint (MD5): EC:40:7D:2B:76:52:67:05:2C:EA:F2:3A:4F:65:F0:D8

5. Now you have to add the previosly installed certificate to this keystore. To add, begin by exporting your CA Root certificate as a DER-encoded binary file and save it as C:\root.cer. (you can view the installed certificates under Tools->'Internet Options' ->Content->Certificates. Once you open the certificates, locate the one you just installed under 'Trusted Root Certification Authorities". Select the right one and click on 'export'. You can now save it (DER encoded binary) under your c: drive.

6. Then use the keytool -import command to import the file into your cacerts keystore.

For example:-alias myprivateroot -keystore ..\lib\security\cacerts -file c:\root.cer

Enter keystore password: changeit

Owner: CN=Division name, OU=Department, O=Your Company, L=Anytown,

ST=NC, C=US, EmailAddress=you@company.com

Issuer: CN=Division name, OU=Department, O=Your Company, L=Anytown,

ST=NC, C=US, EmailAddress=you@company.com

Serial number: 79805d77eecfadb147e84f8cc2a22106

Valid from: Wed Sep 19 14:15:10 EDT 2001 until: Mon Sep 19 14:23:20 EDT 2101

Certificate fingerprints:

MD5: B6:30:03:DC:6D:73:57:9B:F4:EE:13:16:C7:68:85:09

SHA1: B5:C3:BB:CA:34:DF:54:85:2A:E9:B2:05:E0:F7:84:1E:6E:E3:E7:68

Trust this certificate? [no]: yes

Certificate was added to keystore

7. Now run keytool -list again to verify that your private root certificate was added:

    C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts

You will now see a list of all the certificates including the one you just added.

This confirms that your private root certificate has been added to the Extranet server cacerts keystore as a trusted certificate authority.

May 21, 2007

JSF Overview

What is JSF?

JSF is new standard framework , developed through Java Community Process (JCP) , that makes it easy to build user interfaces for java web applications by assembling reusable components in a page.

JSF includes mainly:

  1. Set of APIs to represent and manage state of components that helps server side validation, event handling, page navigation, data conversion etc.
  2. JSP custom tag library to create UI components in a view page.
Goal of JSF is to create web applications faster and easier.

Conclusion:
JSF is a framework, that makes its easy to build user interfaces for java web applications by assembling reusable components in a page.

Java Overview

What's Java?
  1. Java is an object-oriented applications programming language developed by Sun Microsystems in the early 1990s.
  2. Java applications are typically compiled to bytecode, although compilation to native machine code is also possible.
  3. At runtime, bytecode is usually either interpreted or compiled to native code for execution.
History
  1. Java started as a project called "Oak".
  2. The first public implementation was Java 1.0 in 1995.
  3. 2006, Sun released parts of Java as free/open source software, under the GNU General Public License (GPL)
Features
Java=> Java bytecode: portable
Java=>Native code: fast
Java=> Java bytecode: JIT compilation and dynamic recompilation allow Java programs to take advantage of the speed of native code without losing portability.
  • Automatic garbage collection

Extensions and related architectures

  • Java EE (previously J2EE) (Java Platform, Enterprise Edition—for distributed enterprise applications)
  • Java ME (previously J2ME) (Java Platform, Micro Edition—for PDAs and cellular phones)
  • JMF (Java Media Framework)
  • JNDI (Java Naming and Directory Interface)
  • JSML (Java Speech API Markup Language)
  • JDBC (Java DataBase Connectivity)
  • JDO (Java Data Objects)
  • JAI (Java Advanced Imaging)
  • JAIN (Java API for Integrated Networks)
  • JDMK (Java Dynamic Management Kit)
  • Jini (a network architecture for the construction of federated distributed systems)
  • Jiro
  • Java Card (Java for smart cards)
  • JavaSpaces
  • JML (Java Modeling Language)
  • JMI (Java Metadata Interface)
  • JMX (Java Management Extensions)
  • JSP (JavaServer Pages)
  • JSF (JavaServer Faces)
  • JNI (Java Native Interface)
  • JXTA (Open Protocols for Peer-to-Peer (P2P) Virtual Network)
  • Java 3D (A high level API for 3D graphics programming)
  • JOGL (Java OpenGL—A low level API for 3D graphics programming, using OpenGL)
  • LWJGL (Light Weight Java Game Library—A low level API providing access to OpenGL, OpenAL and various input devices)
  • OSGi (Dynamic Service Management and Remote Maintenance)
  • JMonkey Engine (High performance scene graph based 3D engine)

May 16, 2007

Solving the error EJB with JBoss 4.04

Solved it with the following 3 steps:
1] Edit conf/jboss-service.xml and make CallByValue as 'true' in NamingService as below

name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
true


2] Edit deploy/ear-deployer.xml, and set Isloated and CallByValue as true

3]Edit deploy\jbossweb-tomcat55.sar\META-INF\jboss-service.xml , and set Java2ClassLoadingCompilance and UseJbossWebLoader attributes as false

May 15, 2007

What is difference between Application server with Web server

A web server is a server designed to communicate with a web browser. Content includes text-based two-way communication with most of the com going from server to client. Data consists of text, formatting, graphics, sounds, and dynamic content.

An application server can be of several designs, but is basically a synchronous two-way sever that provides access to a single application shared among users through web-based or proprietiary methods. The content consists of data types, app commands, system commands, and data of complex types.

Typically, an app server provides a web-based platform for access to a database-driven application.

Apr 25, 2007

Auto-encodes session IDs in URL

Blarg #22: A Filter that auto-encodes session IDs on relative page links.
Posted by jfalkner on March 27, 2006 at 10:43 PM | Comments (3)

This is an example Filter that auto-encodes all relative links on a website using the HttpServletResponse.encodeURL() method. It was originally encoded as an example during a Develop Mentor course I taught. It is a nice example of a servlet filter that buffers a response, locates links using a simple regular expression, and replaces links with encoded links.

The code. Remember each filter has three parts: the Filter, ServletResponseWrapper, and ServletOutputStream sub-class.

* EncodeSessionInURLFilter.java
* EncodeSessionInURLResponseWrapper.java
* EncodeSessionInURLResponseStream.java

EncodeSessionInURLFilter.java

This filter does nothing more than wraps the HttpServletResponse in order to buffer text sent out to a client.

package example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EncodeSessionInURLFilter implements Filter {
ServletContext sc = null;

public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// check that it is a HTTP request
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

// nonce encode the normal output
EncodeSessionInURLResponseWrapper wrappedResponse = new EncodeSessionInURLResponseWrapper(
response, sc);

// make sure a session exists
HttpSession session = request.getSession(true);

chain.doFilter(req, wrappedResponse);
// finish the respone
wrappedResponse.finishResponse();
}
}

public void init(FilterConfig filterConfig) {
// reference the context
sc = filterConfig.getServletContext();
}

public void destroy() {
// noop
}
}


EncodeSessionInURLResponseWrapper.java

This wrapper sends back a custom ServletOutputStream object in order to buffer all text that is being sent to the client.

package example;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EncodeSessionInURLResponseWrapper extends HttpServletResponseWrapper {
protected HttpServletResponse origResponse = null;
protected ServletOutputStream stream = null;
protected PrintWriter writer = null;
ServletContext sc;

public EncodeSessionInURLResponseWrapper(HttpServletResponse response, ServletContext sc) {
super(response);
this.sc = sc;
origResponse = response;
}

public ServletOutputStream createOutputStream() throws IOException {
return (new EncodeSessionInURLResponseStream(origResponse, sc));
}

public void finishResponse() {
try {
if (writer != null) {
writer.close();
} else {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {}
}

public void flushBuffer() throws IOException {
stream.flush();
}

public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called!");
}

if (stream == null)
stream = createOutputStream();
return (stream);
}

public PrintWriter getWriter() throws IOException {
if (writer != null) {
return (writer);
}

if (stream != null) {
throw new IllegalStateException("getOutputStream() has already been called!");
}

stream = createOutputStream();
// BUG FIX 2003-12-01 Reuse content's encoding, don't assume UTF-8
writer = new PrintWriter(new OutputStreamWriter(stream, origResponse.getCharacterEncoding()));
return (writer);
}

public void setContentLength(int length) {}
}


EncodeSessionInURLResponseStream.java

This response stream buffers all text that is send to the client and uses a regular expression to locate and replace links with encoded links.

package example;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.*;
import javax.servlet.http.*;

/**
*
* @author Jayson Falkner - jayson@jspinsider.com
*/
public class EncodeSessionInURLResponseStream extends ServletOutputStream {
// abstraction of the output stream used for compression
protected OutputStream bufferedOutput = null;

// state keeping variable for if close() has been called
protected boolean closed = false;

// reference to original response
protected HttpServletResponse response = null;

// reference to the output stream to the client's browser
protected ServletOutputStream output = null;

// default size of the in-memory buffer
private int bufferSize = 50000;

ServletContext sc;

public EncodeSessionInURLResponseStream(HttpServletResponse response, ServletContext sc) throws IOException {
super();
closed = false;
this.sc = sc;
this.response = response;
this.output = response.getOutputStream();
bufferedOutput = new ByteArrayOutputStream();
}

public void close() throws IOException {
// make up a nonce
String nonce = Integer.toString((int)(Math.random()*Integer.MAX_VALUE));
// set the nonce in app scope
sc.setAttribute("nonce", nonce);

// get the content
ByteArrayOutputStream baos = (ByteArrayOutputStream) bufferedOutput;

// make a string out of the response
String pageText = new String(baos.toByteArray());

// use regex to find the links
Pattern p = Pattern.compile(" href=\"[^\"]*|action=\"[^\"]*");
Matcher m = p.matcher(pageText);

String newText = "";
int offset = 0;
while (m.find(offset)) {
// update the text
newText += pageText.substring(offset, m.start());
// update the offset
offset = m.end();
// get the matching string
String match = pageText.substring(m.start(), m.end());
// get the URL
String[] split = match.split("\"");
String url = split[1];
// encode the match
String encoded = response.encodeURL(url);

// add the match to the new text
newText += split[0]+"\""+encoded;
}
// add the final text
newText += pageText.substring(offset, pageText.length());



// set appropriate HTTP headers
// response.setContentLength(compressedBytes.length);
output.write(newText.getBytes());
output.flush();
output.close();
closed = true;

}

public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
bufferedOutput.flush();
}

public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the byte to the temporary output
bufferedOutput.write((byte) b);
}

public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}

public void write(byte b[], int off, int len) throws IOException {
System.out.println("writing...");
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the content to the buffer
bufferedOutput.write(b, off, len);
}

public boolean closed() {
return (this.closed);
}

public void reset() {
//noop
}
}
in web.xml
<filter>
<filter-name>CookieSessionFilter</filter-name>
<filter-class> net.kokolink.zimbra.controller.EncodeSessionInURLFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CookieSessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

Apr 24, 2007

Handle duplicate form submission

Handle duplicate form submission
The problem of duplicate form submission arises when a user clicks the Submit button more than once before the response is sent back or when a client accesses a view by returning to a previously bookmarked page. This may result in inconsistent transactions and must be avoided. In our sample application, a similar problem will arise if the customer clicks the submit button more than once while submitting the purchase order.

In Struts this problem can be handled by using the saveToken() and isTokenValid() methods of Action class. saveToken() method creates a token (a unique string) and saves that in the user's current session, while isTokenValid() checks if the token stored in the user's current session is the same as that was passed as the request parameter.

To do this the JSP has to be loaded through an Action. Before loading the JSP call saveToken() to save the token in the user session. When the form is submitted, check the token against that in the session by calling isTokenValid(), as shown in the following code snippet:

Listing 3: Using saveToken() and isTokenValid()

public class PurchaseOrderAction extends DispatchAction

{

public ActionForward load(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception

{

try

{ //save the token

saveToken(request)



// rest of the code for loading the form

}

catch(Exception ex){//exception}

}



public ActionForward submitOrder(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception

{

try

{

// check the token. Proceed only if token is valid

if(isTokenValid(request,true)) {

//implement order submit functionality here

} else {

return mapping.findForward("failure");

}

}

catch(Exception ex){//exception}

}

}
Add this to jsp if you don't use <html:form> to enable store token on jsp
<input type="hidden" name="<%=Constants.TOKEN_KEY %>" value="<%=session.getAttribute(Globals.TRANSACTION_TOKEN_KEY) %>">

Apr 11, 2007

Configure Java with Firefox

ln -s /usr/java/jdk1.5.0_06/jre/plugin/i386/ns7/libjavaplugin_oji.so /usr/local/firefox/plugins/