Thursday, 23 January 2014

Unknown

How To Implements Https in java web applications


First Way
  • First of all you need to enable SSL for your server. For Tomcat you need to generate an openSSL keystore and add the following connector to server.xml:
    <Connector port="8443" scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="mykeystore" sslProtocol="TLS"
       keystorePass="keystore password" />
  • To integrate SSL into your application I recommend Spring Security. It offers exactly what you want (login over HTTPS, then redirected to HTTP). All you have to do to implement it, is to set forceHTTPS to true:
    <bean id="authenticationProcessingFilterEntryPoint"
    class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
      <property name="loginFormUrl" value="/pages/login.jsp" />
      <property name="forceHttps" value="true"/>
    </bean>
  • Of course Spring and Spring security do have a rather steep learning curve, but it is totally worth it. Do it once and then you can apply it to new apps in less than an hour. You can use Spring Security in both the Spring and Struts application.
Second Way:

<http auto-config="true">
<form-login login-page="/login.jsp" />
<port-mappings>
<port-mapping http="8080" https="8443"/>
</port-mappings>

<intercept-url pattern="/login**" access="IS_AUTHENTICATED_ANONYMOUSLY" requires-channel="https"/>
<intercept-url pattern="/j_spring_security_check" access="IS_AUTHENTICATED_ANONYMOUSLY" requires-channel="https"/>
<intercept-url pattern="/*.do" requires-channel="any" access="ROLE_USER"/>

<logout />
</http>
Read More
Unknown

The downside or disadvantages of using HTTPS

The increased security that HTTPS brings might suggest that it should be used as a matter of course, but there are drawbacks that must be considered.



  • Pages accessed by HTTPS can never be cached in a shared cache. Since the conversation between browser and server is encrypted, intermediate caches are unable to see the content to cache it. Worse, some browsers will not even cache HTTPS documents in their local per-user caches. Worse still, since it is dangerous to mix HTTPS and HTTP content on the same page (there are some scripting attacks that can allow a script in one component of a page to read data from another), even embedded icons and pictures have to travel encrypted and therefore can not be cached. The lack of local caching can lead to problems in Internet Explorer that can make it impossible to save documents to disk or to open them in external applications (see for example http://support.microsoft.com/kb/812935)
  • The encryption/decryption represents a computation overhead for both server and browser. Most modern client systems will probably not notice this, but on a busy server handling multiple simultaneous HTTPS connections this could be a problem.
  • Some firewall or proxy systems may not allow access to HTTPS sites. Sometimes this is simply because the administrators have forgotten to allow for HTTPS. However sometimes it is a conscious security decision: since HTTPS connections are end-to-end encrypted, they can be used to carry any traffic at all. Allowing them through a firewall, which then has no way to look inside the data stream, could allow any sort of data transfer (in either direction).
  • Cost. Commercial CAs charge something like £100-200 per year for issuing certificates. And you need at least one for every site that you secure, because the hostname (as it appears in URLs) forms part of the certificate. There is also the "hidden" administrative cost of applying for the certificate and of arranging for its renewal each year.
Read More
Unknown

Difference between http and https

  • There are some primary differences between http and https, however, beginning with the default port, which is 80 for http and 443 for https.
  • Https works by transmitting normal http interactions through an encrypted system, so that in theory, the information cannot be accessed by any party other than the client and end server. There are two common types of encryption layers: Transport Layer Security (TLS) and Secure Sockets Layer (SSL), both of which encode the data records being exchanged.
  • When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.
  • Https is used in many situations, such as log-in pages for banking, forms, corporate log ons, and other applications in which data needs to be secure. However, if not implemented properly, https is not infallible, and therefore it is extremely important for end users to be wary about accepting questionable certificates and cautious with their personal information while using the Internet.
  • Processing time required for HTTPS is greater than HTTP. Because, key negotiation (handshaking) requires a lot CPU capacity.


Read More

Friday, 17 January 2014

Unknown

How to write XML file in java


import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteFormattedXmlExample
{

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

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root element
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);

    // staff element
    Element employee = doc.createElement("employee");
    rootElement.appendChild(employee);

    // set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1001");
    employee.setAttributeNode(attr);

    // shorten way
    // staff.setAttribute("id", "1");

    // firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("vipul"));
    employee.appendChild(firstname);

    // lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("vaghela"));
    employee.appendChild(lastname);

    // nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("vip"));
    employee.appendChild(nickname);

    // salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("2000000"));
    employee.appendChild(salary);

    // write xml to file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");

    DOMSource source = new DOMSource(doc);

    StreamResult result = new StreamResult(new File("file.xml"));

    // Show output on console during development
    //StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("Xml File saved!");

  }
}
Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <employee id="1001">
    <firstname>vipul</firstname>
    <lastname>vaghela</lastname>
    <nickname>vip</nickname>
    <salary>200000</salary>
  </employee>
