All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sun.jbi.management.message.MessageBuilder Maven / Gradle / Ivy

Go to download

JBI Runtime Management components, providing installation, deployment, and other JMX interfaces for remote management consoles.

There is a newer version: 2.4.3
Show newest version
/*
 * BEGIN_HEADER - DO NOT EDIT
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://open-esb.dev.java.net/public/CDDLv1.0.html.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * HEADER in each file and include the License file at
 * https://open-esb.dev.java.net/public/CDDLv1.0.html.
 * If applicable add the following below this CDDL HEADER,
 * with the fields enclosed by brackets "[]" replaced with
 * your own identifying information: Portions Copyright
 * [year] [name of copyright owner]
 */

/*
 * @(#)MessageBuilder.java
 * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
 *
 * END_HEADER - DO NOT EDIT
 */
/**
 *  MessageBuilder.java
 *
 *  SUN PROPRIETARY/CONFIDENTIAL.
 *  This software is the proprietary information of Sun Microsystems, Inc.
 *  Use is subject to license terms.
 *
 *  Created on August 23, 2006, 5:17 PM
 */

package com.sun.jbi.management.message;



import com.sun.jbi.ServiceUnitInfo;
import com.sun.jbi.StringTranslator;
import com.sun.jbi.management.ComponentMessageHolder;
import com.sun.jbi.management.system.ManagementException;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.util.*;
import java.util.logging.Logger;

/**
 * Helper class to create Management messages
 *
 * @author Sun Microsystems, Inc.
 */
public class MessageBuilder
{
    public enum TaskResult  {SUCCESS, FAILED};
    public enum MessageType {ERROR, WARNING, INFO};
    
    // Used to determine if result messages are well-formed xml
    private static SAXParser sXmlParser;
    
    private ObjectFactory       mObjFactory;
    private Marshaller          mWriter;
    private Unmarshaller        mReader;
    private JAXBContext         mJaxbContext;
    private StringTranslator    mTranslator;
    private StringTranslator    mLocalTranslator;
    private Logger              mLog;
    
    private static final String TOKEN_PREFIX = "JBI";
    private static final String JBIMA0000    = "JBIMA0000";
    private static final String JBI_INSTANCE_NAME  = "JBI_INSTANCE_NAME";
        
    /**
     * Message class encapsulates the JbiTask message, two accessors provide the
     * message string and information on whether the message is a success or failure.
     */ 
    public class Message
    {
        private JbiTaskResult mTaskMsg;
        
        public Message(JbiTask task)
        {
            mTaskMsg = task; 
        }
        
        public Message(String jbiTaskMsg)
            throws ManagementException
        {
            mTaskMsg = getJbiTaskFromString(jbiTaskMsg);
        }
        
