Search in sources :

Example 56 with Policy

use of org.apache.neethi.Policy in project wso2-synapse by wso2.

the class ThrottleFactory method fillControlConfiguration.

/**
 * Helper method to process control assertion
 *
 * @param policy              Policy for Control Assertion
 * @param callerConfiguration Caller to whom control need to be applied.
 * @throws ThrottleException
 */
private static void fillControlConfiguration(Policy policy, CallerConfiguration callerConfiguration) throws ThrottleException {
    boolean isFoundMaxCount = false;
    boolean isFoundUnitTime = false;
    List list = policy.getPolicyComponents();
    for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
        Object obj = iterator.next();
        if (obj instanceof Policy) {
            List controlList = ((Policy) obj).getPolicyComponents();
            for (Iterator controlIterator = controlList.iterator(); controlIterator.hasNext(); ) {
                Object object = controlIterator.next();
                if (object instanceof XmlPrimtiveAssertion) {
                    XmlPrimtiveAssertion primitiveAssertion = (XmlPrimtiveAssertion) object;
                    OMElement element = primitiveAssertion.getValue();
                    // Name of the policy assertion
                    String name = element.getLocalName();
                    // Value of the policy assertion
                    String value = element.getText();
                    // invalid policy configuration
                    if (name == null || value == null) {
                        handleException("Either Value or " + "Name of the policy cannot be null");
                    }
                    if (!value.equals("")) {
                        if (name.equals(ThrottleConstants.MAXIMUM_COUNT_PARAMETER_NAME)) {
                            isFoundMaxCount = true;
                            try {
                                callerConfiguration.setMaximumRequestPerUnitTime(Integer.parseInt(value.trim()));
                            } catch (NumberFormatException ignored) {
                                log.error("Error occurred - " + "Invalid number for maximum " + "request number ", ignored);
                                if (log.isDebugEnabled()) {
                                    log.debug("Access" + " will be fully allowed");
                                }
                                callerConfiguration.setAccessState(ThrottleConstants.ACCESS_ALLOWED);
                            }
                        } else if (name.equals(ThrottleConstants.UNIT_TIME_PARAMETER_NAME)) {
                            // TODO need to verify that value is in milisecond
                            long timeInMilliSec = 0;
                            try {
                                timeInMilliSec = Long.parseLong(value.trim());
                            } catch (NumberFormatException ignored) {
                                log.error("Error occurred " + "- Invalid number for unit time", ignored);
                            }
                            if (timeInMilliSec == 0) {
                                handleException("Unit Time cannot " + "find - invalid throttle " + "policy configuration");
                            }
                            isFoundUnitTime = true;
                            callerConfiguration.setUnitTime(timeInMilliSec);
                        } else if (name.equals(ThrottleConstants.PROHIBIT_TIME_PERIOD_PARAMETER_NAME)) {
                            try {
                                callerConfiguration.setProhibitTimePeriod(Long.parseLong(value.trim()));
                            } catch (NumberFormatException ignored) {
                                log.error("Error occurred - Invalid" + " number for prohibit time ", ignored);
                            }
                        } else {
                            handleException("Undefined Policy" + " property for Throttle Policy");
                        }
                    } else {
                        if (!name.equals(ThrottleConstants.PROHIBIT_TIME_PERIOD_PARAMETER_NAME)) {
                            handleException("The policy which have " + " defined as optional " + "should have value ");
                        }
                    }
                }
            }
        } else {
            handleException("Invalid policy - " + "Control Assertion must contain a wsp:Policy as child ");
        }
    }
    if (!isFoundUnitTime && !isFoundMaxCount) {
        handleException("Maximum Count and UnitTime are " + "Mandatory in Throttle Policy ");
    }
}
Also used : Policy(org.apache.neethi.Policy) Iterator(java.util.Iterator) List(java.util.List) OMElement(org.apache.axiom.om.OMElement) XmlPrimtiveAssertion(org.apache.neethi.builders.xml.XmlPrimtiveAssertion)

