Package org.apache.yoko.bindings.corba

Source Code of org.apache.yoko.bindings.corba.CorbaConduit

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.yoko.bindings.corba;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.namespace.QName;

import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.AbstractCachedOutputStream;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.transport.MessageObserver;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.schemas.yoko.bindings.corba.AddressType;
import org.apache.schemas.yoko.bindings.corba.OperationType;
import org.apache.schemas.yoko.bindings.corba.RaisesType;
import org.apache.schemas.yoko.bindings.corba.TypeMappingType;
import org.apache.yoko.bindings.corba.types.CorbaHandlerUtils;
import org.apache.yoko.bindings.corba.types.CorbaObjectHandler;
import org.apache.yoko.wsdl.CorbaConstants;

import org.omg.CORBA.Any;
import org.omg.CORBA.Context;
import org.omg.CORBA.ContextList;
import org.omg.CORBA.ExceptionList;
import org.omg.CORBA.NVList;
import org.omg.CORBA.NamedValue;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Request;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.UnknownUserException;


public class CorbaConduit implements Conduit {
    private static final Logger LOG = LogUtils.getL7dLogger(CorbaConduit.class);

    private EndpointInfo endpointInfo;
    private EndpointReferenceType target;
    private MessageObserver incomingObserver;
    private ORB orb;
    private OrbConfig orbConfig;

    public CorbaConduit(EndpointInfo ei, EndpointReferenceType ref, OrbConfig config) {
        endpointInfo = ei;
        target = getTargetReference(ref);
        orbConfig = config;
        // TODO: Set any additional properties needed to initialize the ORB  before
        // we initialize it.
        java.util.Properties props = System.getProperties();
        props.put("org.omg.CORBA.ORBClass", orbConfig.getOrbClass());
        props.put("org.omg.CORBA.ORBSingletonClass", orbConfig.getOrbSingletonClass());
        props.put("yoko.orb.id", "Yoko-Client-Binding");
        List<String> orbArgs = orbConfig.getOrbArgs();
        orb = ORB.init(orbArgs.toArray(new String[orbArgs.size()]), props);
        if (orb == null) {
            LOG.severe("Could not create instance of the ORB");
            throw new CorbaBindingException("Could not create instance of the ORB");
        }
    }

    public void send(Message message) throws IOException {   
        try {
            AddressType address = endpointInfo.getExtensor(AddressType.class);

            if (address == null) {
                LOG.log(Level.SEVERE, "Unable to locate a valid CORBA address");
                throw new CorbaBindingException("Unable to locate a valid CORBA address");
            }
            List args = message.getContent(List.class);
            EndpointReferenceType ref = (EndpointReferenceType)message.get(Message.ENDPOINT_ADDRESS);
            org.omg.CORBA.Object targetObject;
            // A non-null endpoint address from the message means that we want to invoke on a particular
            // object reference specified by the endpoint reference type.  If the reference is null, then
            // we want to invoke on the default location as specified in the WSDL.
            if (ref != null) {
                targetObject = CorbaObjectReferenceHelper.getReferenceById(ref.getAddress().getValue())
            } else {
                targetObject = CorbaUtils.importObjectReference(orb, address.getLocation());
            }
            message.put(CorbaConstants.ORB, orb);
            message.put(CorbaConstants.CORBA_ENDPOINT_OBJECT, targetObject);
            message.setContent(OutputStream.class,
                               new CorbaOutputStream(message));
        } catch (java.lang.Exception ex) {
            LOG.log(Level.SEVERE, "Could not resolve target object");
            throw new CorbaBindingException(ex);
        }
    }

    public void close(Message message) throws IOException {
        BindingOperationInfo boi = message.getExchange().get(BindingOperationInfo.class);
        OperationType opType = boi.getExtensor(OperationType.class);
       
        try {
            buildRequest((CorbaMessage)message, opType);           
            message.getContent(OutputStream.class).close();
        } catch (Exception ex) {
            ex.printStackTrace();
            LOG.log(Level.SEVERE, "Could not build the corba request");
            throw new CorbaBindingException(ex);
        }
    }

