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

Friday, September 26, 2014

Still not using Maven ? Then here is some dependancy tips

AXIS2 CLIENT

    axis2-xmlbeans-1.6.2
    axis2-transport-http-1.6.2
    axis2-transport-local-1.6.2
    axis2-adb-1.6.2
    axis2-kernel-1.6.2
    axiom-api-1.2.13
    axiom-impl-1.2.13
    neethi-3.0.2
    XmlSchema-1.4.7
    httpcore-4.0
    mail-1.4
    commons-httpclient-3.1
    commons-codec-1.3
    commons-logging-1.1.1
    wsdl4j-1.6.2

JAX-WS
    jaxb-impl.jar
    jaxws-api.jar
    jaxws-rt.jar
    gmbal-api-only.jar
    management-api.jar
    stax-ex.jar
    streambuffer.jar
    policy.jar
    ha-api.jar
    jaxb-core.jar
    
JERSEY
    asm-3.1.jar
    jackson-core-asl-1.9.2.jar
    jackson-jaxrs-1.9.2.jar
    jackson-mapper-asl-1.9.2.jar
    jackson-xc-1.9.2.jar
    jersey-client-1.17.1.jar
    jersey-core-1.17.1.jar
    jersey-json-1.17.1.jar
    jersey-server-1.17.1.jar
    jersey-servlet-1.17.1.jar
    jettison-1.1.jar
    jsr311-api-1.1.1.jar
    
LOG4J
    log4j-1.2.17.jar
    
STRUTS 2
    commons-fileupload-x.y.z.jar
    commons-io-x.y.z.jar
    commons-lang-x.y.jar
    commons-logging-x.y.z.jar
    commons-logging-api-x.y.jar
    freemarker-x.y.z.jar
    javassist-.xy.z.GA
    ognl-x.y.z.jar
    struts2-core-x.y.z.jar
    xwork-core.x.y.z.jar
    commons-lang3-3.1.jar
    
OPEN SAML 2.6
    serializer-2.10.0
    xalan-2.7.1
    xercesImpl-2.10.0
    xml-apis-2.10.0
    xmltooling-1.4.1
    xmlsec-1.5.6
    slf4j-api-1.7.5
    openws-1.5.1
    opensaml-2.6.1
    joda-time-2.2
    esapi-2.0.1
    commons-lang-2.6
    
HIBERNATE 4.1
    commons-collections-3.2.1.jar
    antlr-2.7.7.jar
    commons-lang3-3.1.jar
    commons-logging-1.1.3.jar
    dom4j-1.6.1.jar
    hibernate-commons-annotations-4.0.1.Final.jar
    hibernate-core-4.2.0.Final.jar
    hibernate-jpa-2.0-api-1.0.1.Final.jar
    javassist-3.15.0-GA.jar
    jboss-logging-3.1.0.GA.jar
    jboss-transaction-api_1.1_spec-1.0.0.Final.jar

Monday, August 4, 2014

How to force change jboss class loader method 2

In my previous post there is the first method where you can force jboss to isolate class loader of your web app from server class loader. Here what happen is before adding jars in server classpath, jboss will search jars in your web app classpath. If matching jars or duplicating jars found jboss will give priority to the jars found in your web app’s classpath.


So to achieve this the first method is create an entry in jboss-web.xml which is the jboss specific deployment descriptor. The second method is creating a separate xml file “jboss-classloading.xml” in your app’s “WEB-INF” folder and add the class loading instructions in that file. An example is given below.


<classloading xmlns=”urn:jboss:classloading:1.0”
            name=”MyAPP.war”
            domain=”MyAPP_domain”
            parent-domain=”this is optional”
            parent-first=”false”
            export-all=”NON_EMPTY”
            import-all=”true”>
</classloading>


***** parent daomain is optional.

JBOSS EAP 5.1.2 & Sun Metro JAX-WS

Jboss does have their own web service implementation which is JBossWS-CXF, based out of Apache CXF. But if you are into JAX-WS metro stack you can simply use it with jboss.


1. Overide the class loader to load SUN Metro stack instead jboss supplied jax-ws version.