</company>
Read More

Wednesday, 8 January 2014

Unknown

How to install JDK 7 in Ubuntu 13.04




In case you need Oracle Java instead of OpenJDK in Ubuntu, here's how you can install it via a PPA:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Note that the PPA doesn't host Oracle Java 7 as this not allowed by the new Java license (which is also the reason why it has been removed from the official Ubuntu repositories in the first place). The package in the PPA simply downloads Oracle Java JDK 7 from its official website and installs it on your machine.

To test if the installation is completed successfully, execute:

java -version

If for some reasons, the Java installed is not version 1.7.x, execute the following command to force an update:

sudo update-java-alternatives -s java-7-oracle

To automatically set up the Java 7 environment variables, install the following package:
sudo apt-get install oracle-java7-set-default
Read More

Monday, 6 January 2014

Unknown

New Features Added By Java Compare to C++


There are a number of features in Java that have no equivalent in C++. Perhaps the three most important are multithreading, packages, and interfaces, but there are several others that enrich the Java programming environment as well.
  • Multithreading allows two or more pieces of the same program to 
    execute concurrently. Further, this approach to concurrence is supported at the 
    language level. There is no parallel for this in C++. If you need to multithread a C++ 
    program, you will need to do so manually, using operating system functions. While 
    both methods allow for concurrent execution of two or more threads, Java's approach 
    is cleaner and easier to use.
  • There is no feature in C++ that directly corresponds to a Java package. The closest 
    similarity is a set of library functions that use a common header file. However, 
    constructing and using a library in C++ is completely different from constructing and 
    using a package in Java.
  • The Java interface is somewhat similar to a C++ abstract class. (An abstract class in 
    C++ is a class that contains at least one pure virtual function.) For example, it is 
    impossible to create an instance of a C++ abstract class or a Java interface. Both are 
    used to specify a consistent interface that subclasses will implement. The main 
    difference is that an interface more cleanly represents this concept.
  • Java has a streamlined approach to memory allocation. Like C++, it supports the new 
    keyword. However, it does not have delete. Instead, when the last reference to an 
    object is destroyed, the object, itself, is automatically deleted the next time that 
    garbage collection occurs.
  • Java "removes" the C++ standard library, replacing it with its own set of API classes. 
    While there is substantial functional similarity, there are significant differences in the 
    names and parameters. Also, since all of the Java API library is object-oriented, and 
    only a portion of the C++ library is, there will be differences in the way library routines 
    are invoked.
  • The break and continue statements have been enhanced in Java to accept labels as 
    targets.
  • The char type in Java declares 16-bit-wide Unicode characters. This makes them 
    similar to C++'s wchar_t type. The use of Unicode helps ensure portability.
  • Java adds the >>> operator, which performs an unsigned right shift.
  • In addition to supporting single-line and multiline comments, Java adds a third 
    comment form: the documentation comment. Documentation comments begin with a 
    /** and end with a */.
  • Java contains a built-in string type called String. String is somewhat similar to the 
    standard string class type provided by C++. Of course, in C++ string is only available if 
    you include its class declarations in your program. It is not a built-in type.
Read More
Unknown

How Garbage Collection Works in java


Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. Furthermore, different Java run-time implementations will take varying approaches to garbage collection, but for the most part, you should not have to think about it while writing your programs.

The finalize( ) Method


Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. 
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method you will specify those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls the finalize() method on the object. The finalize( ) method has this general form:


protected void finalize( ) 
// finalization code here 
}


Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize( ) for normal program operation.
Note: If you are familiar with C++, then you know that C++ allows you to define a destructor for a class, which is called when an object goes out-of-scope. Java does not support this idea or provide for destructors. The finalize( ) method only approximates the function of a destructor. As you get more experienced with Java, you will see that the need for destructor functions is minimal because of Java's garbage collection subsystem.
Read More

Friday, 3 January 2014

Unknown

How to view current classpath in java?



Following example demonstrates how to view current classpath using echo command.
C:> echo %CLASSPATH%

Result:

The above code sample will produce the following result.

.;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip
Read More
Unknown

How to set multiple classpath in java?



Following example demonstrates how to set multiple classpath. Multiple class paths are separated by a semicolon.
c:> java -classpath C:\java\MyClasse1;C:\java\MyClass2 
    utility.testapp.main