        /**
         * @return true if the TaskResult == SUCCESS, false otherwise
         */
        public boolean isSuccess()
        {
            JbiTaskResultElement 
                jbiTaskMsgType = mTaskMsg.getJbiTaskResult();
            
            String taskResult =
                jbiTaskMsgType.getFrmwkTaskResult().getFrmwkTaskResultDetails().getTaskResultDetails().getTaskResult();
            
            if ( TaskResult.SUCCESS == TaskResult.valueOf(taskResult))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        /**
         * @return true if the TaskResult == FAILURE, false otherwise
         */
        public boolean isFailure()
        {
            JbiTaskResultElement 
                jbiTaskMsgType = mTaskMsg.getJbiTaskResult();
            
            String taskResult =
                jbiTaskMsgType.getFrmwkTaskResult().getFrmwkTaskResultDetails().getTaskResultDetails().getTaskResult();
            
            if ( TaskResult.FAILED == TaskResult.valueOf(taskResult))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        /**
         * @return true if the TaskResult == SUCCESS and MsgType == WARNING, false otherwise
         */
        public boolean isSuccessWithWarning()
        {
            boolean isSuccess = false;
            boolean isWarning = false;
           
            JbiTaskResultElement 
                jbiTaskMsgType = mTaskMsg.getJbiTaskResult();
            
            String taskResult =
                jbiTaskMsgType.getFrmwkTaskResult().getFrmwkTaskResultDetails().getTaskResultDetails().getTaskResult();
            
            if ( TaskResult.SUCCESS == TaskResult.valueOf(taskResult))
            {
                isSuccess = true;
            }
            
            String msgType = 
                jbiTaskMsgType.getFrmwkTaskResult().getFrmwkTaskResultDetails().getTaskResultDetails().getMessageType();
  
            if ( MessageType.WARNING == MessageType.valueOf(msgType))
            {
                isWarning = true;
            }
            
            return (isSuccess && isWarning);
        }
        
        public String getMessage()
            throws ManagementException
        {
            return getString(mTaskMsg);
        }
    }
    
    
    private synchronized ObjectFactory getObjectFactory()
        throws JAXBException
    {
        if (mObjFactory == null)
        {
            mObjFactory = new ObjectFactory();
        }
        
        return mObjFactory;
    }
    
    /**
     * Create a message
     * @param jbiTaskMsg - task message string
     * @return created Message
     * @throws ManagementException
     */
    public Message createMessage(String jbiTaskMsg)
        throws ManagementException
    {
        return new Message(jbiTaskMsg);
    }
    
    public MessageBuilder(com.sun.jbi.StringTranslator translator)
        throws ManagementException
    {
        try
        {
            mTranslator = translator;
	    mLocalTranslator =
                com.sun.jbi.util.EnvironmentAccess.getContext().getStringTranslator("com.sun.jbi.management");

            mLog = Logger.getLogger("com.sun.jbi.management");
        }
        catch ( Exception ex)
        {
            throw new ManagementException(ex);
        }   
    }
    
         
    /**
     * Build a simple framework task message based on the passed 
     * parameters and return the string.
     */
    public String buildFrameworkMessage(String taskId, TaskResult taskResult, 
        List compMsgs)
            throws ManagementException
    {
        return buildFrameworkMessage(taskId, taskResult, null, null, new String[0], null,
            compMsgs);
    }
    
    /**
     * Build a simple framework task message based on the passed 
     * parameters and return the string.
     */
    public String buildFrameworkMessage(String taskId, TaskResult taskResult)
            throws ManagementException
    {
        return buildFrameworkMessage(taskId, taskResult, null, null, new String[0], null );
    }
    
    /**
     * Build a Framework Message with component task results
     */
    public String buildFrameworkMessage(String taskId, 
        TaskResult taskResult, MessageType messageType, String message,
        String [] params, String token, List compMsgs )
            throws ManagementException
    {
        try
        {
            message = getMessageString(message);
            
            JbiTask
                    jbiTaskMsg = buildTaskMsg(taskId, taskResult, messageType, 
                        message, params, token);

            if ( !compMsgs.isEmpty() )
            {
                appendComponentTaskResultMessages(jbiTaskMsg, compMsgs);
            }

            return getString(jbiTaskMsg);
        }
        catch ( JAXBException jex)
        {
            throw new ManagementException(jex);
        }
    }
     
    /**
     * Build a simple framework task message based on the passed 
     * parameters and return the string.
     */
    public String buildFrameworkMessage(String taskId, 
        TaskResult taskResult, MessageType messageType, String message,
        String [] params, String token )
            throws ManagementException
    {
            List 
                compMsgs = new ArrayList();
            
            return buildFrameworkMessage(taskId, taskResult, messageType, 
                message, params, token, compMsgs);
    };
    
   
    
    /**
     * Build a framework task message with exception. If the exception message is a 
     * jbi task message or a jbi localized message the message is returned as is. 
     *
     * @param taskId - name of the operation which threw the exception
     * @param ex     - the exception
     */
    public String buildExceptionMessage(String taskId, Throwable ex)
        throws ManagementException
    {
        try
        {
            String exMessage = ex.getMessage();
            if ( exMessage != null )
            {
                if ( isXmlString(exMessage))
                {
                    return exMessage;
                }
            }

            JbiTask taskMsg = null;
            if ( isLocalizedMessage(exMessage) )
            {
                taskMsg = buildTaskMsg(taskId, TaskResult.FAILED, MessageType.ERROR,
                    getMessageString(ex.getMessage()), new String[0], 
                    getMessageToken(exMessage));
                ex = ex.getCause();
            }
            else
            {
                taskMsg = buildTaskMsg(taskId, TaskResult.FAILED, MessageType.ERROR,
                    ex.getMessage(), new String[0], null);
            }

            // -- Append Exception Info
            if ( ex != null )
            {
                List
                exList = taskMsg.getJbiTaskResult().getFrmwkTaskResult().getFrmwkTaskResultDetails().
                    getTaskResultDetails().getExceptionInfo();
                appendExceptionInfo(exList, ex);
                ex.printStackTrace();
            }
            return getString(taskMsg);
        }
        catch ( JAXBException jex)
        {
            throw new ManagementException(jex);
        }
    }
    
    /**
     * @return the stack trace of the exception object as a string
     */
    public String getStackTrace(Throwable exObj)
    {
          StackTraceElement[] stckTrElem = exObj.getStackTrace();
          StringBuffer sb = new StringBuffer ("");
          if (stckTrElem != null)
          {
              for (StackTraceElement stckTrElem1 : stckTrElem) {
                  String stckTrace = stckTrElem1.toString();
                  sb.append (stckTrace);
                  sb.append ("\n");
              }
           }
          return sb.toString();
    }
    
    /**
     * Get the string from the management message object.
     */
    public String getString(JbiTaskResult jbiTaskMsg)
        throws ManagementException
    {
        String message = null;
        if ( jbiTaskMsg != null )
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            try
            {
                marshal(jbiTaskMsg, sw);
                message = sw.toString();
            }
            catch(Exception ex)
            {
                throw new ManagementException(ex);
            }
            finally
            {
                try
                
                {
                    sw.close();
                }
                catch( java.io.IOException ioex )
                {
                    
                }
            }
            
        }
        return message;
    }
    
    
    /** Returns the JBIMAxxxx mesage token from a localized message entry. */
    public static String getMessageToken(String message)
    {
        // -- Get the token only if one exists else return JBIMA0000
        if ( isLocalizedMessage(message) && message.length() >= 9 )
        {
            return message.substring(0,9);
        }
        else
        {
            return JBIMA0000;
        }
    }
    
