Search in sources :

Example 61 with DataSource

use of javax.activation.DataSource 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 62 with DataSource

use of javax.activation.DataSource in project teiid by teiid.

the class TestWSTranslator method testStreaming.

@Test
public void testStreaming() throws Exception {
    WSExecutionFactory ef = new WSExecutionFactory();
    WSConnection mockConnection = Mockito.mock(WSConnection.class);
    MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
    ef.getMetadata(mf, mockConnection);
    Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
    assertEquals(7, p.getParameters().size());
    TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
    RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
    Dispatch<Object> mockDispatch = mockDispatch();
    DataSource mock = Mockito.mock(DataSource.class);
    ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]);
    Mockito.stub(mock.getInputStream()).toReturn(baos);
    Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(mock);
    Mockito.stub(mockConnection.createDispatch(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))).toReturn(mockDispatch);
    CommandBuilder cb = new CommandBuilder(tm);
    Call call = (Call) cb.getCommand("call invokeHttp('GET', null, null, true)");
    BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    pe.execute();
    List<?> result = pe.getOutputParameterValues();
    Blob b = (Blob) result.get(0);
    assertEquals(100, ObjectConverterUtil.convertToByteArray(b.getBinaryStream()).length);
    try {
        ObjectConverterUtil.convertToByteArray(b.getBinaryStream());
        fail();
    } catch (SQLException e) {
    // should only be able to read once
    }
}
Also used : WSConnection(org.teiid.translator.WSConnection) Call(org.teiid.language.Call) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) Blob(java.sql.Blob) SQLException(java.sql.SQLException) Properties(java.util.Properties) DataSource(javax.activation.DataSource) ExecutionContext(org.teiid.translator.ExecutionContext) RealMetadataFactory(org.teiid.query.unittest.RealMetadataFactory) MetadataFactory(org.teiid.metadata.MetadataFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) RuntimeMetadataImpl(org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl) Procedure(org.teiid.metadata.Procedure) CommandBuilder(org.teiid.cdk.CommandBuilder) Test(org.junit.Test)

Example 63 with DataSource

use of javax.activation.DataSource in project teiid by teiid.

the class TestWSTranslator method testPre81Procedure.

@Test
public void testPre81Procedure() throws Exception {
    WSExecutionFactory ef = new WSExecutionFactory();
    WSConnection mockConnection = Mockito.mock(WSConnection.class);
    MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
    ef.getMetadata(mf, mockConnection);
    Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
    assertEquals(7, p.getParameters().size());
    p.getParameters().remove(4);
    p.getParameters().remove(5);
    // designer treated the result as an out parameter
    p.getParameters().get(0).setType(Type.Out);
    p.getParameters().add(3, p.getParameters().remove(0));
    for (int i = 0; i < p.getParameters().size(); i++) {
        p.getParameters().get(i).setPosition(i + 1);
    }
    p = mf.getSchema().getProcedure("invoke");
    assertEquals(6, p.getParameters().size());
    p.getParameters().remove(5);
    // designer treated the result as an out parameter
    p.getParameters().get(0).setType(Type.Out);
    p.getParameters().add(p.getParameters().remove(0));
    for (int i = 0; i < p.getParameters().size(); i++) {
        p.getParameters().get(i).setPosition(i + 1);
    }
    TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
    RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
    Dispatch<Object> mockDispatch = mockDispatch();
    DataSource source = Mockito.mock(DataSource.class);
    Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(source);
    Mockito.stub(mockConnection.createDispatch(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))).toReturn(mockDispatch);
    CommandBuilder cb = new CommandBuilder(tm);
    Call call = (Call) cb.getCommand("call invokeHttp('GET', null, null)");
    BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    pe.execute();
    pe.getOutputParameterValues();
    mockConnection = Mockito.mock(WSConnection.class);
    mockDispatch = Mockito.mock(Dispatch.class);
    StAXSource ssource = Mockito.mock(StAXSource.class);
    Mockito.stub(mockDispatch.invoke(Mockito.any(StAXSource.class))).toReturn(ssource);
    Mockito.stub(mockConnection.createDispatch(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))).toReturn(mockDispatch);
    call = (Call) cb.getCommand("call invoke()");
    WSProcedureExecution wpe = new WSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    wpe.execute();
    wpe.getOutputParameterValues();
}
Also used : WSConnection(org.teiid.translator.WSConnection) Call(org.teiid.language.Call) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) Dispatch(javax.xml.ws.Dispatch) StAXSource(javax.xml.transform.stax.StAXSource) Properties(java.util.Properties) DataSource(javax.activation.DataSource) ExecutionContext(org.teiid.translator.ExecutionContext) RealMetadataFactory(org.teiid.query.unittest.RealMetadataFactory) MetadataFactory(org.teiid.metadata.MetadataFactory) RuntimeMetadataImpl(org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl) Procedure(org.teiid.metadata.Procedure) CommandBuilder(org.teiid.cdk.CommandBuilder) Test(org.junit.Test)

Example 64 with DataSource

use of javax.activation.DataSource in project teiid by teiid.

the class TestSwaggerQueryExecution method helpProcedureExecute.

