Search in sources :

Example 1 with FaultException

use of jolie.runtime.FaultException in project jolie by jolie.

the class SoapProtocol method recv_internal.

/*
	 * private Schema getRecvMessageValidationSchema() throws IOException { List< Source > sources = new
	 * ArrayList< Source >(); Definition definition = getWSDLDefinition(); if ( definition != null ) {
	 * Types types = definition.getTypes(); if ( types != null ) { List< ExtensibilityElement > list =
	 * types.getExtensibilityElements(); for( ExtensibilityElement element : list ) { if ( element
	 * instanceof SchemaImpl ) { sources.add( new DOMSource( ((SchemaImpl)element).getElement() ) ); } }
	 * } } SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI
	 * ); try { return schemaFactory.newSchema( sources.toArray( new Source[sources.size()] ) ); }
	 * catch( SAXException e ) { throw new IOException( e ); } }
	 */
public CommMessage recv_internal(InputStream istream, OutputStream ostream) throws IOException {
    HttpParser parser = new HttpParser(istream);
    HttpMessage message = parser.parse();
    String charset = HttpUtils.getCharset(null, message);
    HttpUtils.recv_checkForChannelClosing(message, channel());
    if (inInputPort && message.type() != HttpMessage.Type.POST) {
        throw new UnsupportedMethodException("Only HTTP method POST allowed!", Method.POST);
    }
    encoding = message.getProperty("accept-encoding");
    CommMessage retVal = null;
    String messageId = "";
    FaultException fault = null;
    Value value = Value.create();
    try {
        if (message.size() > 0) {
            if (checkBooleanParameter("debug")) {
                interpreter.logInfo("[SOAP debug] Receiving:\n" + new String(message.content(), charset));
            }
            SOAPMessage soapMessage = messageFactory.createMessage();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            /*
				 * Schema messageSchema = getRecvMessageValidationSchema(); if ( messageSchema != null ) {
				 * factory.setIgnoringElementContentWhitespace( true ); factory.setSchema( messageSchema ); }
				 */
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource src = new InputSource(new ByteArrayInputStream(message.content()));
            src.setEncoding(charset);
            Document doc = builder.parse(src);
            DOMSource dom = new DOMSource(doc);
            soapMessage.getSOAPPart().setContent(dom);
            /*
				 * if ( checkBooleanParameter( "debugAfter" ) ) { ByteArrayOutputStream tmpStream = new
				 * ByteArrayOutputStream(); soapMessage.writeTo( tmpStream ); interpreter.logInfo(
				 * "[SOAP debug] Receiving:\n" + tmpStream.toString() ); }
				 */
            SOAPFault soapFault = soapMessage.getSOAPBody().getFault();
            if (soapFault == null) {
                Element soapValueElement = getFirstElement(soapMessage.getSOAPBody());
                messageId = soapValueElement.getLocalName();
                if (!channel().parentPort().getInterface().containsOperation(messageId)) {
                    String[] soapAction = message.getPropertyOrEmptyString("soapaction").replaceAll("\"", "").split("/");
                    messageId = soapAction[soapAction.length - 1];
                    if (checkBooleanParameter("debug")) {
                        interpreter.logInfo("Operation from SoapAction:" + messageId);
                    }
                }
                // explanation: https://github.com/jolie/jolie/issues/5
                xmlNodeToValue(value, soapValueElement, checkBooleanParameter("dropRootValue", false));
                ValueVector schemaPaths = getParameterVector("schema");
                if (schemaPaths.size() > 0) {
                    List<Source> sources = new LinkedList<>();
                    Value schemaPath;
                    for (int i = 0; i < schemaPaths.size(); i++) {
                        schemaPath = schemaPaths.get(i);
                        if (schemaPath.getChildren("validate").first().intValue() > 0) {
                            sources.add(new StreamSource(new File(schemaPaths.get(i).strValue())));
                        }
                    }
                    if (!sources.isEmpty()) {
                        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources.toArray(new Source[0]));
                        schema.newValidator().validate(new DOMSource(soapMessage.getSOAPBody().getFirstChild()));
                    }
                }
            } else {
                String faultName = "UnknownFault";
                Value faultValue = Value.create();
                Detail d = soapFault.getDetail();
                if (d != null) {
                    Node n = d.getFirstChild();
                    if (n != null) {
                        faultName = n.getLocalName();
                        xmlNodeToValue(faultValue, n, true);
                    } else {
                        faultValue.setValue(soapFault.getFaultString());
                    }
                }
                fault = new FaultException(faultName, faultValue);
            }
        }
        String resourcePath = recv_getResourcePath(message);
        if (message.isResponse()) {
            if (fault != null && message.statusCode() == 500) {
                fault = new FaultException("InternalServerError", "");
            }
            retVal = new CommMessage(CommMessage.GENERIC_ID, inputId, resourcePath, value, fault);
        } else if (!message.isError()) {
            if (messageId.isEmpty()) {
                throw new IOException("Received SOAP Message without a specified operation");
            }
            retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, resourcePath, value, fault);
        }
        final String mId = messageId;
        interpreter.tracer().trace(() -> {
            final StringBuilder traceMessage = new StringBuilder();
            try {
                traceMessage.append(getHeadersFromHttpMessage(message)).append("\n").append(new String(message.content(), charset));
                return new ProtocolTraceAction(ProtocolTraceAction.Type.SOAP, "SOAP MESSAGE RECEIVED", mId, traceMessage.toString(), null);
            } catch (UnsupportedEncodingException e) {
                return new ProtocolTraceAction(ProtocolTraceAction.Type.SOAP, "SOAP MESSAGE RECEIVED", mId, e.getMessage(), null);
            }
        });
    } catch (SOAPException | ParserConfigurationException e) {
        throw new IOException(e);
    } catch (SAXException e) {
        // TODO support resourcePath
        retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, "/", value, new FaultException("TypeMismatch", e));
    }
    received = true;
    if (retVal != null && "/".equals(retVal.resourcePath()) && channel().parentPort() != null && channel().parentPort().getInterface().containsOperation(retVal.operationName())) {
        try {
            // The message is for this service
            Interface iface = channel().parentPort().getInterface();
            OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get(retVal.operationName());
            if (oneWayTypeDescription != null) {
                // We are receiving a One-Way message
                if (message.isResponse() == false) {
                    oneWayTypeDescription.requestType().cast(retVal.value());
                }
            } else {
                RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get(retVal.operationName());
                if (retVal.isFault()) {
                    Type faultType = rrTypeDescription.faults().get(retVal.fault().faultName());
                    if (faultType != null) {
                        faultType.cast(retVal.value());
                    }
                } else if (message.isResponse()) {
                    rrTypeDescription.responseType().cast(retVal.value());
                } else {
                    rrTypeDescription.requestType().cast(retVal.value());
                }
            }
        } catch (TypeCastingException e) {
        // TODO: do something here?
        }
    }
    return retVal;
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) SOAPBodyElement(javax.xml.soap.SOAPBodyElement) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) Element(org.w3c.dom.Element) XSSchema(com.sun.xml.xsom.XSSchema) Schema(javax.xml.validation.Schema) Node(org.w3c.dom.Node) RequestResponseTypeDescription(jolie.runtime.typing.RequestResponseTypeDescription) ProtocolTraceAction(jolie.tracer.ProtocolTraceAction) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXException(org.xml.sax.SAXException) FaultException(jolie.runtime.FaultException) SOAPException(javax.xml.soap.SOAPException) HttpParser(jolie.net.http.HttpParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnsupportedMethodException(jolie.net.http.UnsupportedMethodException) StreamSource(javax.xml.transform.stream.StreamSource) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) OneWayTypeDescription(jolie.runtime.typing.OneWayTypeDescription) LinkedList(java.util.LinkedList) ValueVector(jolie.runtime.ValueVector) XSType(com.sun.xml.xsom.XSType) OperationType(javax.wsdl.OperationType) Type(jolie.runtime.typing.Type) XSComplexType(com.sun.xml.xsom.XSComplexType) XSContentType(com.sun.xml.xsom.XSContentType) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Value(jolie.runtime.Value) SOAPFault(javax.xml.soap.SOAPFault) HttpMessage(jolie.net.http.HttpMessage) TypeCastingException(jolie.runtime.typing.TypeCastingException) File(java.io.File) Detail(javax.xml.soap.Detail) Interface(jolie.net.ports.Interface)

