Package org.wso2.carbon.mashup.javascript.messagereceiver

Examples of org.wso2.carbon.mashup.javascript.messagereceiver.JavaScriptEngine


     * @throws CarbonException Thrown in case any exceptions occur
     */
    public static void jsFunction_include(Context cx, Scriptable thisObj, Object[] arguments,
                                          Function funObj) throws CarbonException {
        // sanity check
        JavaScriptEngine engine = (JavaScriptEngine) getTopLevelScope(thisObj);

        AxisService axisService;
        // retrieves the AxisService object from the Rhino context
        Object axisServiceObject = cx.getThreadLocal(MashupConstants.AXIS2_SERVICE);
        if (axisServiceObject != null && axisServiceObject instanceof AxisService) {
            axisService = (AxisService) axisServiceObject;
        } else {
            throw new CarbonException("Error obtaining the Service Meta Data: Axis2 Service");
        }

        // Retrieves the service.resources directory corresponding to this
        // mashup service
        Parameter parameter = axisService.getParameter(MashupConstants.RESOURCES_FOLDER);
        Object resourceFileObject = parameter.getValue();
        File resourceFolder;
        if (resourceFileObject != null && resourceFileObject instanceof File) {
            resourceFolder = (File) resourceFileObject;
        } else {
            throw new CarbonException("Mashup Resources folder not found.");
        }

        // Creates the base URI for URI resolving. URI's are resolved relative
        // to the serviceContextRoot of the Mashup server.
        // (eg:http://localhost:7762/services/)
        URI baseURI;
        //todo need to handle this scenario
        /*try {
            String contextPath = AdminUIServletContextListener.contextPath;
            if (!contextPath.endsWith(MashupConstants.FORWARD_SLASH)) {
                contextPath += MashupConstants.FORWARD_SLASH;
            }
            baseURI = new URI("http", null, NetworkUtils.getLocalHostname(),
                              ServerManager.getInstance().getHttpPort(),
                              contextPath +
                                      configurationContext.getServicePath() + "/",
                              null, null);
        } catch (Exception e) {
            throw new CarbonException("Cannot create the server base URI.", e);
        }*/

        for (int i = 0; i < arguments.length; i++) {
            Reader reader;
            String path = arguments[i].toString();
            File f = new File(resourceFolder, path);
            // We change the scriptName in the engine so that when warnings are displayed they use the  name of the
            // included scripr rather than the calling script name.
            String parentScriptName = engine.getScriptName();

            try {
                // Check whether this is a file in the service.resources directory
                if (f.exists() && !f.isDirectory()) {
                    reader = new FileReader(f);
                    engine.setScriptName(path);
                    engine.evaluate(reader);
                } else {
                    // This is not a file.. So we check whether this is a URL
                    //todo need to check this
                    //                    readFromURI(engine, baseURI, path);
                }
            } catch (IOException e) {
                throw new CarbonException(e);
            } finally {
                engine.setScriptName(parentScriptName);
            }
        }
    }