create “jboss-web.xml” file in “WEB-INF” folder with following content.


<?xml version=”1.0” encoding=”UTF-8”?>
<jboss-web>
    <context-root>/MyApp</context-root>
    <class-loading java2ClassLoadingCompliance=”false”>
        <loader-repository>
            org.myapp:loader=MyApp.war
            <loader-repository-config>
                java2ParentDelegation=false
            </loader-repository-config>
        </loader-repository>
    </class-loading>
</jboss-web>



2. Add WSServletContextListener listner to web.xml file


<listener>
       <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
  </listener>



3. Add servlet and servlet mapping for WSServlet


<servlet>
    <servlet-name>WSServlet</servlet-name>
    <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>WSServlet</servlet-name>
    <url-pattern>/*</url-pattern>
   <!—  <url-pattern>/services/*</url-pattern> —>
  </servlet-mapping>



You may now get your web service not only work but dynamic WSDL creation also working.

Wednesday, July 23, 2014

WSO2 IS SAML SSO using openSAML java library

In this blog post i will explain how to write a sample SSO service provider code using wso2is as the identity provider and openSAML as the supporting library to create SAML request.


First download the wso2IS from [1] and openSAML release from [2]. Then startup the wso2is. Create a new java web application project and import below jars from opensaml lib and lib/endorsed folders.


    serializer-2.10.0
    xalan-2.7.1
    xercesImpl-2.10.0
    xml-apis-2.10.0
    xmltooling-1.4.1
    xmlsec-1.5.6
    slf4j-api-1.7.5
    openws-1.5.1
    opensaml-2.6.1
    joda-time-2.2
    esapi-2.0.1
    commons-lang-2.6


Also include “axiom-api.jar” from apache axis project which has the UIDGenerator.java class.


Lets take our service provider name is “test.com” & our consumer landing page is “http://localhost:8080/test.com/home.jsp”. (You have to register a new service provider with above fields in wso2 identity server. To do so please refer [3] )


You can use below code to sent login & logout saml requests.




import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.common.SAMLVersion;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.AuthnContextClassRef;
import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.LogoutRequest;
import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.core.NameIDPolicy;
import org.opensaml.saml2.core.RequestAbstractType;
import org.opensaml.saml2.core.RequestedAuthnContext;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.SessionIndex;
import org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder;
import org.opensaml.saml2.core.impl.AuthnRequestBuilder;
import org.opensaml.saml2.core.impl.IssuerBuilder;
import org.opensaml.saml2.core.impl.LogoutRequestBuilder;
import org.opensaml.saml2.core.impl.NameIDBuilder;
import org.opensaml.saml2.core.impl.NameIDPolicyBuilder;
import org.opensaml.saml2.core.impl.RequestedAuthnContextBuilder;
import org.opensaml.saml2.core.impl.SessionIndexBuilder;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class SAMLConsumer {
    
    private static final Logger logger = LoggerFactory.getLogger(SAMLConsumer.class);
    private static boolean isBootstraped = false;

    private static final String ISSUER_URL = “test.com”;
    private static final String CONSUMER_URL = “http://localhost:8080/test.com/home.jsp”;

    private static final String NAME_SPACE_URI_ISSUER = “urn:oasis:names:tc:SAML:2.0:assertion”;
    private static final String NAME_SPACE_URI_AUTH = “urn:oasis:names:tc:SAML:2.0:protocol”;
    private static final String SAML_TRANSPORT_TYPE_PWD_PROTECTED = “urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport”;
    private static final String SAML_TRANSPORT_PROTOCOL_BINDING = “urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST”;
    
    private static final String LOCAL_NAME_ISSUER = “Issuer”;
    private static final String LOCAL_NAME_AUTHRQ = “AuthnRequest”;
    private static final String NAME_SPACE_PREFIX = “samlp”;
    private static final String AUTH_CNTXT_REF = “AuthnContextClassRef”;
    private static final String SAML = “saml”;
    
    public static String buildLoginRequest() throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException, MarshallingException, IOException  {
        logger.info(“started”);

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject(NAME_SPACE_URI_ISSUER, LOCAL_NAME_ISSUER, “samlp”);
        issuer.setValue(ISSUER_URL);
        
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        nameIdPolicy.setFormat(“urn:oasis:names:tc:SAML:2.0:nameid-format:persistent”);
        nameIdPolicy.setSPNameQualifier(“Isser”);
        nameIdPolicy.setAllowCreate(new Boolean(true));
        
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef =
                                                    authnContextClassRefBuilder.buildObject(NAME_SPACE_URI_ISSUER,
                                                            AUTH_CNTXT_REF, SAML);
        authnContextClassRef.setAuthnContextClassRef(SAML_TRANSPORT_TYPE_PWD_PROTECTED);
        
        RequestedAuthnContextBuilder requestedAuthnContextBuilder =
                                                        new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
        
        DateTime issueInstant = new DateTime();
        AuthnRequestBuilder authnRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authnRequest = authnRequestBuilder.buildObject(NAME_SPACE_URI_AUTH, LOCAL_NAME_AUTHRQ, NAME_SPACE_PREFIX);
        authnRequest.setForceAuthn(new Boolean(false));
        authnRequest.setIsPassive(new Boolean(false));
        authnRequest.setIssueInstant(issueInstant);
        authnRequest.setProtocolBinding(SAML_TRANSPORT_PROTOCOL_BINDING);
        authnRequest.setAssertionConsumerServiceURL(CONSUMER_URL);
        authnRequest.setIssuer(issuer);
        authnRequest.setNameIDPolicy(nameIdPolicy);
        authnRequest.setRequestedAuthnContext(requestedAuthnContext);
        
        String authReqRandomId = Integer.toHexString(new Double(Math.random()).intValue());
        
        authnRequest.setID(authReqRandomId);
        authnRequest.setVersion(SAMLVersion.VERSION_20);
                
        return marshall(authnRequest);
        
    }
    
    public static String buildLogoutRequest(String user) throws MarshallingException, IOException {

        LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject();

        logoutReq.setID(createID());

        DateTime issueInstant = new DateTime();
        logoutReq.setIssueInstant(issueInstant);
        logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(ISSUER_URL);
        logoutReq.setIssuer(issuer);

        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setFormat(“urn:oasis:names:tc:SAML:2.0:nameid-format:entity”);
        nameId.setValue(user);
        logoutReq.setNameID(nameId);

        SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
        sessionIndex.setSessionIndex(UIDGenerator.generateUID());
        logoutReq.getSessionIndexes().add(sessionIndex);

        logoutReq.setReason(“Single Logout”);

        return marshall(logoutReq);
    }
    
    private static String marshall(RequestAbstractType authnRequest) throws MarshallingException, IOException {
        doBootstrap();
        Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(authnRequest);
        Element authDOM = marshaller.marshall(authnRequest);
        
        
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        String requestMessage = rspWrt.toString();
        
        System.out.println(requestMessage);
                 
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        deflaterOutputStream.write(requestMessage.getBytes());
        deflaterOutputStream.close();
                 
        /* Encoding the compressed message */
        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
        String encodedAuthnRequest = URLEncoder.encode(encodedRequestMessage,”UTF-8”).trim();;
        
        return encodedAuthnRequest;
    }
    
    
    public static <T> T createSAMLObject(final Class<T> clazz) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
         XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        
         QName defaultElementName = (QName)clazz.getDeclaredField(“DEFAULT_ELEMENT_NAME”).get(null);
         Map<QName, XMLObjectBuilder> builderMap= builderFactory.getBuilders();
         System.out.println(“is nul “  + builderMap.get(defaultElementName));
        
        return null;
    }
    
    private static void doBootstrap() {
        if(!isBootstraped) {
            try {
                DefaultBootstrap.bootstrap();
                isBootstraped = true;
            } catch (ConfigurationException e) {
                logger.error(“Error calling bootstrap”, e);
            }
        }
    }
    
    public static Map<String, String> processResponse(String response) {

        XMLObject resp = null;
        
        try {
            resp = unmarshall(response);
        } catch (ConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnmarshallingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return getResult(resp);
        
    }
    
    private static XMLObject unmarshall(String responseMessage) throws ConfigurationException,
                            ParserConfigurationException, SAXException, IOException, UnmarshallingException {
        
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        
        byte[] base64DecodedResponse = Base64.decode(responseMessage.trim());
        
        System.out.println(new String(base64DecodedResponse));
        
        ByteArrayInputStream is = new ByteArrayInputStream(base64DecodedResponse);
        
        Document document = docBuilder.parse(is);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
        
    }
    
    private static Map<String, String> getResult(XMLObject responseXmlObj) {

        if (responseXmlObj.getDOM().getNodeName().equals(“saml2p:LogoutResponse”)) {
            logger.error(“user logout”);
            return null;
        }

        Response response = (Response) responseXmlObj;
        logger.info(“SAML resp” + response);

        Assertion assertion = response.getAssertions().get(0);
        Map<String, String> resutls = new HashMap<String, String>();

        /*
         * If the request has failed, the IDP shouldn’t send an assertion.
         * SSO profile spec 4.1.4.2 <Response> Usage
         */
        if (assertion != null) {

            String subject = assertion.getSubject().getNameID().getValue();
            resutls.put(“Subject”, subject); // get the subject

            List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();

            if (attributeStatementList != null) {
                // we have received attributes of user
                Iterator<AttributeStatement> attribStatIter = attributeStatementList.iterator();
                while (attribStatIter.hasNext()) {
                    AttributeStatement statment = attribStatIter.next();
                    List<Attribute> attributesList = statment.getAttributes();
                    Iterator<Attribute> attributesIter = attributesList.iterator();
                    while (attributesIter.hasNext()) {
                        Attribute attrib = attributesIter.next();
                        Element value = attrib.getAttributeValues().get(0).getDOM();
                        String attribValue = value.getTextContent();
                        resutls.put(attrib.getName(), attribValue);
                    }
                }
            }
        }
        return resutls;
    }
    
    public static String createID() {

        byte[] bytes = new byte[20]; // 160 bit
        
        new Random().nextBytes(bytes);
        
        char[] charMapping = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’};

        char[] chars = new char[40];

        for (int i = 0; i < bytes.length; i++) {
            int left = (bytes[i] » 4) & 0x0f;
            int right = bytes[i] & 0x0f;
            chars[i * 2] = charMapping[left];
            chars[i * 2 + 1] = charMapping[right];
        }

        return String.valueOf(chars);
    }
    
}




[1] http://wso2.com/products/identity-server/


[2] https://wiki.shibboleth.net/confluence/display/OpenSAML/Home


[3] http://pavithramadurangi.blogspot.com/2013/09/saml-20-sso-with-wso2-is-450.html

Saturday, March 31, 2012

Writing custom cursor adapter to use data from a SQLITE database with AutoCompleteTextView

In this post i am going to discuss how to implement a custom cursor adapter that take the data from a sqlite database and populate the  AutoCompleteTextView on the fly.

First let us write our database code which return a cursor. ( Here i only display the related method to return cursor. You have to write a new class extending  "android.database.sqlite.SQLiteOpenHelper" and write the database initialization and open logic in the class. )



1:  public synchronized Cursor getAutoCompleteCursor(String prefix){  
2:         Cursor c = null;  
3:         if(prefix.compareTo("")==0){  
4:              c = myDataBase.query("dict", new String[]{ID_COLUMN_NAME},   
5:                     ID_COLUMN_NAME+" like '' || ? || '%'",   
6:                     new String[]{"*"},   
7:                     null,   
8:                     null,   
9:                     null);  
10:         }else{  
11:              c = myDataBase.query("tableName",   
12:                        new String[]{COLUMN_NAME},   
13:                     ID_COLUMN_NAME+" like '' || ? || '%'",   
14:                     new String[]{prefix},   
15:                     null,   
16:                     null,   
17:                     null);  
18:         }  
19:         if(c == null & c.getCount() <= 0){  
20:              new Exception("Cursor " + (c==null?"null":" fill with wrong data"));  
21:         }  
22:         return c;  
23:    }  





Here "tableName" is the name of the table and "COLUMN_NAME" is the name of the column in table you want to bind with auto complete view.

My database is a very large one so when query for empty string it returns a large number of rows. This will lead to throw an exception in GPU level (creating a view larger than 40000 rows). So i used a conditional check to verify the empty string and at the initial point i query for a string that is not in database to retrieve a empty cursor and on the second letter enter and onward it will query for the prefix and get suggestion list. Another method i used to overcome this memory issue is to use a threshold in  AutoCompleteTextView so it will start to display suggestions only after the number of characters exceed threshold.

Then we write a class extending CursorAdapter class and implementing the filterable interface to include the view generation logic with the listening to key events in background and query the database to obtain suggestion words.


1:  
2:  import android.content.Context;  
3:  import android.database.Cursor;  
4:  import android.view.LayoutInflater;  
5:  import android.view.View;  
6:  import android.view.ViewGroup;  
7:  import android.widget.AutoCompleteTextView;  
8:  import android.widget.CursorAdapter;  
9:  import android.widget.Filterable;  
10:  import android.widget.TextView;  
11:  public class CustomCursorAdaptor extends CursorAdapter implements Filterable {  
12:       private DatabaseHelper dbHelper;  
13:       private LayoutInflater inflater ;  
14:       public CustomCursorAdaptor(Context context, Cursor c) {  
15:            super(context, c);  
16:            this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
17:            this.dbHelper = DatabaseHelper.getDatabaseHelper(context);  
18:       }  
19:       @Override  
20:       public void bindView(View view, Context context, Cursor cursor) {            
21:            String keyword = cursor.getString(cursor.getColumnIndex(DatabaseHelper.ID_COLUMN_NAME));  
22:      TextView tv = (TextView) view.findViewById(R.id.sugestionTextView);  
23:      tv.setText(keyword);  
24:       }  
25:       @Override  
26:       public View newView(Context context, Cursor cursor, ViewGroup parent) {  
27:            return inflater.inflate(R.layout.list_item, null);            
28:       }  
29:     @Override
31: public CharSequence convertToString(Cursor cursor) {
32:  
33:  return cursor.getString(cursor.getColumnIndex(DatabaseHelper.DICT_ID_COLUMN_NAME));
34: }
35:       @Override  
36:       public Cursor runQueryOnBackgroundThread(CharSequence constraint) {  
37:            //return super.runQueryOnBackgroundThread(constraint);  
38:            if(getFilterQueryProvider() != null){  
39:                 return getFilterQueryProvider().runQuery(constraint);  
40:            }  
41:            String filter = "";  
42:            if(constraint != null){  
43:                 filter = constraint.toString();  
44:            }  
45:            return dbHelper.getIdCursor(filter);  
46:       }  
47:  }  

Here at the construct i initialize the LayoutInflater and obtain the reference to my DatabaseHelper class which was written by extending the SQLiteOpenHelper and included the getAutoCompleteCursor method.

We have to override two abstract methods in the class which are newView and bindView.

In newView  write our code to use the inflater and populate a view return it to current cursor position. Here i used this method to populate my custom written "list_item" layout and return a view of that layout.

1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:id="@+id/sugestionTextView"  
4:    android:layout_width="fill_parent"  
5:    android:layout_height="fill_parent"  
6:    android:padding="10dp"  
7:    android:textSize="16sp"  
8:    android:textColor="#000">  
9:  </TextView>  

"list_item.xml" file

In bindView we used to populate an existing view that is being reused with data in our cursor. Here i get a string from the cursor, create a text view by finding a sugestionTextView which is located in my "list_item" xml file and set the text view with the string i obtained from the cursor.

In the method runQueryOnBackgroundThreadhas been used to run a background thread each time a new character been entered to AutoCompleteTextView and obtain a cursor with the prefix text that is in the AutoCompleteTextView at that point.

Finally in the Activity class write the following code inside onCreate method to initialize the new CursorAdapter implementation class and set the adapter to AutoCompleteTextView.


1:  autoText = (AutoCompleteTextView) findViewById(R.id.autoCompleteEnglishWordText);  
2:  autoText.setThreshold(2);  
3:  CustomCursorAdaptor cursurAdaptor = new CustomCursorAdaptor(this, null);  
4:  autoText.setAdapter(cursurAdaptor);


