Search in sources :

Example 86 with OMException

use of org.apache.axiom.om.OMException in project wso2-synapse by wso2.

the class JSONTransformMediator method mediate.

@Override
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : JSONTransform mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    if (!propertiesArrayList.isEmpty()) {
        try {
            // Passing the the custom jsonOutputFactory and converting the Envelope body to JSON
            String jsonPayloadFromOMElement = JsonUtil.toJsonString(((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().getBody().getFirstElement(), jsonOutputFactory).toString();
            // Update the jsonstream with the newly build payload
            JsonUtil.getNewJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext(), jsonPayloadFromOMElement, true, true);
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("JSON stream after converting xml to json : " + jsonPayloadFromOMElement);
            }
        } catch (AxisFault af) {
            handleException("Axisfault occured when updating the " + "JSON stream after applying the properties: ", af, synCtx);
        }
    }
    if (schemaKey != null) {
        // Derive actual key from message context
        String generatedSchemaKey = schemaKey.evaluateValue(synCtx);
        Object jsonSchemaObj = synCtx.getEntry(generatedSchemaKey);
        if (jsonSchemaObj != null) {
            String schema = "";
            if (jsonSchemaObj instanceof OMTextImpl) {
                try {
                    // reading the schema with the media-type application/json
                    schema = JsonLoader.fromReader(new InputStreamReader(((OMTextImpl) jsonSchemaObj).getInputStream())).toString();
                } catch (OMException e) {
                    // reading the schema with the media type "unknown"
                    schema = ((OMTextImpl) jsonSchemaObj).getText();
                } catch (IOException e) {
                    handleException("Error while reading schema from registry", e, synCtx);
                }
            } else if (jsonSchemaObj instanceof String) {
                schema = (String) jsonSchemaObj;
            } else {
                handleException("Can not find valid JSON Schema content", synCtx);
            }
            try {
                String jsonPayload;
                if (JsonUtil.hasAJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext())) {
                    jsonPayload = JsonUtil.jsonPayloadToString(((Axis2MessageContext) synCtx).getAxis2MessageContext());
                } else {
                    jsonPayload = JsonUtil.toJsonString(((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().getBody().getFirstElement()).toString();
                }
                String result = JsonProcessor.parseJson(jsonPayload, schema);
                JsonUtil.getNewJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext(), result, true, true);
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("JSON stream after applying schema : " + ((result != null) ? result : ""));
                }
            } catch (ValidatorException | ParserException e) {
                handleException(e.getMessage(), e, synCtx);
            } catch (AxisFault af) {
                handleException("Axisfault fault occured when updating the " + "JSON stream after applying the JSON schema", af, synCtx);
            }
        } else {
            handleException("Schema does not exist in the specified location : " + generatedSchemaKey, synCtx);
        }
    }
    synLog.traceOrDebug("End : JSON Transform mediator");
    return true;
}
Also used : AxisFault(org.apache.axis2.AxisFault) ParserException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException) SynapseLog(org.apache.synapse.SynapseLog) ValidatorException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException) InputStreamReader(java.io.InputStreamReader) OMTextImpl(org.apache.axiom.om.impl.llom.OMTextImpl) IOException(java.io.IOException) OMException(org.apache.axiom.om.OMException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 87 with OMException

use of org.apache.axiom.om.OMException in project wso2-synapse by wso2.

the class AbstractRegistry method getResource.

/**
 * Get the resource for the given key from this registry
 * @param entry The Enrty instance that contains meta-data
 * @param properties bag of properties with additional information
 * @return the matching resultant object
 */
public Object getResource(Entry entry, Properties properties) {
    OMNode omNode = null;
    RegistryEntry re = null;
    // if we have an unexpired cached copy, return the cached object
    if (entry.isCached() && !entry.isExpired()) {
        return entry.getValue();
    // if we have not cached the referenced object, fetch it and its RegistryEntry
    } else if (!entry.isCached()) {
        try {
            omNode = lookup(entry.getKey());
            entry.setEntryProperties(getResourceProperties(entry.getKey()));
        } catch (OMException e) {
            log.error("Error reading registry resource file : " + entry.getKey(), e);
        }
        if (omNode == null && entry.getEntryProperties() != null && !entry.getEntryProperties().isEmpty()) {
            // Collection
            re = getRegistryEntry(entry.getKey());
            if (re != null) {
                setExpiryTime(entry, re);
                entry.setVersion(re.getVersion());
            }
        }
        if (omNode == null) {
            return null;
        } else {
            re = getRegistryEntry(entry.getKey());
        }
    // if we have cached it before, and now the cache has expired
    // get its *new* registry entry and compare versions and pick new cache duration
    } else if (entry.isExpired()) {
        if (log.isDebugEnabled()) {
            log.debug("Cached object has expired for key : " + entry.getKey());
        }
        re = getRegistryEntry(entry.getKey());
        if (re.getVersion() != Long.MIN_VALUE && re.getVersion() == entry.getVersion()) {
            if (log.isDebugEnabled()) {
                log.debug("Expired version number is same as current version in registry");
            }
            // renew cache lease for another cachable duration (as returned by the
            // new getRegistryEntry() call
            setExpiryTime(entry, re);
            if (log.isDebugEnabled()) {
                log.debug("Renew cache lease for another " + re.getCachableDuration() / 1000 + "s");
            }
            // return cached object
            return entry.getValue();
        } else {
            omNode = lookup(entry.getKey());
            entry.setEntryProperties(getResourceProperties(entry.getKey()));
            if (omNode == null && entry.getEntryProperties() != null && !entry.getEntryProperties().isEmpty()) {
                // Collection
                re = getRegistryEntry(entry.getKey());
                if (re != null) {
                    setExpiryTime(entry, re);
                    entry.setVersion(re.getVersion());
                }
            }
            if (omNode == null) {
                return null;
            }
        }
    }
    // if we get here, we have received the raw omNode from the
    // registry and our previous copy (if we had one) has expired or is not valid
    Object expiredValue = entry.getValue();
    // resource into the appropriate object - e.g. sequence or endpoint
    if (entry.getMapper() != null) {
        entry.setValue(entry.getMapper().getObjectFromOMNode(omNode, properties));
        if (entry.getValue() instanceof SequenceMediator) {
            SequenceMediator seq = (SequenceMediator) entry.getValue();
            seq.setDynamic(true);
            seq.setRegistryKey(entry.getKey());
        } else if (entry.getValue() instanceof Endpoint) {
            Endpoint ep = (Endpoint) entry.getValue();
        } else if (entry.getValue() instanceof TemplateMediator) {
            ((TemplateMediator) entry.getValue()).setDynamic(true);
        }
    } else {
        // else cache the raw OMNode
        if (re != null && re.getType() != null) {
            XMLToObjectMapper mapper = getMapper(re.getType());
            if (mapper != null) {
                entry.setMapper(mapper);
                entry.setValue(mapper.getObjectFromOMNode(omNode, properties));
            } else {
                entry.setValue(omNode);
            }
        }
    }
    if (expiredValue != null) {
        // Destroy the old resource so that everything is properly cleaned up
        if (expiredValue instanceof SequenceMediator) {
            ((SequenceMediator) expiredValue).destroy();
        } else if (expiredValue instanceof Endpoint) {
            ((Endpoint) expiredValue).destroy();
        }
    }
    // increment cache expiry time as specified by the last getRegistryEntry() call
    if (re != null) {
        setExpiryTime(entry, re);
        entry.setVersion(re.getVersion());
    }
    return entry.getValue();
}
Also used : OMNode(org.apache.axiom.om.OMNode) Endpoint(org.apache.synapse.endpoints.Endpoint) TemplateMediator(org.apache.synapse.mediators.template.TemplateMediator) SequenceMediator(org.apache.synapse.mediators.base.SequenceMediator) OMException(org.apache.axiom.om.OMException) XMLToObjectMapper(org.apache.synapse.config.XMLToObjectMapper)

Example 88 with OMException

use of org.apache.axiom.om.OMException in project wso2-synapse by wso2.

the class SynapseConfigUtils method getObject.

/**
 * Get an object from a given URL. Will first fetch the content from the
 * URL and depending on the content-type, a suitable XMLToObjectMapper
 * (if available) would be used to transform this content into an Object.
 * If a suitable XMLToObjectMapper cannot be found, the content would be
 * treated as XML and an OMNode would be returned
 *
 * @param url the URL to the resource
 * @param properties bag of properties to pass in any information to the factory
 * @return an Object created from the given URL
 */
public static Object getObject(URL url, Properties properties) {
    try {
        if (url != null && "file".equals(url.getProtocol())) {
            try {
                url.openStream();
            } catch (IOException ignored) {
                String path = url.getPath();
                if (log.isDebugEnabled()) {
                    log.debug("Can not open a connection to the URL with a path :" + path);
                }
                String synapseHome = (String) properties.get(SynapseConstants.SYNAPSE_HOME);
                if (synapseHome != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Trying  to resolve an absolute path of the " + " URL using the synapse.home : " + synapseHome);
                    }
                    if (synapseHome.endsWith("/")) {
                        synapseHome = synapseHome.substring(0, synapseHome.lastIndexOf("/"));
                    }
                    url = new URL(url.getProtocol() + ":" + synapseHome + "/" + path);
                    try {
                        url.openStream();
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug("Failed to resolve an absolute path of the " + " URL using the synapse.home : " + synapseHome);
                        }
                        log.warn("IO Error reading from URL " + url.getPath() + e);
                    }
                }
            }
        }
        if (url == null) {
            return null;
        }
        URLConnection connection = getURLConnection(url);
        if (connection == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot create a URLConnection for given URL : " + url);
            }
            return null;
        }
        XMLToObjectMapper xmlToObject = getXmlToObjectMapper(connection.getContentType());
        InputStream inputStream = connection.getInputStream();
        try {
            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            OMElement omElem = builder.getDocumentElement();
            // detach from URL connection and keep in memory
            // TODO remove this
            omElem.build();
            if (xmlToObject != null) {
                return xmlToObject.getObjectFromOMNode(omElem, properties);
            } else {
                return omElem;
            }
        } catch (XMLStreamException e) {
            if (log.isDebugEnabled()) {
                log.debug("Content at URL : " + url + " is non XML..");
            }
            return readNonXML(url);
        } catch (OMException e) {
            if (log.isDebugEnabled()) {
                log.debug("Content at URL : " + url + " is non XML..");
            }
            return readNonXML(url);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        handleException("Error connecting to URL : " + url, e);
    }
    return null;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) OMException(org.apache.axiom.om.OMException) URL(java.net.URL) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 89 with OMException