Example 57 with Policy

use of org.apache.neethi.Policy in project wso2-synapse by wso2.

the class ThrottleFactoryTest method testModuleThrottleForConcurrentModification.

public void testModuleThrottleForConcurrentModification() throws Exception {
    OMElement policyOM = createOMElement(modulePolicy);
    Policy policy = PolicyEngine.getPolicy(policyOM);
    Throttle throttle = ThrottleFactory.createModuleThrottle(policy);
    assertNotNull(throttle);
    assertNotNull(throttle.getConcurrentAccessController());
    ThrottleContext throttleContext = throttle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY);
    RoleBasedAccessRateController roleBasedAccessRateController = new RoleBasedAccessRateController();
    int noOfThreads = 750;
    ExecutorService executorService = Executors.newFixedThreadPool(noOfThreads * 2);
    String roleId = "testRoleId";
    List<String> keys = getRandomKeys(noOfThreads);
    for (String key : keys) {
        RequestThread thread = new RequestThread(roleBasedAccessRateController, throttleContext, key, roleId);
        executorService.submit(thread);
    }
    for (String key : keys) {
        RequestThread thread = new RequestThread(roleBasedAccessRateController, throttleContext, key, roleId);
        executorService.submit(thread);
    }
    executorService.awaitTermination(20, TimeUnit.SECONDS);
    // checks if any thread has reported an error
    assertFalse(errorOccured);
}
Also used : Policy(org.apache.neethi.Policy) ExecutorService(java.util.concurrent.ExecutorService) OMElement(org.apache.axiom.om.OMElement)

Example 58 with Policy

use of org.apache.neethi.Policy in project wso2-synapse by wso2.

the class ThrottleFactoryTest method testModuleThrottleAssertBuilder.