Example 2 with FaultException

use of jolie.runtime.FaultException in project jolie by jolie.

the class XmlRpcProtocol method recv_internal.

public CommMessage recv_internal(InputStream istream, OutputStream ostream) throws IOException {
    HttpParser parser = new HttpParser(istream);
    HttpMessage message = parser.parse();
    String charset = HttpUtils.getCharset(null, message);
    HttpUtils.recv_checkForChannelClosing(message, channel());
    CommMessage retVal = null;
    FaultException fault = null;
    Value value = Value.create();
    Document doc = null;
    if (message.isError()) {
        throw new IOException("HTTP error: " + new String(message.content(), charset));
    }
    if (inInputPort && message.type() != HttpMessage.Type.POST) {
        throw new UnsupportedMethodException("Only HTTP method POST allowed!", Method.POST);
    }
    encoding = message.getProperty("accept-encoding");
    if (message.size() > 0) {
        if (getParameterVector("debug").first().intValue() > 0) {
            interpreter.logInfo("[XMLRPC debug] Receiving:\n" + new String(message.content(), charset));
        }
        try {
            DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
            InputSource src = new InputSource(new ByteArrayInputStream(message.content()));
            src.setEncoding(charset);
            doc = builder.parse(src);
            if (message.isResponse()) {
                // test if the message contains a fault
                try {
                    Element faultElement = getFirstElement(doc.getDocumentElement(), "fault");
                    Element struct = getFirstElement(getFirstElement(faultElement, "value"), "struct");
                    NodeList members = struct.getChildNodes();
                    if (members.getLength() != 2 || members.item(1).getNodeType() != Node.ELEMENT_NODE) {
                        throw new IOException("Malformed fault data");
                    }
                    Element faultMember = (Element) members.item(1);
                    // Element valueElement = getFirstElement( getFirstElement( struct, "value" ), "string" );
                    String faultName = getFirstElement(faultMember, "name").getTextContent();
                    String faultString = getFirstElement(getFirstElement(faultMember, "value"), "string").getTextContent();
                    fault = new FaultException(faultName, Value.create(faultString));
                } catch (IOException e) {
                    documentToValue(value, doc);
                }
            } else {
                documentToValue(value, doc);
            }
        } catch (ParserConfigurationException | SAXException pce) {
            throw new IOException(pce);
        }
        if (message.isResponse()) {
            // fault = new FaultException( "InternalServerError", "" );
            // TODO support resourcePath
            retVal = new CommMessage(CommMessage.GENERIC_ID, inputId, "/", value, fault);
        } else if (!message.isError()) {
            // TODO support resourcePath
            String opname = doc.getDocumentElement().getFirstChild().getTextContent();
            retVal = new CommMessage(CommMessage.GENERIC_ID, opname, "/", value, fault);
        }
    }
    received = true;
    return retVal;
}
Also used : InputSource(org.xml.sax.InputSource) UnsupportedMethodException(jolie.net.http.UnsupportedMethodException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) FaultException(jolie.runtime.FaultException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Value(jolie.runtime.Value) HttpParser(jolie.net.http.HttpParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HttpMessage(jolie.net.http.HttpMessage)

Example 3 with FaultException

use of jolie.runtime.FaultException in project jolie by jolie.

the class DatabaseService method connect.

@RequestResponse
public void connect(Value request) throws FaultException {
    close();
    mustCheckConnection = request.getFirstChild("checkConnection").intValue() > 0;
    toLowerCase = request.getFirstChild("toLowerCase").isDefined() && request.getFirstChild("toLowerCase").boolValue();
    toUpperCase = request.getFirstChild("toUpperCase").isDefined() && request.getFirstChild("toUpperCase").boolValue();
    driver = request.getChildren("driver").first().strValue();
    if (request.getFirstChild("driver").hasChildren("class")) {
        driverClass = request.getFirstChild("driver").getFirstChild("class").strValue();
    }
    String host = request.getChildren("host").first().strValue();
    String port = request.getChildren("port").first().strValue();
    String databaseName = request.getChildren("database").first().strValue();
    username = request.getChildren("username").first().strValue();
    password = request.getChildren("password").first().strValue();
    String attributes = request.getFirstChild("attributes").strValue();
    String separator = "/";
    boolean isEmbedded = false;
    String encoding = "utf8";
    if (request.hasChildren("encoding")) {
        request.getFirstChild("encoding").strValue();
    }
    try {
        if (driverClass == null) {
            if ("postgresql".equals(driver)) {
                Class.forName("org.postgresql.Driver");
            } else if ("mysql".equals(driver)) {
                Class.forName("com.mysql.jdbc.Driver");
            } else if ("derby".equals(driver)) {
                Class.forName("org.apache.derby.jdbc.ClientDriver");
            } else if ("sqlite".equals(driver)) {
                Class.forName("org.sqlite.JDBC");
                isEmbedded = true;
            } else if ("sqlserver".equals(driver)) {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                separator = ";";
                databaseName = "databaseName=" + databaseName;
            } else if ("as400".equals(driver)) {
                Class.forName("com.ibm.as400.access.AS400JDBCDriver");
            } else if ("derby_embedded".equals(driver)) {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                isEmbedded = true;
                driver = "derby";
            } else if ("hsqldb_hsql".equals(driver) || "hsqldb_hsqls".equals(driver) || "hsqldb_http".equals(driver) || "hsqldb_https".equals(driver)) {
                Class.forName("org.hsqldb.jdbcDriver");
            } else if ("hsqldb_embedded".equals(driver)) {
                Class.forName("org.hsqldb.jdbcDriver");
                isEmbedded = true;
                driver = "hsqldb";
            } else if ("db2".equals(driver)) {
                Class.forName("com.ibm.db2.jcc.DB2Driver");
            } else {
                throw new FaultException("InvalidDriver", "Unknown type of driver: " + driver);
            }
        } else {
            Class.forName(driverClass);
        }
        if (isEmbedded) {
            connectionString = "jdbc:" + driver + ":" + databaseName;
            if (!attributes.isEmpty()) {
                connectionString += ";" + attributes;
            }
            if ("hsqldb".equals(driver)) {
                connection = DriverManager.getConnection(connectionString, username, password);
            } else {
                connection = DriverManager.getConnection(connectionString);
            }
        } else {
            if (driver.startsWith("hsqldb")) {
                connectionString = "jdbc:" + driver + ":" + driver.substring(driver.indexOf('_') + 1) + "//" + host + (port.isEmpty() ? "" : ":" + port) + separator + databaseName + "?characterEncoding=" + encoding;
            } else {
                connectionString = "jdbc:" + driver + "://" + host + (port.isEmpty() ? "" : ":" + port) + separator + databaseName + "?characterEncoding=" + encoding;
            }
            connection = DriverManager.getConnection(connectionString, username, password);
        }
        if (connection == null) {
            throw new FaultException("ConnectionError");
        }
    } catch (ClassNotFoundException e) {
        throw new FaultException("DriverClassNotFound", e);
    } catch (SQLException e) {
        throw new FaultException("ConnectionError", e);
    }
}
Also used : FaultException(jolie.runtime.FaultException) SQLException(java.sql.SQLException) RequestResponse(jolie.runtime.embedding.RequestResponse)

Example 4 with FaultException

use of jolie.runtime.FaultException in project jolie by jolie.

the class RuntimeService method getRedirection.

public Value getRedirection(Value request) throws FaultException {
    Value ret;
    String inputPortName = request.getChildren("inputPortName").first().strValue();
    CommListener listener = interpreter().commCore().getListenerByInputPortName(inputPortName);
    if (listener == null) {
        throw new FaultException("RuntimeException", Value.create("Invalid input port: " + inputPortName));
    }
    String resourceName = request.getChildren("resourceName").first().strValue();
    OutputPort p = listener.inputPort().redirectionMap().get(resourceName);
    if (p == null) {
        ret = Value.create();
    } else {
        ret = Value.create(p.id());
    }
    return ret;
}
Also used : OutputPort(jolie.net.ports.OutputPort) FaultException(jolie.runtime.FaultException) CommListener(jolie.net.CommListener) Value(jolie.runtime.Value)

Example 5 with FaultException

use of jolie.runtime.FaultException in project jolie by jolie.

the class RuntimeService method removeRedirection.

@RequestResponse
public void removeRedirection(Value request) throws FaultException {
    String serviceName = request.getChildren("inputPortName").first().strValue();
    CommListener listener = interpreter().commCore().getListenerByInputPortName(serviceName);
    if (listener == null) {
        throw new FaultException("RuntimeException", "Unknown inputPort: " + serviceName);
    }
    String resourceName = request.getChildren("resourceName").first().strValue();
    listener.inputPort().redirectionMap().remove(resourceName);
}
Also used : FaultException(jolie.runtime.FaultException) CommListener(jolie.net.CommListener) RequestResponse(jolie.runtime.embedding.RequestResponse)

Aggregations

FaultException (jolie.runtime.FaultException)81 Value (jolie.runtime.Value)51 IOException (java.io.IOException)44 RequestResponse (jolie.runtime.embedding.RequestResponse)25 File (java.io.File)11 ValueVector (jolie.runtime.ValueVector)11 ParseException (java.text.ParseException)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)9 SimpleDateFormat (java.text.SimpleDateFormat)8 TransformerException (javax.xml.transform.TransformerException)8 Document (org.w3c.dom.Document)8 FileInputStream (java.io.FileInputStream)7 URISyntaxException (java.net.URISyntaxException)7 InputStream (java.io.InputStream)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InputStreamReader (java.io.InputStreamReader)5 DOMSource (javax.xml.transform.dom.DOMSource)5 ByteArray (jolie.runtime.ByteArray)5 TypeCheckingException (jolie.runtime.typing.TypeCheckingException)5