    public EndpointReferenceType getTarget() {
        return target;
    }

    public Destination getBackChannel() {
        return null;
    }

    public void close() {
       
    }

    public void setMessageObserver(MessageObserver observer) {
        incomingObserver = observer;
    }

    public EndpointReferenceType getTargetReference(EndpointReferenceType t) {
        EndpointReferenceType ref = null;
        if (null == t) {
            ref = new EndpointReferenceType();
            AttributedURIType address = new AttributedURIType();
            address.setValue(getAddress());
            ref.setAddress(address);
        } else {
            ref = t;
        }
        return ref;
    }

    protected String getAddress() {
        return endpointInfo.getAddress();
    }
       
    protected void buildRequest(CorbaMessage message, OperationType opType) throws Exception {       
        List<CorbaTypeMap> typeMaps = new ArrayList<CorbaTypeMap>();

        ServiceInfo service = message.getExchange().get(ServiceInfo.class);
        List<TypeMappingType> corbaTypes = service.getDescription().getExtensors(TypeMappingType.class);
        if (corbaTypes != null) {
            CorbaUtils.createCorbaTypeMap(typeMaps, corbaTypes);
        }
       
        NVList nvlist = getArguments(message);
        NamedValue ret = getReturn(message);
        Map<TypeCode, RaisesType> exceptions = getOperationExceptions(opType, typeMaps);
        ExceptionList exList = getExceptionList(exceptions, message, opType, typeMaps);
        Request request = getRequest(message, opType.getName(), nvlist, ret, exList);
        if (request == null) {
            throw new CorbaBindingException("Couldn't build the corba request");
        }
        request.invoke();
        Exception ex = request.env().exception();
        if (ex != null) {
            if (ex instanceof UnknownUserException) {
                UnknownUserException userEx = (UnknownUserException) ex;
                Any except = userEx.except;
                RaisesType raises = exceptions.get(except.type());
                if (raises == null) {
                    throw new CorbaBindingException("Couldn't find the exception type code to unmarshall");
                }
                QName elName = new QName("", raises.getException().getLocalPart());
                CorbaObjectHandler handler =
                    CorbaHandlerUtils.initializeObjectHandler(orb,
                                                              elName,
                                                              raises.getException(),
                                                              typeMaps,
                                                              service);
               
                CorbaStreamable exStreamable = new CorbaStreamable(handler, elName);
                exStreamable._read(except.create_input_stream());
                message.setStreamableException(exStreamable);
                message.setContent(Exception.class, new Fault(userEx));
            } else {
                message.setContent(Exception.class, new Fault(ex));
            }
        }
    }
      
    protected NVList getArguments(CorbaMessage message) {
        // Build the list of DII arguments, returns, and exceptions
        NVList list = null;
        if (message.getStreamableArguments() != null) {
            CorbaStreamable[] arguments = message.getStreamableArguments();
            list = orb.create_list(arguments.length);

            for (int i = 0; i < arguments.length; ++i) {
                Any value = orb.create_any();
                value.insert_Streamable(arguments[i]);
                list.add_value(arguments[i].getName(), value, arguments[i].getMode());
            }
        } else {
            list = orb.create_list(0);
        }

        return list;       
    }
   
    protected NamedValue getReturn(CorbaMessage message) {
        CorbaStreamable retVal = message.getStreamableReturn();
        NamedValue ret = null;
        if (retVal != null) {
            Any returnAny = orb.create_any();
            returnAny.insert_Streamable(retVal);
            ret = orb.create_named_value(retVal.getName(), returnAny, org.omg.CORBA.ARG_OUT.value);
        } else {
            // TODO: REVISIT: for some reason, the yoko ORB does not like to
            // have a null NamedValue return value. Create this 'empty'
            // one if a void return type is used.
            ret = orb.create_named_value("return", orb.create_any(), org.omg.CORBA.ARG_OUT.value);
        }
        return ret;       
    }
   