private ProcedureExecution helpProcedureExecute(String query, final String resultJson, String expectedURL, int responseCode, boolean decode, String expectedMethod, String expectedInput, Map<String, Object> userHeaders) throws Exception {
    userHeaders.put(MessageContext.HTTP_REQUEST_HEADERS, new HashMap<String, List<String>>());
    userHeaders.put(WSConnection.STATUS_CODE, new Integer(responseCode));
    userHeaders.put("Content-Type", Arrays.asList("application/json"));
    SwaggerExecutionFactory translator = new SwaggerExecutionFactory();
    translator.start();
    TranslationUtility utility = new TranslationUtility(TestSwaggerMetadataProcessor.getTransformationMetadata(TestSwaggerMetadataProcessor.petstoreMetadata(translator), translator));
    Command cmd = utility.parseCommand(query);
    ExecutionContext context = Mockito.mock(ExecutionContext.class);
    WSConnection connection = Mockito.mock(WSConnection.class);
    Dispatch<DataSource> dispatch = Mockito.mock(Dispatch.class);
    Mockito.stub(dispatch.getRequestContext()).toReturn(userHeaders);
    Mockito.stub(dispatch.getResponseContext()).toReturn(userHeaders);
    Mockito.stub(connection.createDispatch(Mockito.eq(HTTPBinding.HTTP_BINDING), Mockito.anyString(), Mockito.eq(DataSource.class), Mockito.eq(Mode.MESSAGE))).toReturn(dispatch);
    DataSource outputDS = new DataSource() {

        @Override
        public OutputStream getOutputStream() throws IOException {
            return new ByteArrayOutputStream();
        }

        @Override
        public String getName() {
            return "result";
        }

        @Override
        public InputStream getInputStream() throws IOException {
            ByteArrayInputStream in = new ByteArrayInputStream(resultJson.getBytes());
            return in;
        }

        @Override
        public String getContentType() {
            return "application/json";
        }
    };
    Mockito.stub(dispatch.invoke(Mockito.any(DataSource.class))).toReturn(outputDS);
    ProcedureExecution execution = translator.createProcedureExecution((Call) cmd, context, utility.createRuntimeMetadata(), connection);
    execution.execute();
    ArgumentCaptor<String> endpoint = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> binding = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<DataSource> input = ArgumentCaptor.forClass(DataSource.class);
    Mockito.verify(connection).createDispatch(binding.capture(), endpoint.capture(), Mockito.eq(DataSource.class), Mockito.eq(Mode.MESSAGE));
    Mockito.verify(dispatch).invoke(input.capture());
    assertEquals(expectedURL, decode ? URLDecoder.decode(endpoint.getValue(), "utf-8") : endpoint.getValue());
    assertEquals(expectedMethod, dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_METHOD));
    if (expectedInput != null) {
        assertEquals(expectedInput, ObjectConverterUtil.convertToString(input.getValue().getInputStream()));
    }
    return execution;
}
Also used : WSConnection(org.teiid.translator.WSConnection) TranslationUtility(org.teiid.cdk.api.TranslationUtility) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataSource(javax.activation.DataSource) ExecutionContext(org.teiid.translator.ExecutionContext) Command(org.teiid.language.Command) ByteArrayInputStream(java.io.ByteArrayInputStream) ProcedureExecution(org.teiid.translator.ProcedureExecution) List(java.util.List)

Example 65 with DataSource

use of javax.activation.DataSource in project acs-aem-commons by Adobe-Consulting-Services.

the class EmailServiceImplTest method testSendEmailAttachment.

@Test
public final void testSendEmailAttachment() throws Exception {
    final String expectedMessage = "This is just a message";
    final String expectedSenderName = "John Smith";
    final String expectedSenderEmailAddress = "john@smith.com";
    String attachment = "This is a attachment.";
    String attachmentName = "attachment.txt";
    // Subject is provided inside the HtmlTemplate directly
    final String expectedSubject = "Greetings";
    final Map<String, String> params = new HashMap<String, String>();
    params.put("message", expectedMessage);
    params.put("senderName", expectedSenderName);
    params.put("senderEmailAddress", expectedSenderEmailAddress);
    final String recipient = "upasanac@acs.com";
    Map<String, DataSource> attachments = new HashMap();
    attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain"));
    ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class);
    List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments, recipient);
    verify(messageGatewayHtmlEmail, times(1)).send(captor.capture());
    assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress());
    assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal());
    assertEquals(expectedSubject, captor.getValue().getSubject());
    assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString());
    Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer");
    getContainer.setAccessible(true);
    MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue());
    getContainer.setAccessible(false);
    assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString());
    // If email is sent to the recipient successfully, the response is an empty failureList
    assertTrue(failureList.isEmpty());
}
Also used : HashMap(java.util.HashMap) MimeMultipart(javax.mail.internet.MimeMultipart) HtmlEmail(org.apache.commons.mail.HtmlEmail) Method(java.lang.reflect.Method) ByteArrayDataSource(org.apache.commons.mail.ByteArrayDataSource) DataSource(javax.activation.DataSource) ByteArrayDataSource(org.apache.commons.mail.ByteArrayDataSource) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

DataSource (javax.activation.DataSource)196 DataHandler (javax.activation.DataHandler)114 FileDataSource (javax.activation.FileDataSource)60 MimeBodyPart (javax.mail.internet.MimeBodyPart)53 MimeMultipart (javax.mail.internet.MimeMultipart)48 MimeMessage (javax.mail.internet.MimeMessage)39 InputStream (java.io.InputStream)37 IOException (java.io.IOException)36 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 File (java.io.File)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)30 InternetAddress (javax.mail.internet.InternetAddress)27 Properties (java.util.Properties)26 MessagingException (javax.mail.MessagingException)25 Multipart (javax.mail.Multipart)24 Session (javax.mail.Session)21 BodyPart (javax.mail.BodyPart)19 ArrayList (java.util.ArrayList)16