Search in sources :

Example 11 with Argument

use of org.teiid.language.Argument in project teiid by teiid.

the class BinaryWSProcedureExecution method execute.

public void execute() throws TranslatorException {
    List<Argument> arguments = this.procedure.getArguments();
    String method = (String) arguments.get(0).getArgumentValue().getValue();
    Object payload = arguments.get(1).getArgumentValue().getValue();
    String endpoint = (String) arguments.get(2).getArgumentValue().getValue();
    try {
        Dispatch<DataSource> dispatch = this.conn.createDispatch(HTTPBinding.HTTP_BINDING, endpoint, DataSource.class, Mode.MESSAGE);
        if (method == null) {
            // $NON-NLS-1$
            method = "POST";
        }
        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_METHOD, method);
        if (payload != null && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method) && !"PATCH".equalsIgnoreCase(method)) {
            // $NON-NLS-1$
            throw new WebServiceException(WSExecutionFactory.UTIL.getString("http_usage_error"));
        }
        Map<String, List<String>> httpHeaders = (Map<String, List<String>>) dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
        if (customHeaders != null) {
            httpHeaders.putAll(customHeaders);
        }
        if (arguments.size() > 5 && // designer modeled the return value as an out, which will add an argument in the 5th position that is an out
        this.procedure.getMetadataObject() != null && (this.procedure.getMetadataObject().getParameters().get(0).getType() == Type.ReturnValue || arguments.get(5).getMetadataObject().getSourceName().equalsIgnoreCase("headers"))) {
            // $NON-NLS-1$
            Clob headers = (Clob) arguments.get(5).getArgumentValue().getValue();
            if (headers != null) {
                parseHeader(httpHeaders, headers);
            }
        }
        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
        DataSource ds = null;
        if (payload instanceof String) {
            ds = new InputStreamFactory.ClobInputStreamFactory(new ClobImpl((String) payload));
        } else if (payload instanceof SQLXML) {
            ds = new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML) payload);
        } else if (payload instanceof Clob) {
            ds = new InputStreamFactory.ClobInputStreamFactory((Clob) payload);
        } else if (payload instanceof Blob) {
            ds = new InputStreamFactory.BlobInputStreamFactory((Blob) payload);
        }
        this.returnValue = dispatch.invoke(ds);
        Map<String, Object> rc = dispatch.getResponseContext();
        this.responseCode = (Integer) rc.get(WSConnection.STATUS_CODE);
        if (this.useResponseContext) {
            // it's presumed that the caller will handle the response codes
            this.responseContext = rc;
        } else {
            // TODO: may need to add logic around some 200/300 codes - cxf should at least be logging this
            if (this.responseCode >= 400) {
                String message = conn.getStatusMessage(this.responseCode);
                throw new TranslatorException(WSExecutionFactory.Event.TEIID15005, WSExecutionFactory.UTIL.gs(WSExecutionFactory.Event.TEIID15005, this.responseCode, message));
            }
        }
    } catch (WebServiceException e) {
        throw new TranslatorException(e);
    } catch (ParseException e) {
        throw new TranslatorException(e);
    } catch (IOException e) {
        throw new TranslatorException(e);
    } catch (SQLException e) {
        throw new TranslatorException(e);
    }
}
Also used : Blob(java.sql.Blob) Argument(org.teiid.language.Argument) WebServiceException(javax.xml.ws.WebServiceException) SQLException(java.sql.SQLException) IOException(java.io.IOException) InputStreamFactory(org.teiid.core.types.InputStreamFactory) DataSource(javax.activation.DataSource) SQLXML(java.sql.SQLXML) List(java.util.List) TranslatorException(org.teiid.translator.TranslatorException) ParseException(org.json.simple.parser.ParseException) Clob(java.sql.Clob) HashMap(java.util.HashMap) Map(java.util.Map) ClobImpl(org.teiid.core.types.ClobImpl)

Example 12 with Argument

use of org.teiid.language.Argument in project teiid by teiid.

the class WSWSDLProcedureExecution method execute.

