Archive

Posts Tagged ‘java’

Redirecting permanently in HttpServlet from your old domain (website) to new domain

November 29th, 2009 Karthikeyan C No comments

Let us assume we face a scenario where we move from a old domain (website) to a new domain (website). You may do this when you expand your business offering and the old name may not be appropriate.

But your old domain has gained reputation (like a good page rank and a number of incoming links) which you wish to carry forward to your new domain. One way of doing this is respond with HTTP code 301 which is permanently moved.

You may also make use of use Google web master tools to inform the change in domain address (as Google is currently the #1 search engine ). This will prevent the decrease in hits to your website from search engines.

The below code shows how to implement it if you host a Java web application for your old domain.

In web.xml make the below entry.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <servlet-name>RedirectionServlet</servlet-name>
 <servlet-class>com.olddomain.web.servlet.RedirectionServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>RedirectionServlet</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
 </web-app>

Next the code for RedirectionServlet.java


package com.olddomain.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RedirectionServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

 //Get the incoming URL request.
 response.setHeader("Location", "http://www.yournewdomain.com"+request.getRequestURI());
 response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
 }

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 processRequest(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 processRequest(request, response);
 }
}

Note: Using response.sendRedirect will produce only HTTP status code 302 which is temporarily moved and not 301 which indicates it is permanently moved.

  • Share/Bookmark

For Beginners – Java file to convert XML Document to String representation

November 17th, 2009 Karthikeyan C No comments

The below Java file shows how to create a XML Document, append Elements to it and finally convert the XML Document to String representation. I am posting this as I noticed many of the  developers in my team were using StringBuffer (or StringBuilder) to create the String representation of the XML.


import java.io.StringWriter;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Class to construct string representation of XML rather than using StringBuffer or  StringBuilder  which is cumbersome.
 *
 */
public class XMLStringCreator {

 private Document document = null;

 public XMLStringCreator() throws ParserConfigurationException {
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 document = builder.newDocument();
 }

 /**
 * Creates an xml element with the details passed.
 * @param elementName XML element name
 * @param textNodeValue null if there is no text node value to be associated.
 * @param attributesNameValueMap should pass null or an empty Map if no attributes
 * @return The XML Element with attributes specified (if any)
 */
 public Element createElement(String elementName, String textNodeValue, Map<String, String> attributesNameValueMap) {
 Element element = document.createElement(elementName);

 if (textNodeValue != null) {
 element.appendChild(document.createTextNode(textNodeValue));
 }

 if (attributesNameValueMap == null || attributesNameValueMap.size() == 0) {
 return element;
 } else {
 return addAttributes(element, attributesNameValueMap);
 }//eof else

 }

 /**
 * This method should be called only once. Its the responsibility of the caller to ensure this.
 * @param root The root xml element
 */
 public void addRootElement(Element root) {
 document.appendChild(root);
 }

 /**
 * Appends child to parent xml element (or node)
 * @param parent The parent XML element
 * @param child The child xml element
 */
 public void addChild(Element parent, Element child) {
 parent.appendChild(child);
 }

 /**
 * returns the XML string constructed so far with the other methods of this class.
 * @return xml string representation.
 * @throws Exception
 */
 public String getXMLString() throws Exception {
 StringWriter writer = new StringWriter();
 Result result = new StreamResult(writer);
 Transformer transformer = TransformerFactory.newInstance().newTransformer();
 transformer.transform(new DOMSource(document), result);
 return writer.toString();
 }

 /**
 * Adds attributes to XML element
 * @param element
 * @param attributesNameValueMap
 * @return The xml element with the attributes.
 */
 private Element addAttributes(Element element, Map<String, String> attributesNameValueMap) {

 for (String key : attributesNameValueMap.keySet()) {
 element.setAttribute(key, attributesNameValueMap.get(key));
 }//eof for loop

 return element;
 }

 @Override
 public String toString(){
 throw new UnsupportedOperationException("Please use the method getXMLString instead");
 }

}
  • Share/Bookmark
Categories: Development Tags: ,

“Internet Explorer Cannot Download” Error Message When You Use HTTPS URL

November 16th, 2009 Karthikeyan C No comments

Internet Explorer will not display attachments when HTTPS is used. This bug has been documented in the link below.

http://support.microsoft.com/kb/812935/

If  the development environment is not using HTTPS this issue will be
identified only at a later stage when we move on to integration testing
environment where we normally use HTTPS.

The following are the steps to be followed for the workaround.

1. In the Servlet code please use the below snippet.


response.reset();
//If the report type is other than PDF handle accordingly]
response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment; filename=Report.pdf");

//pragma can be set to other available options also.
response.setHeader("Pragma", "public");
response.setHeader("Cache-control", "max-age=30");
//The logic to write into the OutputStream goes here.

Note: The reset of HttpServletResponse is very important.

Following are to be ensured on the browser (client).

1. Ensure Do not save encrypted pages to disk check box is not selected in Internet Explorer.

2.  Incase of IE 7, ensure the automatic prompting for downloads is enabled
under Tools–>Internet Options–>Custom Level –> Downloads.

  • Share/Bookmark
Categories: Development Tags: