Wednesday 27 July 2016

Add security header into soap request(Spring jax-ws)

Purpose of this note is to showcase adding security information like below into message header

    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
       <S:Header>
          <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
             <wsse:UsernameToken>
                <wsse:Username>XXXXX</wsse:Username>
                <wsse:Password>XXX@mCC</wsse:Password>
             </wsse:UsernameToken>
          </wsse:Security>
       </S:Header>
       <S:Body>
    


     <bean id="aomWSHandlerResolver" class="xx.webservice.util.DefaultHandlerResolver">
        <property name="handlers">
          <list>
             <bean class="xx.webservice.util.SecurityHandler"/>
          </list>
        </property>
      </bean>





<bean id="aomWebServiceProxyParent" abstract="true" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
    <property name="namespaceUri" value="http://xx.xx.com/services"/>
    <property name="serviceName" value="ApiService"/>
    <property name="lookupServiceOnStartup" value="false"/>
     <property name="handlerResolver" ref="aomWSHandlerResolver"/>
     <property name="username" value="xx"/>
    <property name="password" value="xx"/>
    <property name="customProperties">
      <map key-type="java.lang.String" value-type="java.lang.Integer">
        <entry key="com.sun.xml.ws.connect.timeout" value="${webservice.connect.timeout.millisec}"/>
        <entry key="com.sun.xml.ws.request.timeout" value="${webservice.response.timeout.millisec}"/>
      </map>
    </property>
   
  </bean>
 

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Handler that logs all the SOAP requests/responses using SL4J.
 *
 */
public final class SecurityHandler extends SoapHandler {

    
   
    /**
     * Logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(SecurityHandler.class);

    /**
     * Logs the request/response message.
     *
     * @param context
     *            The message context.
     * @return true to indicate the handler that processing should continue.
     */

    /**
     * Soap performance handler
     */

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
       
        String uri = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
        String prefix = "wsse";
        try {
             SOAPMessage message = context.getMessage();
              SOAPHeader header = message.getSOAPHeader();
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

              if (header == null) {
                  header = envelope.addHeader();
              }
              QName SecurityTokenHeader = new QName(uri,"Security",prefix);
                 SOAPHeaderElement securityToken = header.addHeaderElement(SecurityTokenHeader);
                
                
             QName UsernameTokenHeader = new QName(uri,"UsernameToken",prefix);
             SOAPHeaderElement userToken = header.addHeaderElement(UsernameTokenHeader);

             QName qNameuser = new QName(uri, "Username",prefix);
             SOAPHeaderElement userHeader = header.addHeaderElement(qNameuser);
             userHeader.addTextNode("BirminghamCC");
            
             QName qNamecredentials = new QName(uri,"Password",prefix);
             SOAPHeaderElement pwdHeader = header.addHeaderElement(qNamecredentials);
             pwdHeader.addTextNode("B1rm1ngh@mCC");
            
             //securityToken.addChildElement(UsernameTokenHeader);
             userToken.addChildElement(userHeader );
             userToken.addChildElement(pwdHeader);
             securityToken.addChildElement(userToken);
             //securityToken.addAttribute(envelope.createName("S:mustUnderstand") , "1");
             message.saveChanges();
           

        } catch (SOAPException e1) {
            // TODO Auto-generated catch block
            logger.error("SOAP request error: {}", e1.getMessage());
        }
         
         

        Boolean outbound = (Boolean) context
                .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
       
        String msg = WsUtils.getMessageAsString(context.getMessage());
       
        if (Boolean.TRUE.equals(outbound))
        {
            logger.debug("SOAP request: {}", msg);
            context.put(Thread.currentThread().getId() + "OUT", msg);
        }
        else
        {
            logger.debug("SOAP response: {}", msg);
                       
            try {
                if (!(msg.contains("0<") || msg.contains("0<")))
                {
                    logger.error("no success code found");
                    throw new Exception();
                }

            }
            catch (Exception e)
            {
                writeFaultToDatabase((String)context.get(Thread.currentThread().getId() + "OUT"), msg, e);
            }
               
        }
       
       
       
       
        return true;
    }

Friday 26 June 2015

How to configure EGITT for eclipse to connect to GITHub

This tutorial will explain how to configure EGIT eclipse plugin to connect to github.


  • First install EGit plugin for eclipse



  • Now go back to JAVA perspective in the eclipse and open package explorer.Now right click on the project you created in eclipse.Select Team=>Share project and select GIT. see screen below.


  • Clicking the next button will display the below screen. tick on the box to 'use or create repository in the parent folder of project' and then click on the project. now click on the create repository button. and then click finish. This will enable the project as git project and will display a bracket (ie'>') next to the project name in eclipse.


  • Now Open GIT repositories perspective.There you should see git project you set up in the previous step. Now click on create remote repository.
  • Enter remote name as you like in my case I use 'GitHub' and click ok

  • Then you will get 'configure push for remote GitHub' window.There you click Change button next to URL: It will open the window below. specify the url .

You can find the URL info by loggin in to GitHub using this url  https://github.com
You can find this url when you log in to the github reporitory using your github registraion details. For creating a github repository and finding the github url please find below information.

  • You can create a repository if you haven't already created one using the create new repository button next to your profile name in the right hand top of this page.

Once this url is entered in the eclipse configuration window it will populate the values for other fields. Now click finish button it will open the 'Configure push for remote'Origin'' window. Here you need to congiure ref mappings which is your head of the source should map to master of the repository.

Click on add button and that will open the below window. input the field as local branch to Head and remote branch to master if your connection is successfull this field will display relevent master word as you type. finally click on ok button.


Onece you click on the ok button below screen will open.click on to finish the wizard.



Now do some changes to a file in your project .Then right click on the project and select Team->Remote->Commit . see below for screen .




Fork & Pull

The Fork & Pull Model lets anyone fork an existing repository and push changes to their personal fork without requiring access be granted to the source repository. The changes must then be pulled into the source repository by the project maintainer. This model reduces the amount of friction for new contributors and is popular with open source projects because it allows people to work independently without upfront coordination.
  • Thats it enjoy.