    /** Returns the string from a message entry without the JBIMAxxxx token. */
    public static String getMessageString(String message)
    {
        // Changed for for open-esb L10n issue 358 
        // so that the default bundles should be processed as before,
        // but now skips mistranslated and out-of-order "fillers" 
        // primarily in the _fr, _zh_CH, and _zh_TW locales.

        final String A_COLON = ":"; // ASCII colon; not-I18n (to be compared to I18n)
        final String A_SPACE = " "; // ASCII space, not-I18n
        final String FILLER_TEMPLATE = ": "; // not-I18n
        final String ID_TEMPLATE = "JBIxxnnnn"; // not-I18n
        final String U_COLON = "\uff1a"; // unicode colon; not-I18n
        final String U_NBSP = "\u00a0"; // unicode non-breaking space; not-I18n
            
        if ( isLocalizedMessage(message) )
        {
            if ( (ID_TEMPLATE.length() +
                  FILLER_TEMPLATE.length()) < 
                  message.length() )
            {
                int textStartsAt = ID_TEMPLATE.length(); // e.g. nine

                // skips (zero or) up to two "filler" characters:
                for (int i = 0; i < FILLER_TEMPLATE.length(); ++i)
                    {
                        String next = 
                            message.substring(textStartsAt,
                                              textStartsAt + 1);
                        if ((A_COLON.equals(next)) 
                            ||(A_SPACE.equals(next))
                            ||(U_COLON.equals(next)) 
                            ||(U_NBSP.equals(next))) 
                            {
                                ++textStartsAt; // skips the next "filler"
                            }
                    }
                return message.substring(textStartsAt); // nine to eleven
            }
            else
            {
                // Message which has a token but no message string
                return "";
            }
        }
        else
        {
            return message;
        }
    }
    
    public void throwManagementException(String taskId, String msgKey, String[] params)
        throws ManagementException
    {
        String message = mTranslator.getString(msgKey, params);
        String response = buildFrameworkMessage(taskId,
            TaskResult.FAILED, MessageType.ERROR,
            getMessageString(message), params, getMessageToken(message));
        mLog.fine(response);
        throw new ManagementException(response);
    }   
    
    
    /**
     * Parse the Component Results. This is based on the fact that the
     * ServiceUnitList obtained from a ServiceAssemblyInfo and the ComponentTaskResults
     * follow the document order of the ServiceUnits in the Service Assembly jbi.xml.
     *
     * The DeploymentService should also append a ComponentTaskResult for each Service
     * Unit in the Service Assembly. 
     */
    public List getSuccessfulServiceUnits(String jbiTaskMsg,
        List suInfoList) throws ManagementException
    {
        List suList = new ArrayList();
        
        JbiTask jbiTask = getJbiTaskFromString(jbiTaskMsg);
            
        if ( jbiTask != null )
        {
            List compResults = jbiTask.getJbiTaskResult().
                getComponentTaskResult();
            
            int i = 0;
            
            
            for (ComponentTaskResult compResult : compResults ) 
            {
                TaskResultDetailsElement taskDetails = ((TaskResultDetails) 
                    compResult.getComponentTaskResultDetails()).getTaskResultDetails();
                
                String taskResult = taskDetails.getTaskResult();
                if ( TaskResult.SUCCESS == TaskResult.valueOf(taskResult) )
                {
                    boolean matchFound     = false;
                    ServiceUnitInfo suInfo = null;
                    while (!matchFound && i < suInfoList.size())
                    {
                        suInfo = suInfoList.get(i++);
                        if ( !suInfo.getTargetComponent().equals(compResult.getComponentName())) 
                        {
                            
                            String[] params = new String[]{suInfo.getName(), suInfo.getTargetComponent() };
                            String wrnMsg = mLocalTranslator.getString(
                                com.sun.jbi.management.LocalStringKeys.DS_SU_OP_FAILED, params);
                            continue;
                        }
                        else
                        {
                            matchFound = true;
                        }
                    }
                    if ( matchFound )
                    {
                        suList.add(suInfo);
                    }
                }
            }
        }
        return suList;
    }
    
    /**
     * This method composes a JBI Task Message from the exceptions in the Map. In
     * cases of complete failure what we get back from the remote instance is an
     * exception, which ( hopefully ) has a jbi task message as the message. If the
     * exceptions message is not a jbi task message, then this will build a jbi task
     * message from it.
     *
     * This composition is required only in the complete failure cases.
     *
     * @param exceptionMap - a map keyed by the instance names and the value is the
     * exception thrown by the remote instance with the MBean exceptions stripped off.
     * @return a composite JBI Task message that has all the information.
     * 
     */
    public String buildCompositeExceptionMessage(String taskId, java.util.Map exceptionMap)
        throws ManagementException
    {
        
        List exceptions = new ArrayList();
        List taskMsgs   = new ArrayList();
        List taskResults   = new ArrayList();
        List msgTypes     = new ArrayList();
        
        java.util.Set instances = exceptionMap.keySet();
        try
        {
            for ( String instance : instances )
            {
                Exception ex = (Exception) exceptionMap.get(instance);

                JbiTask jbiTask = getJbiTaskMessage(taskId, ex);

                taskResults.add(getTaskResult(jbiTask));

                MessageType msgType = getMessageType(jbiTask);
                if ( msgType != null )
                {
                    msgTypes.add(msgType);
                }

                List 
                    instTaskMsgs = getTaskStatusMsgs(jbiTask);

                if ( !instTaskMsgs.isEmpty() )
                {
                    // -- Add the marker instance status message
                    taskMsgs.add(buildTaskStatusMsg(instance, JBI_INSTANCE_NAME, new String[0]));
                }

                List 
                    instExceptions = getExceptionInfos(jbiTask);

                if ( !instExceptions.isEmpty() )
                {
                    // -- Add the marker exception-info for the instance
                    exceptions.add(buildExceptionInfo(instance, JBI_INSTANCE_NAME, new String[0]));
                }

                taskMsgs.addAll(instTaskMsgs);
                exceptions.addAll(instExceptions);   
            }

            JbiTask compositeTask = null;

            compositeTask = buildTaskMsg(taskId, getEffectiveTaskResult(taskResults, true), 
                getEffectiveMessageType(msgTypes),
                null, new String[0], null);

            compositeTask = appendTaskMsgs(compositeTask, taskMsgs);
            
            compositeTask = appendExceptionInfos(compositeTask, exceptions);
            return getString(compositeTask);
        }
        catch (javax.xml.bind.JAXBException jex )
        {
            throw new ManagementException(jex);
        }
        
        
        
    }
    