public void testModuleThrottleAssertBuilder() throws Exception {
    System.setProperty("carbon.config.dir.path", "resources");
    OMElement policyOM = createOMElement(modulePolicy);
    Policy policy = PolicyEngine.getPolicy(policyOM);
    Throttle throttle = ThrottleFactory.createModuleThrottle(policy);
    assertNotNull(throttle);
    assertNotNull(throttle.getConcurrentAccessController());
    assertNotNull(throttle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(throttle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(throttle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNotNull(throttle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("127.1.1.127"));
    assertNotNull(throttle.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("test.com"));
    OMElement oldElement = createOMElement(oldPolicy);
    Policy oldPolicy = PolicyEngine.getPolicy(oldElement);
    Throttle oldThrottle = ThrottleFactory.createModuleThrottle(oldPolicy);
    assertNotNull(oldThrottle);
    assertNotNull(oldThrottle.getConcurrentAccessController());
    assertNotNull(oldThrottle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(oldThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(oldThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNotNull(oldThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("127.1.1.127"));
    assertNotNull(oldThrottle.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("test.com"));
    OMElement allOM = createOMElement(servicePolicy);
    Policy allPolicy = PolicyEngine.getPolicy(allOM);
    Throttle allThrottle = ThrottleFactory.createServiceThrottle(allPolicy);
    assertNotNull(allThrottle);
    assertNotNull(allThrottle.getConcurrentAccessController());
    assertNotNull(allThrottle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(allThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(allThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNotNull(allThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("127.1.1.127"));
    assertNotNull(allThrottle.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("test.com"));
    OMElement opElement = createOMElement(opPolicy);
    Policy opPolicy = PolicyEngine.getPolicy(opElement);
    Throttle opThrottle = ThrottleFactory.createOperationThrottle(opPolicy);
    assertNotNull(opThrottle);
    assertNotNull(opThrottle.getConcurrentAccessController());
    assertNotNull(opThrottle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(opThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY));
    assertNotNull(opThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNotNull(opThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("127.1.1.127"));
    assertNotNull(opThrottle.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("test.com"));
    assertNotNull(opThrottle.getConcurrentAccessController());
    OMElement defaultElement = createOMElement(defaultMudulePolicy);
    Throttle defaultThrottle = ThrottleFactory.createModuleThrottle(PolicyEngine.getPolicy(defaultElement));
    assertNotNull(defaultThrottle);
    assertNotNull(defaultThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNotNull(defaultThrottle.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNull(defaultThrottle.getConcurrentAccessController());
    OMElement testXMLElement = createOMElement(testXMl);
    Throttle testThrottle = ThrottleFactory.createServiceThrottle(PolicyEngine.getPolicy(testXMLElement));
    assertNotNull(testThrottle);
    assertNotNull(testThrottle.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY).getConfigurationKeyOfCaller("other"));
    assertNull(testThrottle.getConcurrentAccessController());
}
Also used : Policy(org.apache.neethi.Policy) OMElement(org.apache.axiom.om.OMElement)

Example 59 with Policy

use of org.apache.neethi.Policy in project wso2-synapse by wso2.

the class StockQuoteSampleClient method init.

private void init(String addUrl, String trpUrl, String prxUrl, String policyKey, long timeout) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Initializing sample Axis2 client");
    }
    configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(clientConfig.getClientRepo(), clientConfig.getAxis2Xml());
    serviceClient = new ServiceClient(configContext, null);
    Options options = new Options();
    if (addUrl != null && !"".equals(addUrl)) {
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
    }
    if (trpUrl != null && !"".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    if (prxUrl != null && !"".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
        URL url = new URL(prxUrl);
        proxyProperties.setProxyName(url.getHost());
        proxyProperties.setProxyPort(url.getPort());
        proxyProperties.setUserName("");
        proxyProperties.setPassWord("");
        proxyProperties.setDomain("");
        options.setProperty(HTTPConstants.PROXY, proxyProperties);
    }
    if (policyKey != null && !"".equals(policyKey)) {
        log.info("Using WS-Security");
        serviceClient.engageModule("addressing");
        serviceClient.engageModule("rampart");
        OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(new FileInputStream(policyKey));
        Policy policy = PolicyEngine.getPolicy(builder.getDocumentElement());
        options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
    }
    if (timeout > 0) {
        log.info("setting client timeout to: " + timeout);
        options.setTimeOutInMilliSeconds(timeout);
    }
    options.setProperty(HTTPConstants.HTTP_HEADERS, httpHeaders);
    serviceClient.setOptions(options);
}
Also used : Policy(org.apache.neethi.Policy) Options(org.apache.axis2.client.Options) HttpTransportProperties(org.apache.axis2.transport.http.HttpTransportProperties) ServiceClient(org.apache.axis2.client.ServiceClient) URL(java.net.URL) FileInputStream(java.io.FileInputStream) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 60 with Policy

use of org.apache.neethi.Policy in project wso2-synapse by wso2.

the class ProxyService method buildAxisService.

/**
 * Build the underlying Axis2 service from the Proxy service definition
 *
 * @param synCfg  the Synapse configuration
 * @param axisCfg the Axis2 configuration
 * @return the Axis2 service for the Proxy
 */
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
    auditInfo("Building Axis service for Proxy service : " + name);
    if (pinnedServers != null && !pinnedServers.isEmpty()) {
        Parameter param = axisCfg.getParameter(SynapseConstants.SYNAPSE_ENV);
        if (param != null && param.getValue() instanceof SynapseEnvironment) {
            SynapseEnvironment synEnv = (SynapseEnvironment) param.getValue();
            String serverName = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getServerName() : "localhost";
            if (!pinnedServers.contains(serverName)) {
                log.info("Server name " + serverName + " not in pinned servers list. " + "Not deploying Proxy service : " + name);
                return null;
            }
        }
    }
    // get the wsdlElement as an OMElement
    if (trace()) {
        trace.info("Loading the WSDL : " + (publishWSDLEndpoint != null ? " endpoint = " + publishWSDLEndpoint : (wsdlKey != null ? " key = " + wsdlKey : (wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>"))));
    }
    InputStream wsdlInputStream = null;
    OMElement wsdlElement = null;
    boolean wsdlFound = false;
    String publishWSDL = null;
    SynapseEnvironment synEnv = SynapseConfigUtils.getSynapseEnvironment(axisCfg);
    String synapseHome = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getSynapseHome() : "";
    if (wsdlKey != null) {
        synCfg.getEntryDefinition(wsdlKey);
        Object keyObject = synCfg.getEntry(wsdlKey);
        // start of fix for ESBJAVA-2641
        if (keyObject == null) {
            synCfg.removeEntry(wsdlKey);
        }
        // end of fix for ESBJAVA-2641
        if (keyObject instanceof OMElement) {
            wsdlElement = (OMElement) keyObject;
        }
        wsdlFound = true;
    } else if (inLineWSDL != null) {
        wsdlElement = (OMElement) inLineWSDL;
        wsdlFound = true;
    } else if (wsdlURI != null) {
        try {
            URL url = wsdlURI.toURL();
            publishWSDL = url.toString();
            OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
            if (node instanceof OMElement) {
                wsdlElement = (OMElement) node;
            }
            wsdlFound = true;
        } catch (MalformedURLException e) {
            handleException("Malformed URI for wsdl", e);
        } catch (IOException e) {
            // handleException("Error reading from wsdl URI", e);
            boolean enablePublishWSDLSafeMode = false;
            Map proxyParameters = this.getParameterMap();
            if (!proxyParameters.isEmpty()) {
                if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                    enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
                    }
                    handleException("Error reading from wsdl URI", e);
                }
            }
            if (enablePublishWSDLSafeMode) {
                // !!!Need to add a reload function... And display that the wsdl/service is offline!!!
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: true");
                }
                log.warn("Unable to load the WSDL for : " + name, e);
                return null;
            } else {
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: false");
                }
                handleException("Error reading from wsdl URI", e);
            }
        }
    } else if (publishWSDLEndpoint != null) {
        try {
            URL url = null;
            Endpoint ep = synCfg.getEndpoint(publishWSDLEndpoint);
            if (ep == null) {
                handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is null");
            }
            if (ep instanceof AddressEndpoint) {
                url = new URL(((AddressEndpoint) (ep)).getDefinition().getAddress() + "?wsdl");
            } else if (ep instanceof WSDLEndpoint) {
                url = new URL(((WSDLEndpoint) (ep)).getWsdlURI());
            } else {
                handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is not a AddressEndpoint or WSDLEndpoint");
            }
            publishWSDL = url.toString();
            OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
            if (node instanceof OMElement) {
                wsdlElement = (OMElement) node;
            }
            wsdlFound = true;
        } catch (MalformedURLException e) {
            handleException("Malformed URI for wsdl", e);
        } catch (IOException e) {
            // handleException("Error reading from wsdl URI", e);
            boolean enablePublishWSDLSafeMode = false;
            Map proxyParameters = this.getParameterMap();
            if (!proxyParameters.isEmpty()) {
                if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                    enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
                    }
                    handleException("Error reading from wsdl URI " + publishWSDL, e);
                }
            }
            if (enablePublishWSDLSafeMode) {
                // !!!Need to add a reload function... And display that the wsdl/service is offline!!!
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: true");
                }
                log.warn("Unable to load the WSDL for : " + name, e);
                return null;
            } else {
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: false");
                }
                handleException("Error reading from wsdl URI " + publishWSDL, e);
            }
        }
    } else {
        // our SynapseDispatcher will properly dispatch to
        if (trace())
            trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
        axisService = new AxisService();
        AxisOperation mediateOperation = new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
        // Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
        mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
        mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
        axisService.addOperation(mediateOperation);
    }
    // if a WSDL was found
    if (wsdlElement != null) {
        OMNamespace wsdlNamespace = wsdlElement.getNamespace();
        // if preservePolicy is set to 'false', remove the security policy content of publish wsdl
        if (preservePolicy != null && preservePolicy.equals("false")) {
            if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
                removePolicyOfWSDL(wsdlElement);
            }
        }
        // serialize and create an input stream to read WSDL
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            if (trace())
                trace.info("Serializing wsdlElement found to build an Axis2 service");
            wsdlElement.serialize(baos);
            wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
        } catch (XMLStreamException e) {
            handleException("Error converting to a StreamSource", e);
        }
        if (wsdlInputStream != null) {
            try {
                // detect version of the WSDL 1.1 or 2.0
                if (trace())
                    trace.info("WSDL Namespace is : " + wsdlNamespace.getNamespaceURI());
                if (wsdlNamespace != null) {
                    WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
                    if (WSDL2Constants.WSDL_NAMESPACE.equals(wsdlNamespace.getNamespaceURI())) {
                        wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
                    } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
                        wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream);
                    } else {
                        handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                    }
                    if (wsdlToAxisServiceBuilder == null) {
                        throw new SynapseException("Could not get the WSDL to Axis Service Builder");
                    }
                    wsdlToAxisServiceBuilder.setBaseUri(wsdlURI != null ? wsdlURI.toString() : synapseHome);
                    if (trace()) {
                        trace.info("Setting up custom resolvers");
                    }
                    // load the UserDefined WSDLResolver and SchemaURIResolver implementations
                    if (synCfg.getProperty(SynapseConstants.SYNAPSE_WSDL_RESOLVER) != null && synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER) != null) {
                        setUserDefinedResourceResolvers(synCfg, wsdlInputStream, wsdlToAxisServiceBuilder);
                    } else {
                        if (resourceMap != null) {
                            // if the resource map is available use it
                            wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver(resourceMap, synCfg));
                            // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                            if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : "", resourceMap, synCfg));
                            }
                        } else {
                            // if the resource map isn't available ,
                            // then each import URIs will be resolved using base URI
                            wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver());
                            // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                            if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : ""));
                            }
                        }
                    }
                    if (trace()) {
                        trace.info("Populating Axis2 service using WSDL");
                        if (trace.isTraceEnabled()) {
                            trace.trace("WSDL : " + wsdlElement.toString());
                        }
                    }
                    axisService = wsdlToAxisServiceBuilder.populateService();
                    // this is to clear the bindings and ports already in the WSDL so that the
                    // service will generate the bindings on calling the printWSDL otherwise
                    // the WSDL which will be shown is same as the original WSDL except for the
                    // service name
                    axisService.getEndpoints().clear();
                } else {
                    handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                }
            } catch (AxisFault af) {
                handleException("Error building service from WSDL", af);
            } catch (IOException ioe) {
                handleException("Error reading WSDL", ioe);
            }
        }
    } else if (wsdlFound) {
        handleException("Couldn't build the proxy service : " + name + ". Unable to locate the specified WSDL to build the service");
    }
    // default Service destination
    if (axisService == null) {
        throw new SynapseException("Could not create a proxy service");
    }
    axisService.setName(name);
    if (description != null) {
        axisService.setDocumentation(description);
    }
    // Setting file path for axis2 service
    if (filePath != null) {
        axisService.setFileName(filePath);
    }
    // destination
    if (transports == null || transports.size() == 0) {
    // default to all transports using service name as destination
    } else {
        if (trace())
            trace.info("Exposing transports : " + transports);
        axisService.setExposedTransports(transports);
    }
    // process parameters
    if (trace() && parameters.size() > 0) {
        trace.info("Setting service parameters : " + parameters);
    }
    for (Object o : parameters.keySet()) {
        String name = (String) o;
        Object value = parameters.get(name);
        Parameter p = new Parameter();
        p.setName(name);
        p.setValue(value);
        try {
            axisService.addParameter(p);
        } catch (AxisFault af) {
            handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af);
        }
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_SCHEMA_URL_PARAM))) {
        axisService.setCustomSchemaNamePrefix("");
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_PROXY_SCHEMA_URL_PARAM))) {
        axisService.setCustomSchemaNamePrefix("fullschemaurl");
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue("disableOperationValidation"))) {
        try {
            AxisOperation defaultOp = processOperationValidation(axisService);
        // proxyServiceGroup.setParent(axisCfg);
        } catch (AxisFault axisFault) {
        // ignore
        }
    }
    boolean isNoSecPolicy = false;
    if (!policies.isEmpty()) {
        for (PolicyInfo pi : policies) {
            Policy policy = getPolicyFromKey(pi.getPolicyKey(), synCfg);
            if (policy == null) {
                handleException("Cannot find Policy from the key");
            }
            if (NO_SECURITY_POLICY.equals(policy.getId())) {
                isNoSecPolicy = true;
                log.info("NoSecurity Policy found, skipping policy attachment");
                continue;
            }
            if (pi.isServicePolicy()) {
                axisService.getPolicySubject().attachPolicy(policy);
            } else if (pi.isOperationPolicy()) {
                AxisOperation op = axisService.getOperation(pi.getOperation());
                if (op != null) {
                    op.getPolicySubject().attachPolicy(policy);
                } else {
                    handleException("Couldn't find the operation specified " + "by the QName : " + pi.getOperation());
                }
            } else if (pi.isMessagePolicy()) {
                if (pi.getOperation() != null) {
                    AxisOperation op = axisService.getOperation(pi.getOperation());
                    if (op != null) {
                        op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(policy);
                    } else {
                        handleException("Couldn't find the operation " + "specified by the QName : " + pi.getOperation());
                    }
                } else {
                    // operation is not specified and hence apply to all the applicable messages
                    for (Iterator itr = axisService.getOperations(); itr.hasNext(); ) {
                        Object obj = itr.next();
                        if (obj instanceof AxisOperation) {
                            // check whether the policy is applicable
                            if (!((obj instanceof OutOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_IN) || (obj instanceof InOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
                                AxisMessage message = ((AxisOperation) obj).getMessage(pi.getMessageLable());
                                message.getPolicySubject().attachPolicy(policy);
                            }
                        }
                    }
                }
            } else {
                handleException("Undefined Policy type");
            }
        }
    }
    // create a custom message receiver for this proxy service
    ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
    msgRcvr.setName(name);
    msgRcvr.setProxy(this);
    Iterator iter = axisService.getOperations();
    while (iter.hasNext()) {
        AxisOperation op = (AxisOperation) iter.next();
        op.setMessageReceiver(msgRcvr);
    }
    try {
        axisService.addParameter(SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
        if (serviceGroup == null) {
            auditInfo("Adding service " + name + " to the Axis2 configuration");
            axisCfg.addService(axisService);
        } else {
            auditInfo("Adding service " + name + " to the service group " + serviceGroup);
            if (axisCfg.getServiceGroup(serviceGroup) == null) {
                // If the specified group does not exist we should create it
                AxisServiceGroup proxyServiceGroup = new AxisServiceGroup();
                proxyServiceGroup.setServiceGroupName(serviceGroup);
                proxyServiceGroup.setParent(axisCfg);
                // Add  the service to the new group and add the group the AxisConfiguration
                proxyServiceGroup.addService(axisService);
                axisCfg.addServiceGroup(proxyServiceGroup);
            } else {
                // Simply add the service to the existing group
                axisService.setParent(axisCfg.getServiceGroup(serviceGroup));
                axisCfg.addServiceToExistingServiceGroup(axisService, serviceGroup);
            }
        }
        this.setRunning(true);
    } catch (AxisFault axisFault) {
        try {
            if (axisCfg.getService(axisService.getName()) != null) {
                if (trace())
                    trace.info("Removing service " + name + " due to error : " + axisFault.getMessage());
                axisCfg.removeService(axisService.getName());
            }
        } catch (AxisFault ignore) {
        }
        handleException("Error adding Proxy service to the Axis2 engine", axisFault);
    }
    // should Addressing be engaged on this service?
    if (wsAddrEnabled) {
        auditInfo("WS-Addressing is enabled for service : " + name);
        try {
            axisService.engageModule(axisCfg.getModule(SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
        } catch (AxisFault axisFault) {
            handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
        }
    }
    // should Security be engaged on this service?
    boolean secModuleEngaged = false;
    if (wsSecEnabled && !isNoSecPolicy) {
        auditInfo("WS-Security is enabled for service : " + name);
        try {
            axisService.engageModule(axisCfg.getModule(SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
            secModuleEngaged = true;
        } catch (AxisFault axisFault) {
            handleException("Error loading WS Sec module on proxy service : " + name, axisFault);
        }
    } else if (isNoSecPolicy) {
        log.info("NoSecurity Policy found, skipping rampart engagement");
    }
    moduleEngaged = secModuleEngaged || wsAddrEnabled;
    wsdlPublished = wsdlFound;
    // Engaging Axis2 modules
    Object engaged_modules = parameters.get(ENGAGED_MODULES);
    if (engaged_modules != null) {
        String[] moduleNames = getModuleNames((String) engaged_modules);
        if (moduleNames != null) {
            for (String moduleName : moduleNames) {
                try {
                    AxisModule axisModule = axisCfg.getModule(moduleName);
                    if (axisModule != null) {
                        axisService.engageModule(axisModule, axisCfg);
                        moduleEngaged = true;
                    }
                } catch (AxisFault axisFault) {
                    handleException("Error loading " + moduleName + " module on proxy service : " + name, axisFault);
                }
            }
        }
    }
    auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
    return axisService;
}
Also used : AxisFault(org.apache.axis2.AxisFault) Policy(org.apache.neethi.Policy) MalformedURLException(java.net.MalformedURLException) InputSource(org.xml.sax.InputSource) SynapseException(org.apache.synapse.SynapseException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) OMElement(org.apache.axiom.om.OMElement) URL(java.net.URL) Endpoint(org.apache.synapse.endpoints.Endpoint) WSDLEndpoint(org.apache.synapse.endpoints.WSDLEndpoint) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) WSDLEndpoint(org.apache.synapse.endpoints.WSDLEndpoint) CustomXmlSchemaURIResolver(org.apache.synapse.util.resolver.CustomXmlSchemaURIResolver) OMNamespace(org.apache.axiom.om.OMNamespace) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyInfo(org.apache.synapse.util.PolicyInfo) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMNode(org.apache.axiom.om.OMNode) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) CustomWSDLLocator(org.apache.synapse.util.resolver.CustomWSDLLocator) ResourceMap(org.apache.synapse.util.resolver.ResourceMap)

Aggregations

Policy (org.apache.neethi.Policy)122 Test (org.junit.Test)47 Assertion (org.apache.neethi.Assertion)27 QName (javax.xml.namespace.QName)23 ArrayList (java.util.ArrayList)21 All (org.apache.neethi.All)18 ExactlyOne (org.apache.neethi.ExactlyOne)18 Message (org.apache.cxf.message.Message)15 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)14 Element (org.w3c.dom.Element)13 Bus (org.apache.cxf.Bus)12 PrimitiveAssertion (org.apache.cxf.ws.policy.builder.primitive.PrimitiveAssertion)12 List (java.util.List)9 Interceptor (org.apache.cxf.interceptor.Interceptor)9 BindingOperationInfo (org.apache.cxf.service.model.BindingOperationInfo)9 HashMap (java.util.HashMap)7 OMElement (org.apache.axiom.om.OMElement)7 MessageImpl (org.apache.cxf.message.MessageImpl)7 ReferenceResolver (org.apache.cxf.ws.policy.attachment.reference.ReferenceResolver)6 InputStream (java.io.InputStream)5