public void execute() throws TranslatorException {
    List<Argument> arguments = this.procedure.getArguments();
    XMLType docObject = (XMLType) arguments.get(0).getArgumentValue().getValue();
    StAXSource source = null;
    try {
        source = convertToSource(docObject);
        Dispatch<StAXSource> dispatch = conn.createDispatch(StAXSource.class, executionFactory.getDefaultServiceMode());
        String operation = this.procedure.getProcedureName();
        if (this.procedure.getMetadataObject() != null && this.procedure.getMetadataObject().getNameInSource() != null) {
            operation = this.procedure.getMetadataObject().getNameInSource();
        }
        QName opQName = new QName(conn.getServiceQName().getNamespaceURI(), operation);
        dispatch.getRequestContext().put(MessageContext.WSDL_OPERATION, opQName);
        if (source == null) {
            // JBoss Native DispatchImpl throws exception when the source is null
            // $NON-NLS-1$
            source = new StAXSource(XMLType.getXmlInputFactory().createXMLEventReader(new StringReader("<none/>")));
        }
        this.returnValue = dispatch.invoke(source);
    } catch (SQLException e) {
        throw new TranslatorException(e);
    } catch (WebServiceException e) {
        throw new TranslatorException(e);
    } catch (XMLStreamException e) {
        throw new TranslatorException(e);
    } catch (IOException e) {
        throw new TranslatorException(e);
    } finally {
        Util.closeSource(source);
    }
}
Also used : Argument(org.teiid.language.Argument) WebServiceException(javax.xml.ws.WebServiceException) SQLException(java.sql.SQLException) QName(javax.xml.namespace.QName) StAXSource(javax.xml.transform.stax.StAXSource) IOException(java.io.IOException) XMLType(org.teiid.core.types.XMLType) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) TranslatorException(org.teiid.translator.TranslatorException)

Example 13 with Argument

use of org.teiid.language.Argument in project teiid by teiid.

the class BaseQueryExecution method buildInvokeHTTP.