    /**
     * This operation combines the data from exception jbi task messages and response
     * jbi task messages. The primary user of this operation is the facade DeploymentSvc.
     *
     * @param taskId - task id
     * @param responseMap -  a map of jbi task message responses from instances.
     * @param exceptionMap - a map of exception task message from instances.
     * @param requireAllSuccess - this flag indicates how the result of component task
     * results for each component from various instances has to be handled. If set to true
     * a Component task result has a task result of SUCCESS only if all the ComponentTask
     * results in the response and exception maps are a success.
     */
    public Message buildCompositeMessage(String taskId, Map responseMap, 
        Map exceptionMap, boolean requireAllSuccess) 
            throws ManagementException
    {
        List exceptions = new ArrayList();
        List taskMsgs = new ArrayList();
        ComponentInstanceResult[] compResultData = null;
        
        Map jbiTasks = new HashMap();

        List rslts = new ArrayList();
        
        if ( !responseMap.isEmpty() )
        {
            java.util.Set instances = responseMap.keySet();
            for ( String instance : instances )
            {
                JbiTask jbiTask = getJbiTaskFromString(responseMap.get(instance));
                TaskResult 
                    rslt = TaskResult.valueOf(jbiTask.getJbiTaskResult().getFrmwkTaskResult().
                        getFrmwkTaskResultDetails().getTaskResultDetails().getTaskResult());
                rslts.add(rslt);
                jbiTasks.put(instance, jbiTask);
            }
        }
        
        if ( !exceptionMap.isEmpty() )
        {
            java.util.Set instances = exceptionMap.keySet();
            for ( String instance : instances )
            {
                Exception ex = (Exception) exceptionMap.get(instance);

                JbiTask  jbiTask = getJbiTaskMessage(taskId, ex);
                TaskResult 
                    rslt = TaskResult.valueOf(jbiTask.getJbiTaskResult().getFrmwkTaskResult().
                        getFrmwkTaskResultDetails().getTaskResultDetails().getTaskResult());
                rslts.add(rslt);
                jbiTasks.put(instance, jbiTask);
            }
        }
        
        JbiTask compositeTask = null;
        try
        {
            compResultData = extractMessageData(jbiTasks, taskMsgs, exceptions, compResultData);

            compositeTask = buildTaskMsg(taskId, TaskResult.FAILED, MessageType.ERROR,
                null, new String[0], null);

            compositeTask = appendTaskMsgs(compositeTask, taskMsgs);
            
            compositeTask = appendExceptionInfos(compositeTask, exceptions);
            
            List compResults = buildComponentTaskResults(taskId, 
                compResultData, requireAllSuccess);
            compositeTask = appendComponentTaskResult(compositeTask, compResults);
            
            
            for ( ComponentTaskResult compResult: compResults )
            {
                TaskResult 
                    rslt = TaskResult.valueOf(compResult.getComponentTaskResultDetails().
                    getTaskResultDetails().getTaskResult());
                rslts.add(rslt);
            }
            
            // set the corrected task result
            TaskResult theResult = TaskResult.SUCCESS;
            if ( !rslts.isEmpty() )
            {
                theResult = getEffectiveTaskResult(rslts, requireAllSuccess);
            }
            else
            {
                if ( responseMap.isEmpty() && !exceptionMap.isEmpty() )
                {
                    theResult = TaskResult.FAILED;
                }
            }
            
            if ( TaskResult.SUCCESS == theResult )
            {
                TaskResultDetailsElement taskDetails = compositeTask.getJbiTaskResult().
                    getFrmwkTaskResult().
                    getFrmwkTaskResultDetails().
                    getTaskResultDetails();
                
                taskDetails.setTaskResult(theResult.toString());
                MessageType type = getEffectiveMessageType(rslts, requireAllSuccess);
                taskDetails.setMessageType(type.toString());
            }
            return new Message(compositeTask);
        }
        catch (javax.xml.bind.JAXBException jex )
        {
            throw new ManagementException(jex);
        }
        
        
    }
    
    
    
    // -- This is the single op from the ManagementMessageBuilder Interface
    /** 
     * Return an XML string of the component message(either status
     *   or exception message).
     * @param msgObject component message holder object
     * @return Message as XML string
     * @throws Exception if unable to build message
     *
     */
    String buildComponentMessage (ComponentMessageHolder msgObject)
        throws Exception
    {
        return getString(buildComponentTaskResult(msgObject));
    }
        /**
     * This method is used to check if the given string contains well-formed
     * XML.
     * @param str the string
     * @return true if the given string is xml
     */
    public static boolean isXmlString(String str)
    {
        boolean isXmlString = false;
        
        // make sure there is something to validate and there is something to
        // validate it with
        if (str != null)
        {
            try
            {
                if (sXmlParser == null)
                {
                  sXmlParser = SAXParserFactory.newInstance().newSAXParser();
                }
                synchronized (sXmlParser)
                {
                    sXmlParser.parse(
                            new InputSource(new StringReader(str)),
                            new DefaultHandler());
                }
                
                isXmlString = true;
            }
            catch (Exception ex)
            {
                // This is expected in cases where the result is not XML
            }
        }
        
        return isXmlString;
    }
    
