Search in sources :

Example 1 with TypeCastingException

use of jolie.runtime.typing.TypeCastingException in project jolie by jolie.

the class HttpProtocol method recv_internal.

@Override
public CommMessage recv_internal(InputStream istream, OutputStream ostream) throws IOException {
    HttpMessage message = new HttpParser(istream).parse();
    String charset = HttpUtils.getCharset(null, message);
    CommMessage retVal = null;
    DecodedMessage decodedMessage = new DecodedMessage();
    HttpUtils.recv_checkForChannelClosing(message, channel());
    if (checkBooleanParameter(Parameters.DEBUG)) {
        boolean showContent = false;
        if (getParameterFirstValue(Parameters.DEBUG).getFirstChild("showContent").intValue() > 0 && message.size() > 0) {
            showContent = true;
        }
        Interpreter.getInstance().logInfo(getDebugMessage(message, charset, showContent));
    }
    // tracer
    Interpreter.getInstance().tracer().trace(() -> {
        try {
            final String traceMessage = getDebugMessage(message, charset, message.size() > 0);
            return new ProtocolTraceAction(ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE RECEIVED", message.requestPath(), traceMessage, null);
        } catch (IOException e) {
            return new ProtocolTraceAction(ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE RECEIVED", message.requestPath(), e.getMessage(), null);
        }
    });
    recv_checkForStatusCode(message);
    encoding = message.getProperty("accept-encoding");
    headRequest = inInputPort && message.isHead();
    String contentType = DEFAULT_CONTENT_TYPE;
    if (message.getProperty("content-type") != null) {
        contentType = message.getProperty("content-type").split(";", 2)[0].toLowerCase();
    }
    // URI parameter parsing
    if (message.requestPath() != null) {
        boolean strictEncoding = checkStringParameter(Parameters.JSON_ENCODING, "strict");
        recv_parseQueryString(message, decodedMessage.value, contentType, strictEncoding);
    }
    recv_parseRequestFormat(contentType);
    if (!message.isResponse()) {
        recv_checkReceivingOperation(message, decodedMessage);
    }
    /* https://tools.ietf.org/html/rfc7231#section-4.3 */
    if (!message.isGet() && !message.isHead()) {
        // body parsing
        if (message.size() > 0) {
            recv_parseMessage(message, decodedMessage, contentType, charset);
        }
    }
    if (!message.isResponse()) {
        recv_checkDefaultOp(message, decodedMessage);
    }
    if (checkBooleanParameter(Parameters.CONCURRENT)) {
        String messageId = message.getProperty(Headers.JOLIE_MESSAGE_ID);
        if (messageId != null) {
            try {
                decodedMessage.id = Long.parseLong(messageId);
            } catch (NumberFormatException e) {
            }
        }
    }
    if (message.isResponse()) {
        String responseHeader = "";
        if (hasParameter(Parameters.RESPONSE_HEADER) || hasOperationSpecificParameter(inputId, Parameters.RESPONSE_HEADER)) {
            if (hasOperationSpecificParameter(inputId, Parameters.RESPONSE_HEADER)) {
                responseHeader = getOperationSpecificStringParameter(inputId, Parameters.RESPONSE_HEADER);
            } else {
                responseHeader = getStringParameter(Parameters.RESPONSE_HEADER);
            }
            for (Entry<String, String> param : message.properties()) {
                decodedMessage.value.getFirstChild(responseHeader).getFirstChild(param.getKey()).setValue(param.getValue());
            }
            decodedMessage.value.getFirstChild(responseHeader).getFirstChild(Parameters.STATUS_CODE).setValue(message.statusCode());
        }
        recv_checkForSetCookie(message, decodedMessage.value);
        retVal = new CommMessage(decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null);
    } else if (message.isError() == false) {
        recv_checkForMessageProperties(message, decodedMessage);
        retVal = new CommMessage(decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null);
    }
    if (retVal != null && "/".equals(retVal.resourcePath()) && channel().parentPort() != null && (channel().parentPort().getInterface().containsOperation(retVal.operationName()) || (channel().parentInputPort() != null && channel().parentInputPort().getAggregatedOperation(retVal.operationName()) != null))) {
        try {
            // The message is for this service
            boolean hasInput = false;
            OneWayTypeDescription oneWayTypeDescription = null;
            if (channel().parentInputPort() != null) {
                if (channel().parentInputPort().getAggregatedOperation(retVal.operationName()) != null) {
                    oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation(retVal.operationName()).getOperationTypeDescription().asOneWayTypeDescription();
                    hasInput = true;
                }
            }
            if (!hasInput) {
                Interface iface = channel().parentPort().getInterface();
                oneWayTypeDescription = iface.oneWayOperations().get(retVal.operationName());
            }
            if (oneWayTypeDescription != null) {
                // We are receiving a One-Way message
                oneWayTypeDescription.requestType().cast(retVal.value());
            } else {
                hasInput = false;
                RequestResponseTypeDescription rrTypeDescription = null;
                if (channel().parentInputPort() != null) {
                    if (channel().parentInputPort().getAggregatedOperation(retVal.operationName()) != null) {
                        rrTypeDescription = channel().parentInputPort().getAggregatedOperation(retVal.operationName()).getOperationTypeDescription().asRequestResponseTypeDescription();
                        hasInput = true;
                    }
                }
                if (!hasInput) {
                    Interface iface = channel().parentPort().getInterface();
                    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 : RequestResponseTypeDescription(jolie.runtime.typing.RequestResponseTypeDescription) ProtocolTraceAction(jolie.tracer.ProtocolTraceAction) IOException(java.io.IOException) OneWayTypeDescription(jolie.runtime.typing.OneWayTypeDescription) Type(jolie.runtime.typing.Type) NativeType(jolie.lang.NativeType) HttpParser(jolie.net.http.HttpParser) HttpMessage(jolie.net.http.HttpMessage) TypeCastingException(jolie.runtime.typing.TypeCastingException) Interface(jolie.net.ports.Interface)

Example 2 with TypeCastingException

use of jolie.runtime.typing.TypeCastingException 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 3 with TypeCastingException

use of jolie.runtime.typing.TypeCastingException in project jolie by jolie.

the class Value method boolValueStrict.

public boolean boolValueStrict() throws TypeCastingException {
    boolean r = false;
    Object o = valueObject();
    if (o == null) {
        throw new TypeCastingException();
    } else if (o instanceof Boolean) {
        r = ((Boolean) o).booleanValue();
    } else if (o instanceof Number) {
        if (((Number) o).longValue() > 0) {
            r = true;
        }
    } else if (o instanceof String) {
        r = Boolean.parseBoolean(((String) o).trim());
    } else if (o instanceof ByteArray) {
        try {
            return new DataInputStream(new ByteArrayInputStream(((ByteArray) o).getBytes())).readBoolean();
        } catch (IOException e) {
            throw new TypeCastingException();
        }
    }
    return r;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) TypeCastingException(jolie.runtime.typing.TypeCastingException) DataInputStream(java.io.DataInputStream)

Example 4 with TypeCastingException

use of jolie.runtime.typing.TypeCastingException in project jolie by jolie.

the class Value method doubleValueStrict.

public final double doubleValueStrict() throws TypeCastingException {
    double r = 0.0;
    Object o = valueObject();
    if (o == null) {
        throw new TypeCastingException();
    } else if (o instanceof Integer) {
        r = ((Integer) o).doubleValue();
    } else if (o instanceof Double) {
        r = ((Double) o).doubleValue();
    } else if (o instanceof Long) {
        r = ((Long) o).doubleValue();
    } else if (o instanceof Boolean) {
        r = (((Boolean) o).booleanValue() == true) ? 1.0 : 0.0;
    } else if (o instanceof String) {
        try {
            r = Double.parseDouble(((String) o).trim());
        } catch (NumberFormatException nfe) {
            throw new TypeCastingException();
        }
    } else if (o instanceof ByteArray) {
        try {
            return new DataInputStream(new ByteArrayInputStream(((ByteArray) o).getBytes())).readDouble();
        } catch (IOException e) {
            throw new TypeCastingException();
        }
    }
    return r;
}
Also used : IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TypeCastingException(jolie.runtime.typing.TypeCastingException)

Example 5 with TypeCastingException

use of jolie.runtime.typing.TypeCastingException in project jolie by jolie.

the class Value method longValueStrict.

public final long longValueStrict() throws TypeCastingException {
    long r = 0L;
    Object o = valueObject();
    if (o == null) {
        throw new TypeCastingException();
    } else if (o instanceof Long) {
        r = ((Long) o).longValue();
    } else if (o instanceof Integer) {
        // added by Balint Maschio
        r = ((Integer) o).longValue();
    } else if (o instanceof Boolean) {
        r = (((Boolean) o).booleanValue() == true) ? 1L : 0L;
    } else if (o instanceof Double) {
        r = ((Double) o).longValue();
    } else if (o instanceof String) {
        try {
            r = Long.parseLong(((String) o).trim());
        } catch (NumberFormatException nfe) {
            throw new TypeCastingException();
        }
    } else if (o instanceof ByteArray) {
        try {
            return new DataInputStream(new ByteArrayInputStream(((ByteArray) o).getBytes())).readLong();
        } catch (IOException e) {
            throw new TypeCastingException();
        }
    }
    return r;
}
Also used : IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TypeCastingException(jolie.runtime.typing.TypeCastingException)

Aggregations

IOException (java.io.IOException)7 TypeCastingException (jolie.runtime.typing.TypeCastingException)7 ByteArrayInputStream (java.io.ByteArrayInputStream)5 DataInputStream (java.io.DataInputStream)4 HttpMessage (jolie.net.http.HttpMessage)2 HttpParser (jolie.net.http.HttpParser)2 Interface (jolie.net.ports.Interface)2 OneWayTypeDescription (jolie.runtime.typing.OneWayTypeDescription)2 RequestResponseTypeDescription (jolie.runtime.typing.RequestResponseTypeDescription)2 Type (jolie.runtime.typing.Type)2 ProtocolTraceAction (jolie.tracer.ProtocolTraceAction)2 XSComplexType (com.sun.xml.xsom.XSComplexType)1 XSContentType (com.sun.xml.xsom.XSContentType)1 XSSchema (com.sun.xml.xsom.XSSchema)1 XSType (com.sun.xml.xsom.XSType)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataOutputStream (java.io.DataOutputStream)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 LinkedList (java.util.LinkedList)1