protected BinaryWSProcedureExecution buildInvokeHTTP(String method, String uri, Object payload, Map<String, List<String>> headers) throws TranslatorException {
    if (LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL)) {
        try {
            LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Source-URL=", // $NON-NLS-1$ //$NON-NLS-2$
            URLDecoder.decode(uri, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
    }
    List<Argument> parameters = new ArrayList<Argument>();
    parameters.add(new Argument(Direction.IN, new Literal(method, TypeFacility.RUNTIME_TYPES.STRING), null));
    parameters.add(new Argument(Direction.IN, new Literal(payload, TypeFacility.RUNTIME_TYPES.STRING), null));
    parameters.add(new Argument(Direction.IN, new Literal(uri, TypeFacility.RUNTIME_TYPES.STRING), null));
    parameters.add(new Argument(Direction.IN, new Literal(true, TypeFacility.RUNTIME_TYPES.BOOLEAN), null));
    // the engine currently always associates out params at resolve time even if the
    // values are not directly read by the call
    parameters.add(new Argument(Direction.OUT, TypeFacility.RUNTIME_TYPES.STRING, null));
    Call call = this.translator.getLanguageFactory().createCall("invokeHttp", parameters, null);
    BinaryWSProcedureExecution execution = new BinaryWSProcedureExecution(call, this.metadata, this.executionContext, null, this.connection);
    execution.setUseResponseContext(true);
    execution.setCustomHeaders(headers);
    return execution;
}
Also used : Call(org.teiid.language.Call) Argument(org.teiid.language.Argument) Literal(org.teiid.language.Literal) BinaryWSProcedureExecution(org.teiid.translator.ws.BinaryWSProcedureExecution) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 14 with Argument

use of org.teiid.language.Argument in project teiid by teiid.

the class SwaggerProcedureExecution method buildWSExecution.

private BinaryWSProcedureExecution buildWSExecution(Call obj) throws TranslatorException {
    Procedure procedure = obj.getMetadataObject();
    String uri = procedure.getProperty(RestMetadataExtension.URI, false);
    String method = procedure.getProperty(RestMetadataExtension.METHOD, false);
    StringBuilder queryParameters = new StringBuilder();
    StringBuilder formParameters = new StringBuilder();
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    Object payload = null;
    // body payload document
    SwaggerBodyInputDocument input = null;
    final List<Argument> params = obj.getArguments();
    if (params != null && params.size() != 0) {
        Argument param = null;
        for (int i = 0; i < params.size(); i++) {
            param = params.get(i);
            ProcedureParameter metadata = param.getMetadataObject();
            String argName = WSConnection.Util.httpURLEncode(param.getMetadataObject().getName());
            if (param.getDirection() == Direction.IN || param.getDirection() == Direction.INOUT) {
                String in = metadata.getProperty(RestMetadataExtension.PARAMETER_TYPE, false);
                if (in.equalsIgnoreCase(RestMetadataExtension.ParameterType.QUERY.name())) {
                    if (queryParameters.length() != 0) {
                        // $NON-NLS-1$
                        queryParameters.append("&");
                    }
                    Object value = param.getExpression();
                    if (value instanceof Array) {
                        addArgumentValue(argName, (Array) value, metadata.getProperty(SwaggerMetadataProcessor.COLLECION_FORMAT, false), queryParameters);
                    } else {
                        String argValue = getURLValue((Literal) value);
                        queryParameters.append(argName);
                        queryParameters.append(Tokens.EQ);
                        queryParameters.append(argValue);
                    }
                } else if (in.equalsIgnoreCase(RestMetadataExtension.ParameterType.PATH.name())) {
                    String argValue = getURLValue(param.getArgumentValue());
                    // $NON-NLS-1$ //$NON-NLS-2$
                    String regex = "\\{" + argName + "\\}";
                    uri = uri.replaceAll(regex, argValue);
                } else if (in.equalsIgnoreCase(RestMetadataExtension.ParameterType.FORM.name()) || in.equalsIgnoreCase(RestMetadataExtension.ParameterType.FORMDATA.name())) {
                    if (formParameters.length() != 0) {
                        // $NON-NLS-1$
                        formParameters.append("&");
                    }
                    Object value = param.getExpression();
                    if (value instanceof Array) {
                        addArgumentValue(argName, (Array) value, metadata.getProperty(SwaggerMetadataProcessor.COLLECION_FORMAT, false), formParameters);
                    } else {
                        formParameters.append(argName);
                        formParameters.append(Tokens.EQ);
                        formParameters.append(getURLValue((Literal) value));
                    }
                } else if (in.equalsIgnoreCase(RestMetadataExtension.ParameterType.BODY.name())) {
                    if (input == null) {
                        input = new SwaggerBodyInputDocument();
                    }
                    Object expr = param.getExpression();
                    if (expr instanceof Literal) {
                        expr = ((Literal) expr).getValue();
                    }
                    input.addArgument(param.getMetadataObject(), expr);
                } else if (in.equalsIgnoreCase(RestMetadataExtension.ParameterType.HEADER.name())) {
                    String argValue = param.getArgumentValue().getValue().toString();
                    headers.put(argName, Arrays.asList(argValue));
                }
            } else {
                throw new TranslatorException("Not supported parameter");
            }
        }
    }
    String consumes = procedure.getProperty(RestMetadataExtension.CONSUMES, false);
    if (consumes == null) {
        consumes = "application/json";
    }
    if (input != null) {
        try {
            SwaggerSerializer serializer = getSerializer(consumes);
            InputStream oos = serializer.serialize(input);
            payload = ObjectConverterUtil.convertToString(oos);
        } catch (IOException e) {
            throw new TranslatorException(e);
        }
    }
    if (payload == null && formParameters.length() > 0) {
        payload = formParameters.toString();
    }
    headers.put("Content-Type", Arrays.asList(consumes));
    String produces = procedure.getProperty(RestMetadataExtension.PRODUCES, false);
    if (produces == null) {
        produces = "application/json";
    }
    headers.put("Accept", Arrays.asList(produces));
    if (queryParameters.length() > 0) {
        uri = uri + "?" + queryParameters;
    }
    return buildInvokeHTTP(method, uri, payload, headers);
}
Also used : ProcedureParameter(org.teiid.metadata.ProcedureParameter) Argument(org.teiid.language.Argument) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InputStream(java.io.InputStream) IOException(java.io.IOException) Array(org.teiid.language.Array) Literal(org.teiid.language.Literal) Procedure(org.teiid.metadata.Procedure) List(java.util.List) TranslatorException(org.teiid.translator.TranslatorException)

Example 15 with Argument

use of org.teiid.language.Argument in project teiid by teiid.

the class MongoDBDirectQueryExecution method execute.

@Override
public void execute() throws TranslatorException {
    StringBuilder buffer = new StringBuilder();
    SQLStringVisitor.parseNativeQueryParts(query, arguments, buffer, new SQLStringVisitor.Substitutor() {

        @Override
        public void substitute(Argument arg, StringBuilder builder, int index) {
            Literal argumentValue = arg.getArgumentValue();
            builder.append(argumentValue.getValue());
        }
    });
    // $NON-NLS-1$
    StringTokenizer st = new StringTokenizer(buffer.toString(), ";");
    String collectionName = st.nextToken();
    // $NON-NLS-1$
    boolean shellOperation = collectionName.equalsIgnoreCase("$ShellCmd");
    String shellOperationName = null;
    if (shellOperation) {
        collectionName = st.nextToken();
        shellOperationName = st.nextToken();
    }
    DBCollection collection = this.mongoDB.getCollection(collectionName);
    if (collection == null) {
        throw new TranslatorException(MongoDBPlugin.Event.TEIID18020, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18020, collectionName));
    }
    if (shellOperation) {
        ArrayList<Object> operations = new ArrayList<Object>();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.startsWith("{")) {
                // $NON-NLS-1$
                operations.add(JSON.parse(token));
            } else {
                operations.add(token);
            }
        }
        try {
            ReflectionHelper helper = new ReflectionHelper(DBCollection.class);
            Method method = helper.findBestMethodOnTarget(shellOperationName, operations.toArray(new Object[operations.size()]));
            Object result = method.invoke(collection, operations.toArray(new Object[operations.size()]));
            if (result instanceof Cursor) {
                this.results = (Cursor) result;
            } else if (result instanceof WriteResult) {
                WriteResult wr = (WriteResult) result;
                if (!wr.wasAcknowledged()) {
                    // throw error for unacknowledged write
                    throw new TranslatorException(wr.toString());
                }
            }
        } catch (NoSuchMethodException e) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString()));
        } catch (SecurityException e) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString()));
        } catch (IllegalAccessException e) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString()));
        } catch (IllegalArgumentException e) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString()));
        } catch (InvocationTargetException e) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e.getTargetException(), MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString()));
        }
    } else {
        ArrayList<DBObject> operations = new ArrayList<DBObject>();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            operations.add((DBObject) JSON.parse(token));
        }
        if (operations.isEmpty()) {
            throw new TranslatorException(MongoDBPlugin.Event.TEIID18021, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18021, collectionName));
        }
        this.results = collection.aggregate(operations, this.executionFactory.getOptions(this.executionContext.getBatchSize()));
    }
}
Also used : SQLStringVisitor(org.teiid.language.visitor.SQLStringVisitor) Argument(org.teiid.language.Argument) ArrayList(java.util.ArrayList) Cursor(com.mongodb.Cursor) DBObject(com.mongodb.DBObject) DBCollection(com.mongodb.DBCollection) Literal(org.teiid.language.Literal) ReflectionHelper(org.teiid.core.util.ReflectionHelper) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) StringTokenizer(java.util.StringTokenizer) WriteResult(com.mongodb.WriteResult) TranslatorException(org.teiid.translator.TranslatorException) DBObject(com.mongodb.DBObject)

Aggregations

Argument (org.teiid.language.Argument)27 TranslatorException (org.teiid.translator.TranslatorException)13 Literal (org.teiid.language.Literal)12 ArrayList (java.util.ArrayList)9 Call (org.teiid.language.Call)9 SQLException (java.sql.SQLException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 Test (org.junit.Test)4 BinaryWSProcedureExecution (org.teiid.translator.ws.BinaryWSProcedureExecution)4 DBCollection (com.mongodb.DBCollection)3 IOException (java.io.IOException)3 Timestamp (java.sql.Timestamp)3 HashMap (java.util.HashMap)3 StringTokenizer (java.util.StringTokenizer)3 ResourceException (javax.resource.ResourceException)3 DB (com.mongodb.DB)2 DBObject (com.mongodb.DBObject)2 SObject (com.sforce.soap.partner.sobject.SObject)2 XmlObject (com.sforce.ws.bind.XmlObject)2