use of org.apache.axiom.om.OMException in project wso2-synapse by wso2.

the class ConnectorDeployer method addEntry.

/**
 * Add a local entry.
 *
 * @param element ekement string
 * @param axisConfig AxisConfiguration of the current tenant
 */
private static boolean addEntry(String element, AxisConfiguration axisConfig) {
    final Lock lock = getLock(axisConfig);
    try {
        lock.lock();
        OMElement elem;
        try {
            elem = nonCoalescingStringToOm(element);
        } catch (XMLStreamException e) {
            log.error("Error while converting the file content : ", e);
            return false;
        }
        if (elem.getQName().getLocalPart().equals(XMLConfigConstants.ENTRY_ELT.getLocalPart())) {
            String entryKey = elem.getAttributeValue(new QName("key"));
            entryKey = entryKey.trim();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration(axisConfig);
            if (log.isDebugEnabled()) {
                log.debug("Adding local entry with key : " + entryKey);
            }
            if (synapseConfiguration.getLocalRegistry().containsKey(entryKey)) {
                log.error("An Entry with key " + entryKey + " is already used within the configuration");
            } else {
                Entry entry = EntryFactory.createEntry(elem, synapseConfiguration.getProperties());
                entry.setFileName(generateFileName(entry.getKey()));
                synapseConfiguration.addEntry(entryKey, entry);
            }
            if (log.isDebugEnabled()) {
                log.debug("Local registry entry : " + entryKey + " added to the configuration");
            }
            return true;
        } else {
            log.warn("Error adding local entry. Invalid definition");
        }
    } catch (SynapseException syne) {
        log.error("Unable to add local entry ", syne);
    } catch (OMException e) {
        log.error("Unable to add local entry. Invalid XML ", e);
    } catch (Exception e) {
        log.error("Unable to add local entry. Invalid XML ", e);
    } finally {
        lock.unlock();
    }
    return false;
}
Also used : Entry(org.apache.synapse.config.Entry) XMLStreamException(javax.xml.stream.XMLStreamException) SynapseException(org.apache.synapse.SynapseException) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) OMException(org.apache.axiom.om.OMException) XMLStreamException(javax.xml.stream.XMLStreamException) DeploymentException(org.apache.axis2.deployment.DeploymentException) SynapseException(org.apache.synapse.SynapseException) IOException(java.io.IOException) OMException(org.apache.axiom.om.OMException) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Aggregations

OMException (org.apache.axiom.om.OMException)89 OMElement (org.apache.axiom.om.OMElement)35 XMLStreamException (javax.xml.stream.XMLStreamException)31 IOException (java.io.IOException)30 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)18 InputStream (java.io.InputStream)16 QName (javax.xml.namespace.QName)13 OMFactory (org.apache.axiom.om.OMFactory)12 ArrayList (java.util.ArrayList)11 MalformedURLException (java.net.MalformedURLException)10 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 ParseException (org.json.simple.parser.ParseException)9 APIMgtResourceAlreadyExistsException (org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException)9 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)9 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)9 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)9 UnsupportedPolicyTypeException (org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException)9