Result:

The above code sample will produce the following result.

Class path set.
Read More
Unknown

How to fill (initialize at once) an array in java?


This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and Array.fill(arrayname ,starting index ,ending index ,value) method of Java Util class.
import java.util.*;

public class FillTest {
   public static void main(String args[]) {
      int array[] = new int[6];
      Arrays.fill(array, 100);
      for (int i=0, n=array.length; i < n; i++) {
         System.out.println(array[i]);
      }
      System.out.println();
      Arrays.fill(array, 3, 6, 50);
      for (int i=0, n=array.length; i< n; i++) {
         System.out.println(array[i]);
      }
   }
}

Result:

The above code sample will produce the following result.

100
100
100
100
100
100

100
100
100
50
50
50
Read More
Unknown

How to compile a java file?


Following example demonstrates how to compile a java file using javac command.
c:\jdk\demoapp> javac First.java 

Result:

The above code sample will produce the following result.

First.java compile successfully.
Read More
Unknown

Example of object sorting in java



import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * Java program to test Object sorting in Java. This Java program
 * test Comparable and Comparator implementation provided by Order
 * class by sorting list of Order object in ascending and descending order.
 * Both in natural order using Comparable and custom Order using Comparator in Java
 *

 */

public classObjectSortingExample {

    public static voidmain(Stringargs[]) {
     
        //Creating Order object to demonstrate Sorting of Object in Java
        Order ord1 = newOrder(101,2000, "Sony");
        Order ord2 = newOrder(102,4000, "Hitachi");
        Order ord3 = newOrder(103,6000, "Philips");
     
        //putting Objects into Collection to sort
        List<Order>orders = new ArrayList<Order>();
        orders.add(ord3);
        orders.add(ord1);
        orders.add(ord2);
     
        //printing unsorted collection
        System.out.println("Unsorted Collection : " + orders);
     
        //Sorting Order Object on natural order - ascending
        Collections.sort(orders);
     
        //printing sorted collection
        System.out.println("List of Order object sorted in natural order : "+ orders);
     
        // Sorting object in descending order in Java
        Collections.sort(orders, Collections.reverseOrder());
        System.out.println("List of object sorted in descending order : "+ orders);
             
        //Sorting object using Comparator in Java
        Collections.sort(orders, newOrder.OrderByAmount());
        System.out.println("List of Order object sorted using Comparator - amount : " + orders);
     
        // Comparator sorting Example - Sorting based on customer
        Collections.sort(orders, newOrder.OrderByCustomer());
        System.out.println("Collection of Orders sorted using Comparator - by customer : " + orders);
    }
}

/*
 * Order class is a domain object which implements
 * Comparable interface to provide sorting on natural order.
 * Order also provides copule of custom Comparators to
 * sort object based uopn amount and customer
 */

class Order implementsComparable<Order> {

    private int orderId;
    private int amount;
    private Stringcustomer;

    /*
     * Comparator implementation to Sort Order object based on Amount
     */

    public static classOrderByAmount implements Comparator<Order> {

        @Override
        public int compare(Order o1, Order o2) {
            returno1.amount >o2.amount ?1 : (o1.amount < o2.amount ? -1 : 0);
        }
    }

    /*
     * Anohter implementation or Comparator interface to sort list of Order object
     * based upon customer name.
     */

    public static classOrderByCustomer implements Comparator<Order> {

        @Override
        public int compare(Order o1, Order o2) {
            returno1.customer.compareTo(o2.customer);
        }
    }

    public Order(intorderId, int amount, Stringcustomer) {
        this.orderId = orderId;
        this.amount = amount;
        this.customer = customer;
    }

 
    public int getAmount(){returnamount; }
    public void setAmount(int amount){this.amount = amount;}

    public StringgetCustomer() {return customer;}
    public void setCustomer(Stringcustomer) {this.customer= customer;}

    public int getOrderId(){returnorderId;}
    public void setOrderId(int orderId){this.orderId = orderId;}

    /*
     * Sorting on orderId is natural sorting for Order.
     */

    @Override
    public int compareTo(Order o) {
        return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
    }
 
    /*
     * implementing toString method to print orderId of Order
     */

    @Override
    public StringtoString(){
        return String.valueOf(orderId);
    }
}

Output
Unsorted Collection : [103, 101, 102]
List of Order object sorted in natural order : [101, 102, 103]
List of object sorted in descending order : [103, 102, 101]
List of Order object sorted using Comparator - amount : [101, 102, 103]
Collection of Orders sorted using Comparator - by customer : [102, 103, 101]
Read More