com.sfs.whichdoctor.webservice.PublishServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.webservice.PublishServiceImpl.java

Source

/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs.whichdoctor.webservice;

import com.sfs.DataFilter;
import com.sfs.beans.UserBean;
import com.sfs.whichdoctor.beans.IsbEntityBean;
import com.sfs.whichdoctor.beans.IsbMessageBean;
import com.sfs.whichdoctor.beans.PersonBean;
import com.sfs.whichdoctor.beans.SearchBean;
import com.sfs.whichdoctor.beans.SearchResultsBean;
import com.sfs.whichdoctor.dao.IsbEntityDAO;
import com.sfs.whichdoctor.dao.IsbMessageDAO;
import com.sfs.whichdoctor.dao.IsbPersonTransactionDAO;
import com.sfs.whichdoctor.dao.WhichDoctorDaoException;
import com.sfs.whichdoctor.search.SearchDAO;
import com.sfs.whichdoctor.isb.publisher.PersonIsbXmlWriter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;

/**
 * The Class PublishServiceImpl.
 */
public class PublishServiceImpl implements PublishService {

    /** The logger. */
    private static Logger logger = Logger.getLogger(PublishServiceImpl.class);

    /** The target for the web service. */
    private String target = "production";

    /** The key. */
    private String key;

    /** The isb entity dao. */
    @Resource
    private IsbEntityDAO isbEntityDAO;

    /** The isb message dao. */
    @Resource
    private IsbMessageDAO isbMessageDAO;

    /** The isb person transaction dao. */
    @Resource
    private IsbPersonTransactionDAO isbPersonTransactionDAO;

    /** The search dao. */
    @Resource
    private SearchDAO searchDAO;

    /**
     * The target which the web service publishes to.
     * This value is injected via Spring.
     *
     * @param targetVal the target
     */
    public final void setTarget(final String targetVal) {
        this.target = targetVal;
    }

    /**
     * The key which the web service validates incoming ISB messages. This value
     * is injected via Spring.
     *
     * @param keyVal the key
     */
    public final void setKey(final String keyVal) {
        this.key = keyVal;
    }

    /**
     * Record the incoming ISB message as long as the key is valid.
     *
     * @param keyVal the key
     * @param source the source
     * @param targetVal the target
     * @param xmlPayload the xml payload
     *
     * @return the string
     */
    public final String Deliver(final String keyVal, final String source, final String targetVal,
            final String xmlPayload) {
        String outcome = "";

        /* Validate the ISB key - if it does not match do not process */
        if (StringUtils.equalsIgnoreCase(keyVal, this.key)) {
            outcome = deliverMessage(source, targetVal, xmlPayload);
        } else {
            outcome = "ERROR - Invalid ISB key";
        }
        return outcome;
    }

    /**
     * Loads a list of changed records from the specified time - defaults to
     * production ISB target.
     *
     * @param datetime the timestamp since last synchronised
     *
     * @return XML string of ISB XML information
     */
    public final String GetUsersUpToDate(final Calendar datetime) {
        return loadModifiedUsers(datetime);
    }

    /**
     * Gets the user details.
     *
     * @param userid the userid
     *
     * @return the string
     */
    public final String GetUserDetails(final String userid) {
        return loadUserDetails(userid);
    }