View Full Code Here


            Object[] parameters = (Object[]) jdm.get(FunctionSchedulingJob.FUNCTION_PARAMETERS);


            String serviceName = axisService.getName();
            JavaScriptEngine jsEngine = new JavaScriptEngine(serviceName);

            // Rhino E4X XMLLibImpl object can be instantiated only from within a script
            // So we instantiate it in here, so that we can use it outside of the script later
            jsEngine.getCx().evaluateString(jsEngine, "new XML();", "Instantiate E4X", 0, null);


            JavaScriptEngineUtils.loadHostObjects(jsEngine, serviceName);

            // Inject the incoming MessageContext to the Rhino Context. Some
            // host objects need access to the MessageContext. Eg: FileSystem,
            // WSRequest
            Context context = jsEngine.getCx();

            /*
             * Some host objects depend on the data we obtain from the
             * AxisService & ConfigurationContext.. It is possible to get these
             * data through the MessageContext. But we face problems at the
             * deployer, where we need to instantiate host objects in order for
             * the annotations framework to work and the MessageContext is not
             * available at that time. For the consistency we inject them in
             * here too..
             */
            context.putThreadLocal(MashupConstants.AXIS2_SERVICE, axisService);
            context.putThreadLocal(MashupConstants.AXIS2_CONFIGURATION_CONTEXT,
                                   configurationContext);

            AxisConfiguration axisConfig = configurationContext.
                    getAxisConfiguration();
            JavaScriptEngineUtils.loadHostObjects(jsEngine, serviceName);

            URL repoURL = axisConfig.getRepository();
            if (repoURL != null) {
                JavaScriptEngine.axis2RepositoryLocation = repoURL.getPath();
            }

            Reader reader = MashupUtils.readJS(axisService);

            Object[] args;

            //support for importing javaScript files using services.xml or the axis2.xml
            String scripts = MashupUtils.getImportScriptsList(axisService);

            //Loading imported JavaScript files if there are any
            if (scripts != null) {
                // Generate load command out of the parameter scripts
                scripts = "load(" + ("[\"" + scripts + "\"]").replaceAll(",", "\"],[\"") + ")";
                jsEngine.getCx().evaluateString(jsEngine, scripts, "Load Included JavaScript File(s)", 0, null);
            }

            //Evaluating the JavaScript service file
            jsEngine.getCx().evaluateReader(jsEngine, reader, "Load JSService file", 1, null);

            if (jsFunction instanceof Function) {
                if (parameters != null) {
                    args = parameters;
                } else {
                    args = new Object[0];
                }

                Function function = (Function) jsFunction;
                function.call(jsEngine.getCx(), jsEngine, jsEngine, args);

            } else if (jsFunction instanceof String) {
                String jsString = (String) jsFunction;
                jsEngine.getCx()
                        .evaluateString(jsEngine, jsString, "Load JavaScriptString", 0, null);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
View Full Code Here

        }
    }

    private Context getContext() throws AxisFault {
        AxisService service = (AxisService) this.context.getThreadLocal(MashupConstants.AXIS2_SERVICE);
        JavaScriptEngine engine = new JavaScriptEngine(service.getName());
        Context context = engine.getCx();
        context.putThreadLocal(MashupConstants.AXIS2_MESSAGECONTEXT,
                this.context.getThreadLocal(MashupConstants.AXIS2_MESSAGECONTEXT));
        context.putThreadLocal(MashupConstants.AXIS2_CONFIGURATION_CONTEXT,
                this.context.getThreadLocal(MashupConstants.AXIS2_CONFIGURATION_CONTEXT));
        context.putThreadLocal(MashupConstants.AXIS2_SERVICE, service);
        engine.getCx().evaluateString(engine, "new XML();", "Instantiate E4X", 0, null);
        JavaScriptEngineUtils.loadHostObjects(engine, service.getName());
        return context;
    }