Saturday, March 17, 2012

Ant target to start axis2 server

Here i will describe how to write ant target to start apache axis2 server directly from your "build.xml" file without calling any shell script file. For this purpose we use "org.apache.axis2.transport.SimpleAxis2Server" class and pass it few arguments to tell it about our configuration files and service folder path.

First let us add locations to class path.
(here the ${axis-home} refers to the root of your apache axis2 directory.)



<path id="axis-classpath">
 <pathelement location="${axis-home}"/>
 <pathelement location="${axis-home}/conf"/>
 <pathelement location="${env.JAVA_HOME}/lib/tools.jar"/>
 <fileset dir="${axis-home}/lib">
  <include name="*.jar"/>
 </fileset>
</path>

with adding those paths to the class path let us write ant target to start axis2 server like below.


<target name="start-axis">
 <java classname="org.apache.axis2.transport.SimpleAxis2Server" fork="true">
  <classpath refid="axis-classpath" /> 
  <jvmarg value="-Djava.endorsed.dirs=${axis-home}/lib/endorsed;${env.JAVA_HOME}/jre/lib/endorsed;${env.JAVA_HOME}/lib/endorsed" />
  <arg line="-repo ${axis-home}/repository"/>
  <arg line="-conf ${axis-home}/conf/axis2.xml"/>
 </java>
</target>


Here we pass a jvm argument stating all the endorsed folder paths and two runtime arguments which are the location for service repository and path to axis configuration file.

Friday, March 16, 2012

Ant target for Apache Tomcat

This tutorial will explain how to write an ant target to start and stop tomcat. For this task we use a special class located in "tomcat/bin/bootstrap.jar" namely "org.apache.catalina.startup.Bootstrap". Also this  jar will be depend on another jar which is located at the same location "tomcat/bin/tomcat-juli.jar".

First add these locations to a class path like below.
(here the ${tomcat} refers to the root of your tomcat directory.)


<path id="tomcat-classpath">
 <fileset dir="${tomcat}/lib">
  <include name="*.jar" />
 </fileset>
 <fileset dir="${tomcat}/bin">
  <include name="tomcat-juli.jar" />
  <include name="bootstrap.jar" />
 </fileset>
</path>


Then we write start-tomcat target to start the apache tomcat.


<target name="start-tomcat">
 <java classname="org.apache.catalina.startup.Bootstrap" fork="true">
  <classpath refid="tomcat-classpath" />
  <jvmarg value="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager" />
  <jvmarg value="-Djava.util.logging.config.file=${tomcat}/conf/logging.properties" />
  <jvmarg value="-Dcatalina.home=${tomcat}" />
  <jvmarg value="-Dcatalina.base=${tomcat}" />
  <jvmarg value="-Djava.io.tmpdir=${tomcat}/temp" />
  <arg line="start"/>
 </java>
</target>


And then we write the stop-tomcat target to stop the running tomcat instance.


<target name="stop-tomcat">
 <java classname="org.apache.catalina.startup.Bootstrap" fork="true">
  <classpath refid="tomcat-classpath" />
  <jvmarg value="-Dcatalina.home=${tomcat}" />
  <arg line="stop" />
 </java>
</target>


Ok! we are done!!!

Saturday, March 10, 2012

Reverse engineering - Generating hbm.xml from annotated POJO

I have look for these particular scenario every where but couldnot found anything usefull other than the hibernate tools documentation. Reason the people not doing this is because hibernate - tools are mainly using for reverse engineering where this is not coming across. Only scenario i can think of where you need to generate a hibernate mapping xml from a POJO which is already annotated ( annotations are the successor of hibernate mapping xmls) is when you are in middle of the migration process from hibernate mapping xmls to annotations.

People already developing a product are not likely to suddenly adapting the changes. So they do it, step by step when it is needed so in such a case first you write annotation base POJOs but really not using them instead u generate the hbm.xml from the annotations, is the best way to work around. And also writing POJO separately and mapping separately increase the possibility of  erroneous of the code. Instead generating one automatically when the other given is much applicable which in case reduce   the time of the development and make the process more efficient.