    /**
     * Load modified users.
     *
     * @param datetime the datetime
     *
     * @return XML string of ISB XML information
     */
    private String loadModifiedUsers(final Calendar datetime) {

        String xmlOutput = "";

        Collection<IsbEntityBean> isbEntities = new ArrayList<IsbEntityBean>();

        SearchBean search = searchDAO.initiate("isbentity", new UserBean());
        IsbEntityBean criteria = (IsbEntityBean) search.getSearchCriteria();
        IsbEntityBean constraints = (IsbEntityBean) search.getSearchCriteria();

        criteria.setCreatedDate(datetime.getTime());
        constraints.setCreatedDate(DataFilter.parseDate("31/12/2037", false));

        search.setSearchCriteria(criteria);
        search.setSearchConstraints(constraints);
        search.setLimit(0);

        // Load the list of changed ISB entities
        try {

            SearchResultsBean results = searchDAO.search(search);
            if (results != null && results.getSearchResults() != null) {
                for (Object result : results.getSearchResults()) {
                    IsbEntityBean entity = (IsbEntityBean) result;
                    isbEntities.add(entity);
                }
            }
        } catch (Exception e) {
            logger.error("Error loading list of changed ISB entities: " + e.getMessage());
        }

        PersonIsbXmlWriter xmlWriter = new PersonIsbXmlWriter();

        StringBuffer personXML = new StringBuffer();

        // Iterate through the changes, load the person + generate XML
        for (IsbEntityBean isbEntity : isbEntities) {
            try {
                PersonBean person = isbPersonTransactionDAO.loadPerson(isbEntity.getGUID());

                xmlWriter.setExistingPerson(person);
                xmlWriter.setUpdatedPerson(person);

                // Determine the action for this ISB entity
                String action = "modify";
                if (isbEntity.getModifiedDate() == null) {
                    action = "create";
                }
                if (!isbEntity.getActive()) {
                    action = "delete";
                }
                personXML.append(xmlWriter.publish(action));

            } catch (Exception e) {
                logger.error("Error generating XML for changed ISB entity: " + e.getMessage());
            }
        }

        // Place the personXML content into an ISB wrapper
        try {
            xmlOutput = xmlWriter.isbEnvelope(personXML.toString(), "whichdoctor", this.target);
            logger.debug("XML result: " + xmlOutput);
        } catch (Exception e) {
            logger.error("Error generating ISB XML envelope: " + e.getMessage());
        }
        return xmlOutput;
    }

    /**
     * Load user details.
     *
     * @param userid a string value representing the userid (MIN) of a requested person
     *
     * @return XML string of ISB XML information
     */
    private String loadUserDetails(final String userid) {

        String result = "";

        // Load the ISB entity, if it does not exist return an empty string
        IsbEntityBean isbEntity = null;
        try {
            isbEntity = isbEntityDAO.load(this.target, userid);
        } catch (Exception e) {
            logger.error("Error loading ISB entity (" + userid + "): " + e.getMessage());
        }

        if (isbEntity != null) {
            // This identity exists on the ISB target in some form
            PersonBean person = new PersonBean();

            try {
                person = isbPersonTransactionDAO.loadPerson(isbEntity.getGUID());
            } catch (Exception e) {
                logger.error("Error loading person: " + e.getMessage());
            }

            try {
                PersonIsbXmlWriter xmlWriter = new PersonIsbXmlWriter();
                xmlWriter.setExistingPerson(person);
                xmlWriter.setUpdatedPerson(person);

                // Determine the action for this ISB entity
                String action = "modify";
                if (isbEntity.getModifiedDate() == null) {
                    action = "create";
                }
                if (!isbEntity.getActive()) {
                    action = "delete";
                }

                result = xmlWriter.isbEnvelope(xmlWriter.publish(action), "whichdoctor", this.target);

            } catch (Exception e) {
                logger.error("Error generating ISB XML: " + e.getMessage());
            }
        }

        return result;
    }

    /**
     * Records the ISB message in the WhichDoctor datastore.
     *
     * @param source the source
     * @param targetVal the target
     * @param xmlPayload the xml payload
     *
     * @return the string
     */
    private String deliverMessage(final String source, final String targetVal, final String xmlPayload) {

        String outcome = "SUCCESS";

        IsbMessageBean isbMessage = new IsbMessageBean();

        if (logger.isDebugEnabled()) {
            logger.debug("ISB Message source: " + source);
            logger.debug("ISB Message target: " + targetVal);
            logger.debug("ISB Message xmlPayload: " + xmlPayload);
        }
        try {
            isbMessage.parseXmlPayload(xmlPayload);
            isbMessage.setTarget(targetVal);
            isbMessage.setSource(source);
            // Set the message to be inbound and unprocessed
            isbMessage.setIsInbound(true);
            isbMessage.setProcessed(false);

            logger.info("ISB message source: " + isbMessage.getSource());

            isbMessageDAO.create(isbMessage);

        } catch (JDOMException jdome) {
            logger.error("Error parsing ISB XML message: " + jdome.getMessage());
            outcome = "ERROR - Failed to parse ISB XML: " + jdome.getMessage();
        } catch (WhichDoctorDaoException wde) {
            logger.error("Error recording ISB XML message: " + wde.getMessage());
            outcome = "ERROR - Failed to record ISB message: " + wde.getMessage();
        }

        return outcome;
    }
}