View Full Code Here

                call on undeployment if such a function was specified.
                */
                Function destroy =
                        (Function) service.getParameterValue(JSConstants.MASHUP_DESTROY_FUNCTION);
                if (destroy != null) {
                    JavaScriptEngine engine = new JavaScriptEngine(jsFileName);
                    JavaScriptEngineUtils.loadHostObjects(engine, jsFilePath);
                    destroy.call(engine.getCx(), engine, engine, new Object[0]);
                }
            }

            /*
            There exist only one service group for the JavaScript services deployed from this
View Full Code Here

            /*
             Service level java script annotations processing. We create a
             JavaScriptEngine and load the scripts and the associated host
             objects.
             */
            JavaScriptEngine engine = new JavaScriptEngine(jsFileNameShort);
            /*
             We inject the AxisService & ConfigContext as a workaround for not
             having the MessageContext injected in the deployment time. Some host objects need
             data from them at the initialize time.
             */
            engine.getCx().putThreadLocal(MashupConstants.AXIS2_SERVICE, axisService);
            engine.getCx().putThreadLocal(MashupConstants.AXIS2_CONFIGURATION_CONTEXT, configCtx);

            /*
            Load the JavaScriptHostObjects that are specified using the OSGI header
            JavaScript-HostObject
            */
            JavaScriptEngineUtils.loadHostObjects(engine, jsFileNameShort);

            FileInputStream fileInputStream = new FileInputStream(jsFile);
            // load the service java script file
            engine.evaluate(new BufferedReader(new InputStreamReader(fileInputStream)));

            // Use the JavaScriptServiceAnnotationParser to extract serviceLevel annotations
            JavaScriptServiceAnnotationParser serviceAnnotationParser =
                    new JavaScriptServiceAnnotationParser(engine, jsFileNameShort);

            axisService.setParent(axisServiceGroup);
            axisService.setClassLoader(deploymentFileData.getClassLoader());
            String serviceName = serviceAnnotationParser.getServiceName();

            // Setting Axis Parameters given in serviceParameters annotation
            Object serviceParametersObject = serviceAnnotationParser.getServiceParameters();
            if (serviceParametersObject instanceof NativeObject) {
                NativeObject nativeObject = (NativeObject) serviceParametersObject;
                Object[] propertyNames = nativeObject.getIds();
                for (Object propertyNameObject : propertyNames) {
                    if (propertyNameObject instanceof String) {
                        String propertyName = (String) propertyNameObject;
                        Object propertyValueObject = nativeObject.get(propertyName, nativeObject);
                        if (propertyValueObject instanceof String) {
                            try {
                                OMFactory factory = OMAbstractFactory.getOMFactory();
                                OMElement parameterElement = factory.createOMElement("parameter", null);
                                parameterElement.addAttribute("name", propertyName, null);
                                parameterElement.setText((String) propertyValueObject);
                                Parameter param = new Parameter(propertyName, propertyValueObject);
                                param.setParameterElement(parameterElement);
                                axisService.addParameter(param);
                            } catch (AxisFault axisFault) {
                                throw new DeploymentException(
                                        "Error adding service parameter : " + propertyName,
                                        axisFault);
                            }
                        } else if (propertyValueObject instanceof XML) {
                            XML xml = (XML) propertyValueObject;
                            OMNode axiom = xml.getAxiomFromXML();
                            try {
                                OMFactory factory = OMAbstractFactory.getOMFactory();
                                OMElement parameterElement = factory.createOMElement("parameter", null);
                                parameterElement.addAttribute("name", propertyName, null);
                                parameterElement.addChild(axiom);
                                Parameter param = new Parameter(propertyName, axiom);
                                param.setParameterElement(parameterElement);
                                axisService.addParameter(param);
                            } catch (AxisFault axisFault) {
                                throw new DeploymentException(
                                        "Error adding service parameter : " + propertyName,
                                        axisFault);
                            }
                        } else if (propertyValueObject instanceof XMLList) {
                            XMLList list = (XMLList) propertyValueObject;
                            OMNode[] omNodes = list.getAxiomFromXML();
                            try {
                                OMFactory factory = OMAbstractFactory.getOMFactory();
                                OMElement parameterElement = factory.createOMElement("parameter", null);
                                parameterElement.addAttribute("name", propertyName, null);
                                for (OMNode node : omNodes) {
                                    parameterElement.addChild(node);
                                }
                                Parameter param = new Parameter(propertyName, omNodes);
                                param.setParameterElement(parameterElement);
                                axisService.addParameter(param);
                            } catch (AxisFault axisFault) {
                                throw new DeploymentException(
                                        "Error adding service parameter : " + propertyName,
                                        axisFault);
                            }
                        } else {
                            throw new DeploymentException("Invalid property value specified for " +
                                    "\"serviceProperties\" annotation : " + propertyName +
                                    ". You should provide a string for property value.");
                        }
                    } else {
                        throw new DeploymentException("Invalid property name specified for " +
                                "\"serviceProperties\" annotation : " + propertyNameObject);
                    }
                }
            }

            /*
            Checks the validity of the serviceName. If the serviceName is invalid an exception is
            thrown
            */
            JSUtils.validateName(serviceName, SERVICE_NAME);

            /*
            Although Mashup Server supports only one service per *.js file at the moment, we set
            the service group name as a combination of author name and *.js file name. If the
            mashup was created manually on the file system, then the parent directory of the
            mashup will be used as the prefix.
             */
            axisServiceGroup.setServiceGroupName(
                    username + MashupConstants.SEPARATOR_CHAR + jsFileNameShort);
            /*
            All mashup services are deployed under the authors name with the help of Axis2's
            hierarchical service deployment model. So each service name is prefixed
            by author name.
             */
            axisService.setName(username + MashupConstants.SEPARATOR_CHAR + serviceName);

            // Sets the namespace map which is defined using this.targetNamespace
            String targetNamespace = serviceAnnotationParser.getTargetNamespace();
            axisService.setTargetNamespace(targetNamespace);

            /*
            Sets the scope of the service, this is defined as a service level annotation in the mashup i.e.
            this.scope = "application | soapsession | transportsession | request"
             */
            axisService.setScope(serviceAnnotationParser.getServiceScope());
            // Sets service documentation which is defined using this.documentation annotation
            axisService.setDocumentation(serviceAnnotationParser.getServiceDocumentation());
            // Sets the namespace map which is defined using this.schemaTargetNamespace
            SchemaGenerator schemaGenerator =
                    new SchemaGenerator(serviceAnnotationParser.getSchemaTargetNamespace());
            axisService.setNamespaceMap(schemaGenerator.getNamespaceMap());

            /*
            The interfaceName is used by org.apache.axis2.description.AxisService2WSDL20 to
            set the interface during ?wsdl2
            */
            String interfaceName = serviceName + WSDL2Constants.INTERFACE_PREFIX;
            axisService.addParameter(WSDL2Constants.INTERFACE_LOCAL_NAME, interfaceName);

            /*
            Set a comparator so tha httpLocations are stored in descending order. We want the
            HTTPLocationBasedDiapatcher to make the best match hence we need them in descending
            order
            */
            httpLocationTable = new TreeMap<String, AxisOperation>(new Comparator() {
                public int compare(Object o1, Object o2) {
                    return (-1 * ((Comparable) o1).compareTo(o2));
                }
            });

            /*
            We create the AxisBinding Hierarchy in here. In the Mashup Server we take complete
            control of the Axis2 binding hierarchy cause we need to specify some HTTPBinding
            properties such as httpMethod and httpLocation
            */
            String bindingPrefix = username.replace('/', '-') + "-" + serviceName + "-";
            // Create a default SOAP 1.1 Binding
            createDefaultSOAP11Binding(bindingPrefix, interfaceName);

            // Create a default SOAP 1.2 Binding
            createDefaultSOAP12Binding(bindingPrefix, interfaceName);

            // Create a default HTTP Binding
            createDefaultHTTPBinding(bindingPrefix, interfaceName);

            /*
            We need to get all transports from the axis2 engine and create endpoints for each of
            those in here
            */
            createDefaultEndpoints(axisService);

            // Obtain the list of functions in the java script service and process each one of them.
            Object[] ids = engine.getIds();
            for (Object id : ids) {
                String method = (String) id;
                Object object = engine.get(method, engine);
                // some id's are not functions
                if (object instanceof Function) {
                    processOperation(engine, axisService, method, (Function) object,
                            schemaGenerator, targetNamespace);
                }
            }
            axisService.addSchema(schemaGenerator.getSchema());

            Function init = serviceAnnotationParser.getInit();
            Function destroy = serviceAnnotationParser.getDestroy();

            /*
            this.init and this.destroy correspond to service lifecycle functions.
            this.init is called upon service deployment and this.destroy is called on
            undeployment.
            */
            if (init != null) {
                JavaScriptEngineUtils.loadHostObjects(engine, serviceName);
                init.call(engine.getCx(), engine, engine, new Object[0]);
            }

            if (destroy != null) {
                axisService.addParameter(JSConstants.MASHUP_DESTROY_FUNCTION, destroy);
            }