    /**
     * @return true if the message starts with JBIMA
     */
    public static boolean isLocalizedMessage(String message)
    {
        boolean isLocMsg = false;
        
        if ( message != null )
        {
            // The message should be at least 9 chars long ( 1-9 - token)
            isLocMsg = ( message.trim().startsWith(TOKEN_PREFIX) && message.length() >= 9 );
        }
        return isLocMsg;
    }
    
    /*--------------------------------------------------------------------------------*\
     *                        Private Helpers                                         *
    \*--------------------------------------------------------------------------------*/
    
    /**
     * Append ExceptionInfo's to the exception info list. An exception info is added
     * for each exception in the chain with a nesting level = number of exceptions 
     * in the chain.
     */
    private void appendExceptionInfo(List exList, Throwable ex)
        throws JAXBException
    {       
        int nestingLevel = 1;
        while ( ex != null )
        {
            if ((ex.getMessage() == null) ||
                    (ex.getMessage().compareTo("") == 0))
            {
                nestingLevel += 1;
                ex = ex.getCause();
                continue;
            }
            ExceptionInfo exInfo = getObjectFactory().createExceptionInfo();
            
            exInfo.setNestingLevel(String.valueOf(nestingLevel));
            /** The extends message could be a jbi localized message, we don't
                have the localized params, but atleast salvage the token */
            MsgLocInfo msgLocInfo = buildMsgLocInfo(
                getMessageString(ex.getMessage()), getMessageToken(ex.getMessage()), new String[0]);
            exInfo.setMsgLocInfo(msgLocInfo);
            exInfo.setStackTrace(getStackTrace(ex));
            
            // -- append the exception info
            exList.add(exInfo);
            nestingLevel += 1;
            ex = ex.getCause();
        }
    }
    
    /**
     * Append ExceptionInfo's to the exception info list for a Component Task result. 
     * An exception info is added for each exception in the chain with a nesting level 
     * = number of exceptions in the chain. If the loc message info is set in the
     * ComponentMessageHolder use that
     */
    private void appendExceptionInfo(List exList, Throwable ex,
        ComponentMessageHolder compMsg)
        throws JAXBException
    {       
        int nestingLevel = 1;
        while ( ex != null )
        {
            ExceptionInfo exInfo = getObjectFactory().createExceptionInfo();
            
            exInfo.setNestingLevel(String.valueOf(nestingLevel));
            
            MsgLocInfo msgLocInfo = null;        
            if ( compMsg.getLocMessage(nestingLevel) != null )
            {
                msgLocInfo = buildMsgLocInfo(
                    compMsg.getLocMessage(nestingLevel), 
                    compMsg.getLocToken(nestingLevel), 
                    compMsg.getLocParam(nestingLevel));
            }
            else
            {
                msgLocInfo = buildMsgLocInfo(ex.toString(), null, new String[0]);
            }
            
            exInfo.setMsgLocInfo(msgLocInfo);
            
            exInfo.setStackTrace(getStackTrace(ex));
            
            // -- append the exception info
            exList.add(exInfo);
            nestingLevel += 1;
            ex = ex.getCause();
        }
    }
    
    /**
     * 
     */
    private JbiTask buildTaskMsg(String taskId, 
        TaskResult taskResult, MessageType messageType, String message,
        String [] params, String token)
            throws JAXBException
    {
        JbiTask jbiTask = getObjectFactory().createJbiTask();
        
        JbiTaskResultElement
            jbiTaskMsgType = getObjectFactory().createJbiTaskResultElement();

        FrmwkTaskResult
            fmwkTaskResult =  getObjectFactory().createFrmwkTaskResult();

        FrmwkTaskResultDetails 
            fmwkTaskResultDetails = getObjectFactory().createFrmwkTaskResultDetails();

        TaskResultDetailsElement 
            taskResultDetails = getObjectFactory().createTaskResultDetailsElement();

        taskResultDetails.setTaskId(taskId);
        taskResultDetails.setTaskResult(taskResult.toString());

        if ( messageType != null )
        {
            taskResultDetails.setMessageType(messageType.toString());
        }

        // - Task Status Message
        if ( message != null )
        {
            TaskStatusMsg taskStatusMsg = buildTaskStatusMsg(message, token, params);

            taskResultDetails.getTaskStatusMsg().add(taskStatusMsg);
        }

        fmwkTaskResultDetails.setLocale(java.util.Locale.getDefault().toString());

        fmwkTaskResultDetails.setTaskResultDetails(taskResultDetails);
        fmwkTaskResult.setFrmwkTaskResultDetails(fmwkTaskResultDetails);

        jbiTaskMsgType.setFrmwkTaskResult(fmwkTaskResult);
        //jbiTaskMsg.setJbiTaskResult(jbiTaskMsgType);
        
        jbiTask.setJbiTaskResult(jbiTaskMsgType);
        jbiTask.setVersion(new java.math.BigDecimal("1.0"));
        return jbiTask;
    }

    
    /**
     * Build a general task-status-msg based on passed params.
     */
    private TaskStatusMsg buildTaskStatusMsg(String message, String token, String[] params)
        throws JAXBException
    {
    
        MsgLocInfo msgLocInfo = buildMsgLocInfo(message, token, params);
        TaskStatusMsg taskStatusMsg = getObjectFactory().createTaskStatusMsg();
        taskStatusMsg.setMsgLocInfo(msgLocInfo);
        
        return taskStatusMsg;
    }  
    
