Skip to content

Http outbound #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,17 @@
*/
package org.springframework.sbm.mule.actions.javadsl.translators.http;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.mulesoft.schema.mule.http.RequestConfigType;
import org.mulesoft.schema.mule.http.RequestType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.sbm.mule.actions.javadsl.translators.DslSnippet;
import org.springframework.sbm.mule.actions.javadsl.translators.MuleComponentToSpringIntegrationDslTranslator;
import org.springframework.sbm.mule.api.toplevel.configuration.ConfigurationTypeAdapter;
import org.springframework.sbm.mule.api.toplevel.configuration.MuleConfigurations;
import org.springframework.stereotype.Component;

import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.*;


/**
* Translator for {@code <http:request> } elements.spring integration
Expand All @@ -46,59 +37,61 @@
@Component
public class HttpRequestTranslator implements MuleComponentToSpringIntegrationDslTranslator<RequestType> {

@Autowired
private Configuration configuration;

@Override
public Class getSupportedMuleType() {
return RequestType.class;
}

private static final String template = " .headerFilter(\"accept-encoding\", false)\n" +
" .handle(\n" +
" Http.outboundGateway(\"$PROTOCOL://$HOST:$PORT$PATH\")\n" +
" .httpMethod(HttpMethod.$METHOD)\n" +
" //FIXME: Use appropriate response class type here instead of String.class\n" +
" .expectedResponseType(String.class)\n" +
" )";

@Override
public DslSnippet translate(RequestType component,
QName name,
MuleConfigurations muleConfigurations,
String flowName) {

RequestConfigType config = getRequestConfiguration(component, muleConfigurations);
return new DslSnippet(
template
.replace("$PATH", emptyStringIfNull(component.getPath()))
.replace("$METHOD", defaultToValueIfNull(component.getMethod(), "GET"))
.replace("$HOST", emptyStringIfNull(config.getHost()))
.replace("$PORT", emptyStringIfNull(config.getPort()))
.replace("$PROTOCOL", defaultToValueIfNull(config.getProtocol(), "http").toLowerCase())
,
Set.of("org.springframework.http.HttpMethod")
);
}

private RequestConfigType getRequestConfiguration(RequestType component, MuleConfigurations muleConfigurations) {
RequestConfigType emptyRequestConfig = new RequestConfigType();

ConfigurationTypeAdapter<RequestConfigType> configurationTypeAdapter =
muleConfigurations.getConfigurations().get(component.getConfigRef());

String templateStr = "return IntegrationFlows\n" +
" .from\n" +
" (\n" +
" Http.inboundChannelAdapter(\"${host}<#if port?has_content>:${port}</#if>/${basePath}\")\n" +
" .requestMapping(m -> m.methods(HttpMethod.GET))\n" +
"<#if responseTimeout?has_content>" +
" .replyTimeout(${responseTimeout})\n" +
"</#if>" +
" )\n" +
" .channel(INBOUND_DEMO_CHANNEL)\n" +
" .get();";

try {
Map<String, Object> data = new HashMap<>();

// TODO: requires access to config, e.g. muleMigrationContext.getConfigRef("...")
String configRef = component.getConfigRef();
Optional<? extends ConfigurationTypeAdapter> configurationTypeAdapter = muleConfigurations.find(configRef);
if(configurationTypeAdapter.isPresent()) {
RequestConfigType cast = (RequestConfigType) configurationTypeAdapter.get().getMuleConfiguration();
data.put("host", cast.getHost());
data.put("port", cast.getPort());
}


data.put("basePath", component.getPath());
data.put("method", component.getMethod());
data.put("responseTimeout", component.getResponseTimeout());
Template t = new Template("name", new StringReader(templateStr), configuration);
StringWriter stringWriter = new StringWriter();
t.process(data,
stringWriter);
return new DslSnippet(stringWriter.toString(), Collections.emptySet());
} catch (IOException | TemplateException e) {
e.printStackTrace();
if (configurationTypeAdapter == null) {

return emptyRequestConfig;
}

RequestConfigType requestConfig = configurationTypeAdapter
.getMuleConfiguration();

return requestConfig != null ? requestConfig : emptyRequestConfig;
}

private String defaultToValueIfNull(String originalValue, String defaultValue) {

return originalValue == null ? defaultValue : originalValue;
}

return null;
private String emptyStringIfNull(String value) {
return value == null ? "" : value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ public Map<String, ConfigurationTypeAdapter<?>> extractAllConfigurations(List<Mu

public static boolean isConfigType(JAXBElement jaxbElement) {
Class<?> aClass = jaxbElement.getValue().getClass();
Set<Class> configTypes = Set.of(RequestConfigType.class, ConfigurationType.class, AbstractConnectorType.class, ListenerConfigType.class);
Set<Class> configTypes = Set.of(RequestConfigType.class,
ConfigurationType.class,
AbstractConnectorType.class,
ListenerConfigType.class
);
return configTypes.stream()
.anyMatch(ct -> ct.isAssignableFrom(aClass));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import org.springframework.sbm.mule.actions.javadsl.translators.dwl.DwlTransformTranslator;
import org.springframework.sbm.mule.actions.javadsl.translators.http.HttpListenerConfigTypeAdapter;
import org.springframework.sbm.mule.actions.javadsl.translators.http.HttpListenerTranslator;
import org.springframework.sbm.mule.actions.javadsl.translators.http.HttpRequestTranslator;
import org.springframework.sbm.mule.actions.javadsl.translators.http.RequestConfigTypeAdapter;
import org.springframework.sbm.mule.actions.javadsl.translators.logging.LoggingTranslator;
import org.springframework.sbm.mule.actions.javadsl.translators.wmq.WmqConnectorTypeAdapter;
import org.springframework.sbm.mule.actions.javadsl.translators.wmq.WmqInboundEndpointTranslator;
Expand Down Expand Up @@ -73,7 +75,8 @@ public void setup() {
new TransformerTranslator(),
new WmqOutboundEndpointTranslator(),
new WmqInboundEndpointTranslator(),
new DwlTransformTranslator()
new DwlTransformTranslator(),
new HttpRequestTranslator()
);
List<TopLevelElementFactory> topLevelTypeFactories = List.of(
new FlowTopLevelElementFactory(translators),
Expand All @@ -84,7 +87,8 @@ public void setup() {
List.of(
new AmqpConfigTypeAdapter(),
new HttpListenerConfigTypeAdapter(),
new WmqConnectorTypeAdapter()
new WmqConnectorTypeAdapter(),
new RequestConfigTypeAdapter()
)
);
MuleMigrationContextFactory muleMigrationContextFactory = new MuleMigrationContextFactory(new MuleConfigurationsExtractor(configurationTypeAdapterFactory));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright 2021 - 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.sbm.mule.actions;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class MuleToJavaDSLHttpOutbound extends JavaDSLActionBaseTest {
private static final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<mule xmlns:json=\"http://www.mulesoft.org/schema/mule/json\" xmlns:http=\"http://www.mulesoft.org/schema/mule/http\" xmlns=\"http://www.mulesoft.org/schema/mule/core\" xmlns:doc=\"http://www.mulesoft.org/schema/mule/documentation\"\n" +
" xmlns:spring=\"http://www.springframework.org/schema/beans\" \n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd\n" +
"http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd\n" +
"http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd\n" +
"http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd\">\n" +
" <http:listener-config name=\"HTTP_Listener_Configuration1\" host=\"0.0.0.0\" port=\"9082\" doc:name=\"HTTP Listener Configuration\"/>\n" +
" <http:request-config name=\"HTTP_Request_Configuration\" host=\"catfact.ninja\" port=\"443\" doc:name=\"HTTP Request Configuration\" protocol=\"HTTPS\"/>\n" +
" <flow name=\"httpFlow\">\n" +
" <http:listener config-ref=\"HTTP_Listener_Configuration1\" path=\"/gimme-a-cat-fact\" doc:name=\"HTTP\"/>\n" +
" <http:request config-ref=\"HTTP_Request_Configuration\" path=\"/fact\" method=\"GET\" doc:name=\"HTTP\"/>\n" +
" <set-payload doc:name=\"Set Payload\" value=\"#[payload]\"/>\n" +
" </flow>\n" +
"</mule>";

@Test
public void supportForHttpOutboundRequest() {
addXMLFileToResource(xml);
runAction();
assertThat(projectContext.getProjectJavaSources().list()).hasSize(1);
assertThat(projectContext.getProjectJavaSources().list().get(0).print())
.isEqualTo("package com.example.javadsl;\n" +
"import org.springframework.context.annotation.Bean;\n" +
"import org.springframework.context.annotation.Configuration;\n" +
"import org.springframework.http.HttpMethod;\n" +
"import org.springframework.integration.dsl.IntegrationFlow;\n" +
"import org.springframework.integration.dsl.IntegrationFlows;\n" +
"import org.springframework.integration.http.dsl.Http;\n" +
"\n" +
"@Configuration\n" +
"public class FlowConfigurations {\n" +
" @Bean\n" +
" IntegrationFlow httpFlow() {\n" +
" return IntegrationFlows.from(Http.inboundChannelAdapter(\"/gimme-a-cat-fact\")).handle((p, h) -> p)\n" +
" .headerFilter(\"accept-encoding\", false)\n" +
" .handle(\n" +
" Http.outboundGateway(\"https://catfact.ninja:443/fact\")\n" +
" .httpMethod(HttpMethod.GET)\n" +
" //FIXME: Use appropriate response class type here instead of String.class\n" +
" .expectedResponseType(String.class)\n" +
" )\n" +
" .handle((p, h) -> \"#[payload]\")\n" +
" .get();\n" +
" }}");
}
}