enough talking now i will explain the process
only to generate the hbm mapping i only needed hibernate-tool-xx.jar and fremarker.jar but to run a complete hibernate base code using the generated hbm i need the following dependencies so before you start better to include all of them in to your lib directory

below jars are coming with hibernate distribution
antlr-2.7.6.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar                                                              
hibernate3.jar
slf4j-api-1.6.1.jar
jta-1.1.jar
javassist-3.12.0.GA.jar

and you have to download these separately
commons-collections-3.2.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jtidy-r8-21122004.jar
mysql-connector-java-5.0.4-bin.jar (if you use mysql as back end database)
slf4j-simple-1.6.1.jar
freemarker.jar
hibernate-tools-3.2.4.GA.jar

that is all you need. And lets begin coding you have to write an ant build script with following target and taskdef which need to create hbm.xml mapping for your pojo

 <taskdef name="hibernatetool"   
                classname="org.hibernate.tool.ant.HibernateToolTask"   
                classpathref="lib" />  
      <taskdef name="annotationconfiguration"   
                classname="org.hibernate.tool.ant.AnnotationConfigurationTask"   
                classpathref="lib" />  
      <target name="init" depends="copy-resources">  
           <hibernatetool destdir="${builddir}">  
                <classpath>  
                     <path location="${srcdir}" />  
                     <path location="${libdir}" />  
                     <path location="${builddir}" />  
                </classpath>  
                <annotationconfiguration configurationfile="${srcdir}/hibernate.cfg.xml" />  
                <hbm2hbmxml />  
           </hibernatetool>  
      </target>  

Put this ant file in to your project and write a POJO with annotations as they used to write in. (Everything is normal than the crazy work - trying to generate hbm.xml from annotations.)

And here is the important part. You have to include your pojo's full class path into your hibernate.cfg.xml (hibernate configuration file) as a mapping.

Below is my example hibernate.cfg.xml ,

 <?xml version='1.0' encoding='utf-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD//EN"  
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
  <property name="hibernate.connection.driver_class">  
 com.mysql.jdbc.Driver</property>  
  <property name="hibernate.connection.url">  
 jdbc:mysql://localhost:3306/testhib</property>  
  <property name="hibernate.connection.username">root</property>  
  <property name="hibernate.connection.password">1234</property>  
  <property name="hibernate.connection.pool_size">1</property>  
  <property name="show_sql">true</property>  
  <!-- <property name="hibernate.bytecode.provider">javassist</property> -->  
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  <property name="hibernate.hbm2ddl.auto">update</property>  
  <!-- Mapping files -->  
  <mapping class="com.example.User"/>  
  <mapping class="com.example.Task"/>  
  </session-factory>  
 </hibernate-configuration>  

here my POJOs which are  "com.example.User"  and "com.example.Task"  list under the mapping where normally hbm.xml goes. What happen here is the when the ant target "init" is called it tell hibernate tool task to read the hibernate configuration file and find the mapping class files then it goes to class path folders defined under hibernatetool task, travel the folder structure defined in package name and find the .class file, read the annotations in the .class file and generate the mappings in your directory where you defined under "destdir".

tomcat 7 taglib definition not consist issue

I have encountered this when i tried to port a java war file which is previously deployed in tomcat 6.0.13 to newest tomcat version tomcat 7.0.14

when the web container trying to deploy the .war file it throws an exception saying that

jndi:/localhost/application/WEB-INF/web.xml
java.lang.IllegalArgumentException: taglib definition not consistent with application version

and i when i googled for this problem i found only one mail thread regarding this tomcat 7 issue 

and i tried with all the options described their and finally found the solution that is write tags inside of which resolve the problem


  
  <jsp-config>
      <taglib>
          <taglib-uri>
              http://metawerx.net/mapp/taglibs
          </taglib-uri>
          <taglib-location>
              /WEB-INF/mapp.tld
          </taglib-location>
     </taglib>
  </jsp-config>


for more details about refer this site