    /**
     * Build a general Exception info based on the passed params.
     */
    private ExceptionInfo buildExceptionInfo(String message, String token, String[] params)
        throws JAXBException
    {
        MsgLocInfo msgLocInfo = buildMsgLocInfo(message, token, params);
        ExceptionInfo exceptionInfo = getObjectFactory().createExceptionInfo();
        exceptionInfo.setMsgLocInfo(msgLocInfo);
        exceptionInfo.setNestingLevel("0");
        
        return exceptionInfo;
    }
    
    /**
     * Build a MsgLocInfo based on the passed parameters
     */
    private MsgLocInfo buildMsgLocInfo(String message, String token, String[] params)
        throws JAXBException
    {
        MsgLocInfo msgLocInfo = getObjectFactory().createMsgLocInfo();

        msgLocInfo.setLocMessage(message);

        if ( token != null )
        {
            msgLocInfo.setLocToken(token);   
        }
        else
        {
            msgLocInfo.setLocToken(JBIMA0000);   
        }
        java.util.List locParams = msgLocInfo.getLocParam();
        for ( String param : params )
        {
            locParams.add(param);
        }
        
        return msgLocInfo;
    }
    
    /**
     * Get the JbiTask Message JAXB object from the message string version
     */
    private JbiTask getJbiTaskFromString(String jbiTaskMsg)
        throws ManagementException
    {
        try
        {
            StringBuffer strBuf = new StringBuffer(jbiTaskMsg);
            return  (JbiTask) unmarshal( new StreamSource( 
                new java.io.StringReader( strBuf.toString())));
        }
        catch (Exception jex )
        {
            throw new ManagementException(jex);
        }
    }
    
    /**
     *
     */
    private JbiTask getJbiTaskMessage(String taskId, Exception ex)
        throws ManagementException
    {
        JbiTask jbiTask = null;
        if ( isXmlString(ex.getMessage()) )
        {
            jbiTask = getJbiTaskFromString(ex.getMessage());
        }
        else
        {
            try
            {
                jbiTask = buildTaskMsg(taskId, TaskResult.FAILED, MessageType.ERROR,
                    ex.getMessage(), new String[0], null);
                
                // -- Append Exception Info
                List 
                    exList = jbiTask.getJbiTaskResult().getFrmwkTaskResult().getFrmwkTaskResultDetails().
                        getTaskResultDetails().getExceptionInfo();
                appendExceptionInfo(exList, ex);
            }
            catch (javax.xml.bind.JAXBException jex )
            {
                throw new ManagementException(jex);
            }
        }
        
        return jbiTask;
    }
    
    /**
     * Append Component Task results to the JbiTask message.
     *
     * @param 
     */
    private void appendComponentTaskResultMessages(JbiTask jbiTaskMsg, 
        List compMsgs) throws JAXBException
    {
        if ( jbiTaskMsg != null )
        {
            JbiTaskResultElement
                taskResult = jbiTaskMsg.getJbiTaskResult();
            
            if (taskResult != null )
            {
                List 
                    comTaskResults = taskResult.getComponentTaskResult();

                for (ComponentMessageHolder compMsg : compMsgs)
                {
                    comTaskResults.add(buildComponentTaskResult(compMsg));
                }
            }
        }
    }
    
    /**
     * Build a Component Task Result from the ComponentMessageHolder
     */
    private ComponentTaskResult buildComponentTaskResult(ComponentMessageHolder compMsg)
        throws JAXBException
    {
        ComponentTaskResult compRslt = getObjectFactory().createComponentTaskResult();
        
        compRslt.setComponentName(compMsg.getComponentName());
        
        TaskResultDetailsElement 
            taskResultDetailsElement = getObjectFactory().createTaskResultDetailsElement();

        TaskResultDetails 
            taskResultDetails = getObjectFactory().createTaskResultDetails();
                
        taskResultDetailsElement.setTaskId(compMsg.getTaskName());
        taskResultDetailsElement.setTaskResult(compMsg.getTaskResult());

        if ( compMsg.getStatusMessageType() != null )
        {
            taskResultDetailsElement.setMessageType(MessageType.valueOf(
                compMsg.getStatusMessageType()).toString());
        }

        // - Task Status Message
        // -- ComponentMessageHolder does not accomodate TaskStatusMsg !!


        // -- Exception Info
        if ( compMsg.getExceptionObject() != null )
        {
            appendExceptionInfo(taskResultDetailsElement.getExceptionInfo(), 
                compMsg.getExceptionObject(), compMsg );
        }
        taskResultDetails.setTaskResultDetails(taskResultDetailsElement);
        compRslt.setComponentTaskResultDetails(taskResultDetails);
        
        return compRslt;
    }
    
    /**
     * Get the String for the ComponentTaskResult
     */
        /**
     * Get the string from the management message object.
     */
    private String getString(ComponentTaskResult compTaskResult)
        throws ManagementException
    {
        String message = null;
        if ( compTaskResult != null )
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            try
            {
                marshal(compTaskResult, sw);
                message = sw.toString();
            }
            catch(Exception ex)
            {
                throw new ManagementException(ex);
            }
            finally
            {
                try
                
                {
                    sw.close();
                }
                catch( java.io.IOException ioex )
                {
                    
                }
            }
        }
        return message;
    }
    
    private List getTaskStatusMsgs(JbiTask jbiTask)
    {
        return jbiTask.getJbiTaskResult().getFrmwkTaskResult().
            getFrmwkTaskResultDetails().getTaskResultDetails().getTaskStatusMsg();
    }
    
    private List getExceptionInfos(JbiTask jbiTask)
    {
        return jbiTask.getJbiTaskResult().getFrmwkTaskResult().
                getFrmwkTaskResultDetails().getTaskResultDetails().getExceptionInfo();
            
    }
    