    protected ExceptionList getExceptionList(Map<TypeCode, RaisesType> exceptions,
                                             CorbaMessage message,
                                             OperationType opType,
                                             List<CorbaTypeMap> typeMaps) {
        // Get the typecodes for the exceptions this operation can throw.
        // These are defined in the operation definition from WSDL.
        ExceptionList exList = orb.create_exception_list();

              
        if (exceptions != null) {
            Object[] tcs = null;
            tcs = exceptions.keySet().toArray();
       
            for (int i = 0; i < exceptions.size(); ++i) {
                exList.add((TypeCode)tcs[i]);
            }
        }
        return exList;
    }
           
    protected Request getRequest(CorbaMessage message,
                                 String opName,
                                 org.omg.CORBA.NVList nvlist,
                                 org.omg.CORBA.NamedValue ret,
                                 org.omg.CORBA.ExceptionList exList)
        throws Exception {
        Request request = null;
        ContextList ctxList = orb.create_context_list();
        Context ctx = orb.get_default_context();           

        org.omg.CORBA.Object targetObj =
            (org.omg.CORBA.Object)message.get(CorbaConstants.CORBA_ENDPOINT_OBJECT);
        if (targetObj != null) {
            request = targetObj._create_request(ctx, opName, nvlist, ret, exList, ctxList);
        }
        return request;
    }
       
    protected Map<TypeCode, RaisesType> getOperationExceptions(
                                         OperationType operation,
                                         List<CorbaTypeMap> typeMaps) {
        Map<TypeCode, RaisesType> exceptions = new HashMap<TypeCode, RaisesType>();
        List<RaisesType> exList = operation.getRaises();
        if (exList != null) {
            for (int i = 0; i < exList.size(); ++i) {
                RaisesType ex = exList.get(i);
                TypeCode tc = CorbaUtils.getTypeCode(orb, ex.getException(), typeMaps);
                exceptions.put(tc, ex);
            }
        }

        return exceptions;
    }
   
    private class CorbaOutputStream extends AbstractCachedOutputStream {
      
        private Message message;
        private boolean isOneWay;

        CorbaOutputStream(Message m) {
            message = m;       
        }

        /**
         * Perform any actions required on stream flush (freeze headers, reset
         * output stream ... etc.)
         */
        public void doFlush() throws IOException {
            // do nothing here
        }

        /**
         * Perform any actions required on stream closure (handle response etc.)
         */
        public void doClose() throws IOException {
            if (ContextUtils.isRequestor(message) && ContextUtils.isOutbound(message)) {
                try {
                    isOneWay = message.getExchange().isOneWay();
                   
                    if (!isOneWay) {               
                        handleResponse();
                    }
                } catch (Exception ex) {
                    LOG.log(Level.WARNING, "Connection failed with Exception : ", ex);
                    throw new IOException(ex.toString());
                }           
            }
        }

        public void onWrite() throws IOException {

        }

        public void handleResponse() throws IOException {
            LOG.log(Level.FINE, "incoming observer is " + incomingObserver);
            Exchange exchange = message.getExchange();           
            MessageImpl inMessage = new MessageImpl();
            CorbaDestination destination = new CorbaDestination(endpointInfo, orbConfig);
            inMessage.setDestination(destination);
            exchange.put(ORB.class, orb);
            inMessage.setExchange(exchange);
            CorbaMessage inCorbaMsg = new CorbaMessage(inMessage);
            CorbaMessage corbaMsg = (CorbaMessage) message;
            if (corbaMsg.getStreamableException() != null) {
                exchange.setInFaultMessage(corbaMsg);
                inCorbaMsg.setStreamableException(corbaMsg.getStreamableException());               
            }
            LOG.log(Level.FINE, "incoming observer is " + incomingObserver);
            incomingObserver.onMessage((Message)inCorbaMsg);         
        }

    }
}
TOP

Related Classes of org.apache.yoko.bindings.corba.CorbaConduit

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.