INTSAMPLES-19 First Set of Sample Testing Techniques

This commit is contained in:
Gary Russell
2011-02-01 17:05:20 -05:00
parent f91e7227ed
commit bfb4f0c4aa
28 changed files with 1347 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2011 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
*
* http://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.integration.samples.testing.aggregator;
import java.util.List;
import org.springframework.integration.annotation.Aggregator;
/**
*
* Aggregates messages into a comma-delimited list.
*
* @author Gary Russell
* @since 2.0.2
*
*/
public class CommaDelimitedAggregator {
@Aggregator
public String aggregate(List<String> bits) {
StringBuilder sb = new StringBuilder();
for (String bit : bits) {
sb.append(bit).append(",");
}
// remove final comma, if any
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
if (sb.length() < 1) {
return null;
}
return sb.toString();
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2011 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
*
* http://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.integration.samples.testing.externalgateway;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Gary Russell
* @since 2.0.2
*
*/
public class Main {
public static void main(String[] args) throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"META-INF/spring/integration/04-externalgateway/*.xml");
System.out.println("Please enter zip");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String zip = console.readLine().trim();
WeatherAndTraffic weatherAndTraffic = context.getBean("wat", WeatherAndTraffic.class);
String[] result = weatherAndTraffic.getByZip(zip);
System.out.println(result[0] + "\r\n" + result[1] + "\r\n");
context.close();
System.exit(0);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2010 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
*
* http://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.integration.samples.testing.externalgateway;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since SpringOne2GX - 2010, Chicago
*/
public class Traffic {
private Map<String, String> incidents = new HashMap<String, String>();
public void addIncident(String title, String description){
incidents.put(title, description);
}
public Map<String, String> getIncidents(){
return incidents;
}
public String toString(){
return "Traffic: {" + incidents.keySet().toString() + "}";
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2010 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
*
* http://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.integration.samples.testing.externalgateway;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
*
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since SpringOne2GX - 2010, Chicago
*/
public class TrafficHttpConverter implements HttpMessageConverter<Traffic> {
private List<MediaType> supportedMediaTypes = Collections.emptyList();
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return Traffic.class.equals(clazz);
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return supportedMediaTypes;
}
@SuppressWarnings("unchecked")
@Override
public Traffic read(Class<? extends Traffic> clazz, HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
Traffic traffic = new Traffic();
try {
Document document =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputMessage.getBody());
XPathExpression titlesXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Title");
List<Node> titles = titlesXp.evaluateAsNodeList(document);
XPathExpression descXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Description");
List<Node> description = descXp.evaluateAsNodeList(document);
int counter = 0;
for (Node node : titles) {
traffic.addIncident(((Element)node).getTextContent(), ((Element)description.get(counter++)).getTextContent());
}
} catch (Exception e) {
throw new HttpMessageConversionException("Failed to convert response to: " + clazz, e);
}
return traffic;
}
@Override
public void write(Traffic t, MediaType contentType,
HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
// for now this converter is only used for converting response
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2010 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
*
* http://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.integration.samples.testing.externalgateway;
/**
*
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since SpringOne2GX - 2010, Chicago
*/
public class Weather {
private String city;
private String state;
private String temperature;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String toString(){
return description + " in " + city +
", " + state + "; Temperature " + temperature + "";
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2002-2011 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
*
* http://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.integration.samples.testing.externalgateway;
/**
* @author Gary Russell
* @since 2.0.2
*
*/
public interface WeatherAndTraffic {
public String[] getByZip(String zip);
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright 2010 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
*
* http://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.integration.samples.testing.externalgateway;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import org.springframework.xml.xpath.XPathExpressionFactory;
import org.w3c.dom.Document;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
/**
*
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since SpringOne2GX - 2010, Chicago
*/
public class WeatherMarshaller implements Marshaller, Unmarshaller, InitializingBean {
private Map<String, String> namespacePrefixes = new HashMap<String, String>();
private String xpathPrefix = "/p:GetCityWeatherByZIPResponse/p:GetCityWeatherByZIPResult/";
@Override
public Object unmarshal(Source source) throws IOException, XmlMappingException {
//this.writeXml(((DOMSource)source).getNode().getOwnerDocument());
DOMResult result = null;
try {
Transformer transformer = new TransformerFactoryImpl().newTransformer();
result = new DOMResult();
transformer.transform(source, result);
} catch (Exception e) {
throw new MarshallingFailureException("Failed to unmarshal SOAP Response", e);
}
Weather weather = new Weather();
String expression = xpathPrefix + "p:City";
String city = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
weather.setCity(city);
expression = xpathPrefix + "p:State";
String state = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
weather.setState(state);
expression = xpathPrefix + "p:Temperature";
String temperature = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
weather.setTemperature(temperature);
expression = xpathPrefix + "p:Description";
String description = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
weather.setDescription(description);
return weather;
}
@Override
public boolean supports(Class<?> clazz) {
System.out.println("Suppors");
return false;
}
@Override
public void marshal(Object zip, Result result) throws IOException,
XmlMappingException {
String xmlString = "<weat:GetCityWeatherByZIP xmlns:weat=\"http://ws.cdyne.com/WeatherWS/\">" +
" <weat:ZIP>" + zip + "</weat:ZIP>" +
"</weat:GetCityWeatherByZIP>";
try {
Transformer transformer = new TransformerFactoryImpl().newTransformer();
transformer.transform(new StringSource(xmlString), result);
} catch (Exception e) {
e.printStackTrace();
}
}
public static final void writeXml(Document document) {
Transformer transformer = createIndentingTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
try {
StringResult streamResult = new StringResult();
transformer.transform(new DOMSource(document), streamResult);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
public static final Transformer createIndentingTransformer() {
Transformer xformer;
try {
xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(2));
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
return xformer;
}
@Override
public void afterPropertiesSet() throws Exception {
namespacePrefixes.put("p", "http://ws.cdyne.com/WeatherWS/");
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2011 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
*
* http://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.integration.samples.testing.splitter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.integration.annotation.Splitter;
/**
* Splits a message containing a comma-delimited list into
* a list of strings. Empty elements are dropped.
*
* @author Gary Russell
* @since 2.0.2
*
*/
public class CommaDelimitedSplitter {
@Splitter
public List<String> split(String input) {
String[] splits = input.split(",");
List<String> list = new ArrayList<String>();
for (String split : splits) {
String trimmed = split.trim();
if (trimmed.length() > 0) {
list.add(trimmed);
}
}
return list;
}
}

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<channel id="inputChannel"/>
<chain input-channel="inputChannel"
output-channel="outputChannel">
<header-enricher>
<header name="myHeader" expression="payload.contains('ABC')"/>
</header-enricher>
<transformer expression="payload.toLowerCase()"/>
</chain>
<channel id="outputChannel"/>
</beans:beans>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<channel id="inputChannel"/>
<splitter input-channel="inputChannel"
output-channel="outputChannel">
<beans:bean class="org.springframework.integration.samples.testing.splitter.CommaDelimitedSplitter"/>
</splitter>
<channel id="outputChannel"/>
</beans:beans>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<channel id="inputChannel"/>
<splitter input-channel="inputChannel"
output-channel="upperChannel">
<beans:bean class="org.springframework.integration.samples.testing.splitter.CommaDelimitedSplitter"/>
</splitter>
<channel id="upperChannel"/>
<transformer input-channel="upperChannel"
output-channel="aggregationChannel"
expression="payload.toUpperCase()"/>
<channel id="aggregationChannel"/>
<aggregator input-channel="aggregationChannel"
output-channel="outputChannel">
<beans:bean class="org.springframework.integration.samples.testing.aggregator.CommaDelimitedAggregator"/>
</aggregator>
<channel id="outputChannel"/>
</beans:beans>

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<gateway id="wat"
service-interface="org.springframework.integration.samples.testing.externalgateway.WeatherAndTraffic"
default-request-channel="inputChannel"/>
<publish-subscribe-channel id="inputChannel"
apply-sequence="true"
task-executor="executor"/>
<bridge input-channel="inputChannel"
output-channel="trafficRequestChannel"/>
<bridge input-channel="inputChannel"
output-channel="weatherRequestChannel" />
<!-- Results -->
<bridge input-channel="trafficResponseChannel"
output-channel="toStringChannel"/>
<bridge input-channel="weatherResponseChannel"
output-channel="toStringChannel"/>
<channel id="toStringChannel"/>
<transformer input-channel="toStringChannel"
output-channel="aggregatorChannel"
expression="payload.toString()"/>
<channel id="aggregatorChannel" />
<aggregator input-channel="aggregatorChannel"
expression="#this.![payload].toArray()"/>
<task:executor id="executor" pool-size="10"/>
</beans:beans>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
xmlns:int-ws="http://www.springframework.org/schema/integration/ws"
xsi:schemaLocation="http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http-2.0.xsd
http://www.springframework.org/schema/integration/ws http://www.springframework.org/schema/integration/ws/spring-integration-ws-2.0.xsd
http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail-2.0.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<int-http:outbound-gateway id="trafficService"
url="http://local.yahooapis.com/MapsService/V1/trafficData?appid=YdnDemo&amp;zip={zipCode}"
request-channel="trafficRequestChannel"
reply-channel="trafficResponseChannel"
http-method="GET"
message-converters="trafficConverter"
expected-response-type="org.springframework.integration.samples.testing.externalgateway.Traffic">
<int-http:uri-variable name="zipCode" expression="payload"/>
</int-http:outbound-gateway>
<int-ws:header-enricher id="soapHeaderEnricher"
input-channel="weatherRequestChannel"
output-channel="weatherServiceChannel">
<int-ws:soap-action value="http://ws.cdyne.com/WeatherWS/GetCityWeatherByZIP" />
</int-ws:header-enricher>
<int:channel id="weatherServiceChannel" />
<int-ws:outbound-gateway id="weatherService"
request-channel="weatherServiceChannel"
reply-channel="weatherResponseChannel"
marshaller="marshaller"
unmarshaller="marshaller"
uri="http://ws.cdyne.com/WeatherWS/Weather.asmx"/>
<int:channel id="weatherResponseChannel"/>
<bean id="trafficConverter" class="org.springframework.integration.samples.testing.externalgateway.TrafficHttpConverter"/>
<bean id="marshaller" class="org.springframework.integration.samples.testing.externalgateway.WeatherMarshaller"/>
</beans>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %d %c{1} - %m%n" />
</layout>
</appender>
<!-- Loggers -->
<logger name="org.springframework">
<level value="warn" />
</logger>
<logger name="org.springframework.integration">
<level value="warn" />
</logger>
<logger name="org.springframework.integration.samples">
<level value="debug" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
</root>
</log4j:configuration>