    /**
     * Append the list of task status messages to the framework task result details.
     */
    private JbiTask appendTaskMsgs(JbiTask jbiTask, List taskMsgs)
    {
        TaskResultDetailsElement details = jbiTask.getJbiTaskResult().getFrmwkTaskResult().
                getFrmwkTaskResultDetails().getTaskResultDetails();

        for ( TaskStatusMsg taskMsg : taskMsgs)
        {
            details.getTaskStatusMsg().add(taskMsg);
        }
        
        return jbiTask;   
    }
    
    /**
     * Append the list of exception infos to the framework task result details.
     */
    private JbiTask appendExceptionInfos(JbiTask jbiTask, List exceptions)
    
    {
       TaskResultDetailsElement details = jbiTask.getJbiTaskResult().getFrmwkTaskResult().
            getFrmwkTaskResultDetails().getTaskResultDetails();

        for (ExceptionInfo exInfo : exceptions )
        {
            details.getExceptionInfo().add(exInfo);
        }
        
        return jbiTask;
    }
    
    /**
     * For each component in compResultData, build a single ComponentTaskResult with
     * all the task status msgs and exception infos from all the TaskResultDetails
     * for the component. 
     *
     * If requireAllSuccess is true then the ComponentTaskResult has a status of SUCCESS
     * if all TaskResultDetails have a SUCCESS task result.
     */
    private List buildComponentTaskResults(String taskId,  
        ComponentInstanceResult[] compResultData, boolean requireAllSuccess)
            throws JAXBException
    {
        List compResults = new ArrayList();
        
        List taskResults = new ArrayList();
        
        for ( ComponentInstanceResult compInstResult : compResultData )
        {
            ComponentTaskResult compRslt = getObjectFactory().createComponentTaskResult();
        
            compRslt.setComponentName(compInstResult.getComponentName());
        
        
            TaskResultDetailsElement 
                taskResultDetails = getObjectFactory().createTaskResultDetailsElement();

            taskResultDetails.setTaskId(taskId);
           
            Map compInstanceDetails = 
                (Map) compInstResult.getInstanceResults();
   
            Set instances =   compInstanceDetails.keySet();
   
            for ( String instance : instances )
            {
                TaskResultDetailsElement details = 
                    (TaskResultDetailsElement) compInstanceDetails.get(instance);
            
                // Get the task status msg and any exception infos from the component
                // task result details
                List instTaskMsgs = details.getTaskStatusMsg(); 
                if ( !instTaskMsgs.isEmpty() )
                {
                   taskResultDetails.getTaskStatusMsg().add(buildTaskStatusMsg(instance, 
                       JBI_INSTANCE_NAME, new String[0]));     
                }
                taskResultDetails.getTaskStatusMsg().addAll(instTaskMsgs);

                List instExceptions = details.getExceptionInfo();
                if ( !instExceptions.isEmpty() )
                {
                   taskResultDetails.getExceptionInfo().add(buildExceptionInfo(instance, 
                       JBI_INSTANCE_NAME, new String[0]));     

                }
                taskResultDetails.getExceptionInfo().addAll(instExceptions);
                taskResults.add(TaskResult.valueOf(details.getTaskResult())); 
            } 

            TaskResult rslt = getEffectiveTaskResult(taskResults, requireAllSuccess);
            taskResultDetails.setTaskResult(rslt.toString());
            MessageType type = getEffectiveMessageType(taskResults, requireAllSuccess);
            taskResultDetails.setMessageType(type.toString());
         
            // Task Result Details
            TaskResultDetails 
                compTaskResultDetails = getObjectFactory().createTaskResultDetails();

            compTaskResultDetails.setTaskResultDetails(taskResultDetails);
            compRslt.setComponentTaskResultDetails(compTaskResultDetails);
            compResults.add(compRslt);
        }

        
        return compResults;
        
    }
    
    /**
     *
     */
    private ComponentInstanceResult[] extractMessageData(Map jbiTasks, List taskMsgs,
        List exceptions, ComponentInstanceResult[]  compResultData)
        throws javax.xml.bind.JAXBException
    {
        Set instances = jbiTasks.keySet();

        for ( String instance : instances )
        {
            JbiTask jbiTask = jbiTasks.get(instance);

            List instTaskMsgs   = getTaskStatusMsgs(jbiTask);
            List instExceptions = getExceptionInfos(jbiTask);

            if ( !instTaskMsgs.isEmpty() )
            {
                // -- Add the marker instance status message
                taskMsgs.add(buildTaskStatusMsg(instance, JBI_INSTANCE_NAME, new String[0]));
            }

            taskMsgs.addAll(instTaskMsgs);

            if ( !instExceptions.isEmpty() )
            {
                // -- Add the marker instance  exception info
                exceptions.add(buildExceptionInfo(instance, JBI_INSTANCE_NAME, new String[0]));
            }

            exceptions.addAll(instExceptions);   

            List compResults = jbiTask.getJbiTaskResult().
                getComponentTaskResult();
                
            int compOrder = 0;
            if ( compResults.size() > 0 )
            {
                if ( compResultData == null )
                {
                    compResultData = new ComponentInstanceResult[compResults.size()];
                }
            }
            for (ComponentTaskResult compResult : compResults ) 
            {
                String compName = compResult.getComponentName();
                
                if ( compResultData[compOrder] == null )
                {
                    HashMap instMap = new HashMap();
                    compResultData[compOrder] = new ComponentInstanceResult(compName, new HashMap());
                }
                
                TaskResultDetailsElement taskDetails = ((TaskResultDetails) 
                    compResult.getComponentTaskResultDetails()).getTaskResultDetails();
                
                Map instMap = compResultData[compOrder].getInstanceResults();
                instMap.put(instance, taskDetails);
                compOrder++;
            }
        }
        
        // -- If there are no component results return a zero size array
        if ( compResultData == null ) 
        {
             compResultData = new ComponentInstanceResult[0];
        }
        return compResultData;
    }
    