View Full Code Here

        }

        public void run() {
            try {
                MessageContext msgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
                Event<MessageContext> event = new Event(msgCtx);
                subscriptions = subscriptionManager.getMatchingSubscriptions(event);
            } catch (EventException e) {
                handleException("Matching subscriptions fetching error", e);
            }
View Full Code Here

     * @throws EventException event
     */
    private void processGetStatusRequest(MessageContext mc,
                                         ResponseMessageBuilder messageBuilder)
            throws AxisFault, EventException {
        Subscription subscription =
                SubscriptionMessageBuilder.createGetStatusMessage(mc);
        if (log.isDebugEnabled()) {
            log.debug("GetStatus request recived for SynapseSubscription ID : " +
                    subscription.getId());
        }
        subscription = subscriptionManager.getSubscription(subscription.getId());
        if (subscription != null) {
            if (log.isDebugEnabled()) {
                log.debug("Sending GetStatus responce for SynapseSubscription ID : " +
                        subscription.getId());
            }
            //send the responce
            SOAPEnvelope soapEnvelope = messageBuilder.genGetStatusResponse(subscription);
            dispatchResponse(soapEnvelope, EventingConstants.WSE_GET_STATUS_RESPONSE,
                    mc, false);
View Full Code Here

            // Adding static subscriptions
            List<Subscription> staticSubscriptionList =
                    eventSource.getSubscriptionManager().getStaticSubscriptions();
            for (Iterator<Subscription> iterator = staticSubscriptionList.iterator();
                 iterator.hasNext();) {
                Subscription staticSubscription = iterator.next();
                OMElement staticSubElem =
                        fac.createOMElement("subscription", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                staticSubElem.addAttribute(
                        fac.createOMAttribute("id", nullNS, staticSubscription.getId()));
                OMElement filterElem =
                        fac.createOMElement("filter", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                filterElem.addAttribute(fac.createOMAttribute("source", nullNS,
                        (String) staticSubscription.getFilterValue()));
                filterElem.addAttribute(fac.createOMAttribute("dialect", nullNS,
                        (String) staticSubscription.getFilterDialect()));
                staticSubElem.addChild(filterElem);
                OMElement endpointElem =
                        fac.createOMElement("endpoint", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                OMElement addressElem =
                        fac.createOMElement("address", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                addressElem.addAttribute(
                        fac.createOMAttribute("uri", nullNS, staticSubscription.getEndpointUrl()));
                endpointElem.addChild(addressElem);
                staticSubElem.addChild(endpointElem);
                if (staticSubscription.getExpires() != null) {
                    OMElement expiresElem =
                            fac.createOMElement("expires", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                    fac.createOMText(expiresElem,
                            ConverterUtil.convertToString(staticSubscription.getExpires()));
                    staticSubElem.addChild(expiresElem);
                }
                evenSourceElem.addChild(staticSubElem);
            }
View Full Code Here


    public SynapseSubscription() {
        this.setId(UIDGenerator.generateURNString());
        this.setDeliveryMode(EventingConstants.WSE_DEFAULT_DELIVERY_MODE);
        SubscriptionData subscriptionData = new SubscriptionData();
        subscriptionData.setProperty(SynapseEventingConstants.STATIC_ENTRY, "false");
        this.setSubscriptionData(subscriptionData);
    }
View Full Code Here

                    .getAttribute(new QName(XMLConfigConstants.NULL_NAMESPACE, "class"));
            if (clazz != null) {
                String className = clazz.getAttributeValue();
                try {
                    Class subscriptionManagerClass = Class.forName(className);
                    SubscriptionManager manager =
                            (SubscriptionManager) subscriptionManagerClass.newInstance();
                    Iterator itr = subscriptionManagerElem.getChildrenWithName(PROPERTIES_QNAME);
                    while (itr.hasNext()) {
                        OMElement propElem = (OMElement) itr.next();
                        String propName =
                                propElem.getAttribute(new QName("name")).getAttributeValue();
                        String propValue =
                                propElem.getAttribute(new QName("value")).getAttributeValue();
                        if (propName != null && !"".equals(propName.trim()) &&
                                propValue != null && !"".equals(propValue.trim())) {

                            propName = propName.trim();
                            propValue = propValue.trim();

                            PasswordManager passwordManager =
                                    PasswordManager.getInstance();
                            String key = eventSource.getName() + "." + propName;

                            if (passwordManager.isInitialized()
                                    && passwordManager.isTokenProtected(key)) {
                                eventSource.putConfigurationProperty(propName, propValue);
                                propValue = passwordManager.resolve(propValue);
                            }

                            manager.addProperty(propName, propValue);
                        }
                    }
                    eventSource.setSubscriptionManager(manager);
                    eventSource.getSubscriptionManager()
                            .init(); // Initialise before doing further processing, required for static subscriptions
View Full Code Here

TOP

Related Classes of org.wso2.carbon.mashup.javascript.messagereceiver.JavaScriptEngine

Copyright © 2018 www.massapicom. 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.