    /**
     *
     */
    private TaskResult getEffectiveTaskResult(List taskResults,
        boolean requireAllSuccess)
    {
        TaskResult rslt = TaskResult.FAILED;
        if ( requireAllSuccess )
        {
            if ( taskResults.contains(TaskResult.FAILED) )
            {
                rslt = TaskResult.FAILED;
            }
            else
            {
                rslt = TaskResult.SUCCESS;
            }
        }
        else if ( taskResults.contains(TaskResult.SUCCESS) )
        {
            rslt = TaskResult.SUCCESS;
        }
        return rslt;
    }
    
    /**
     * @param taskResults - task results based on which the message type is to be determined.
     * @param requireAllSuccess - if this is true, then even a single FAILED task result results
     *                            in a MessageType of ERROR. If false, then a single failed task 
     *                            result implies a MessageType of WARNING. 
     * @return the effective MessageType.
     */
    private MessageType getEffectiveMessageType(List taskResults,
        boolean requireAllSuccess)
    {
        MessageType type = MessageType.INFO;
        if ( requireAllSuccess )
        {
            if ( taskResults.contains(TaskResult.FAILED) )
            {
                type = MessageType.ERROR;
            }
            else
            {
                type = MessageType.INFO;
            }
        }
        else if ( taskResults.contains(TaskResult.FAILED) )
        {
            type = MessageType.WARNING;
        }
        return type;
    }
    
    /**
     *
     */
    private JbiTask appendComponentTaskResult(JbiTask jbiTask, List compResults)
    {
        jbiTask.getJbiTaskResult().
                getComponentTaskResult().addAll(compResults);
        
        return jbiTask;
    }
    
    
    /**
     * Get the  from the framework task result message.
     */
    private TaskResult getTaskResult(JbiTask jbiTask)
    {
        TaskResult rslt = TaskResult.FAILED;
        
        TaskResultDetailsElement details = getTaskResultDetails(jbiTask);
        
        if ( details != null )
        {
            String result = details.getTaskResult();
            rslt = TaskResult.valueOf(result);
        }
        return rslt;
    }
    
    /**
     * Get the  from the framework task result message.
     */
    private MessageType getMessageType(JbiTask jbiTask)
    {
        MessageType type = null;
        
        TaskResultDetailsElement details = getTaskResultDetails(jbiTask);
        
        if ( details != null )
        {
            String msgType = details.getMessageType();
            if ( msgType != null )
            {
                type = MessageType.valueOf(msgType);
            }
        }
        return type;
    }
    
    
    
    /**
     * @return the TaskResultDetails from the framework task result
     */
    private TaskResultDetailsElement getTaskResultDetails(JbiTask jbiTask)
    {
        TaskResultDetailsElement detailsType = null;
        JbiTaskResultElement jbiTaskRsltType = jbiTask.getJbiTaskResult();
        
        if ( jbiTaskRsltType != null )
        {
            FrmwkTaskResult fmwkRslt = jbiTaskRsltType.getFrmwkTaskResult();
            
            if (fmwkRslt != null)
            {
                FrmwkTaskResultDetails details = fmwkRslt.getFrmwkTaskResultDetails();
                
                if ( details != null )
                {
                    detailsType = details.getTaskResultDetails();
                }
            }
        } 
        return detailsType;
    }
    
    /**
     * Get the effective message type from the list of message types. The effective type 
     * is the most severe type
     */
    private MessageType getEffectiveMessageType(List msgTypes)
    {
        MessageType msgType = null;
        
        if ( !msgTypes.isEmpty() )
        {
            if ( msgTypes.contains(MessageType.ERROR))
            {
                msgType = MessageType.ERROR;
            }
            else if ( msgTypes.contains(MessageType.WARNING))
            {
                msgType = MessageType.WARNING;
            }
            else
            {
               msgType = MessageType.INFO;
            }
        }
        return msgType;
    }
    
    /** Provides a reference to the JAXB context for management messages, 
     *  initializing one if necessary.
     * @throws Excepion if the JAXB Context cannot be initialized
     */
    private synchronized JAXBContext getJaxbContext()
        throws Exception
    {
        if ( mJaxbContext == null )
        {
            ClassLoader cl = 
                    Class.forName(
                        "com.sun.jbi.management.message.JbiTaskResult").
                        getClassLoader();
            mJaxbContext = JAXBContext.newInstance( "com.sun.jbi.management.message", cl);
        }
        
        return mJaxbContext;
    }
    
    /** Synchronizes access to the non thread-safe Marshaller for this context.
     */
    private synchronized void marshal(Object jaxbElement, java.io.Writer writer)
        throws Exception
    {
        if (mWriter == null)
        {
            mWriter = getJaxbContext().createMarshaller();
        }
        
        mWriter.marshal(jaxbElement, writer);
    }
    
    /** Synchronizes access to the non thread-safe Unmarshaller for this context.
     */
    private synchronized Object unmarshal(StreamSource input)
        throws Exception
    {
        if (mReader == null)
        {
            mReader = getJaxbContext().createUnmarshaller();
        }
        
        return mReader.unmarshal(input);
    }    
    
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy