Spring Integration出站门方式,包括动态URL,HTTP方法和不同的响应类型

时间:2018-05-30 09:49:14

标签: spring-integration spring-integration-http

我对Spring Integration有一点了解,到目前为止我已经使用了JMS和File出站适配器,现在我想介绍用于Spring REST支持的HTTP out bound适配器。到目前为止,我已经能够调用外部REST api,如下所示。

Spring Integration Config

<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.omg.PortableServer.Servant"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="java.nio.file.Paths"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
     <%@page import="java.sql.*" %>
    <%@page import ="java.util.Date" %>  
    <%@page import ="java.io.*" %>  
    <%@page import ="java.io.FileNotFoundException" %>  
    <%@page import ="java.io.IOException" %>  
    <%@page import ="java.util.Iterator" %>  
    <%@page import ="java.util.ArrayList" %> 
    <%@page import="org.apache.poi.hssf.usermodel.*" %>
    <%@page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>  
    <%@page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>  
    <%@page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>  
    <%@page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>  
    <%@page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
    <%@page import="org.apache.poi.ss.usermodel.Cell" %>
    <%@page import ="org.apache.poi.ss.usermodel.Row"%>
    <%@page import="org.apache.poi.ss.usermodel.Sheet" %>
    <%@page import="org.apache.poi.ss.usermodel.Workbook" %>
    <%@page import="com.oreilly.servlet.MultipartRequest" %>
    <%@page import="org.apache.poi.xssf.usermodel.*"%>
    <%@page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>
    <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>


     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
  <%

    try
    {
 ArrayList CellArrayListHolder=new ArrayList();
 Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.18.114.213:1831:godb","xe","se");
      String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
out.println(saveFile);
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

%>
<%

PreparedStatement psmnt = null;
FileInputStream fis;
File file1 = new File(saveFile);
FileInputStream file_inut=new FileInputStream(file1);
XSSFWorkbook workbook=new XSSFWorkbook(file_inut);
Sheet firstsheet=workbook.getSheetAt(0);
Iterator<Row> iterator=firstsheet.iterator();
int count=0;
while(iterator.hasNext())
{
   XSSFRow nextrow=(XSSFRow)iterator.next();
    ArrayList rowarraylist=new ArrayList();
    Iterator<Cell> cellIterator=nextrow.cellIterator();

    while(cellIterator.hasNext())
    {
        XSSFCell cell=(XSSFCell)cellIterator.next();
        rowarraylist.add(cell);
    }
    CellArrayListHolder.add(rowarraylist);
}
       out.println(CellArrayListHolder);
       ArrayList rowarraylist=null;
       PreparedStatement st=con.prepareStatement("insert into DYNAMIC_INSERT values(?)");

for(int i=1;i<CellArrayListHolder.size();i++)
{
    rowarraylist=(ArrayList)CellArrayListHolder.get(i);
     //st.setString(1, file_name);
    st.setString(1, rowarraylist.get(0).toString());
    //st.executeUpdate();
    count=st.executeUpdate();

}
if(count>0)
{
       out.println("<script type=\"text/javascript\">");
   out.println("alert('File added');");
      out.println("location='xlsUpload.html';");
   out.println("</script>");    
}
}
}
catch(Exception ex)
{
 out.println("<script type=\"text/javascript\">");
   out.println("alert('File not found');");
      out.println("location='xlsUpload.html';");
   out.println("</script>");    

}


  %>
    </body>
</html>

出站网关调用

<int-http:outbound-gateway id="outbound.gateway"
    request-channel="get.request.channel" url="https://jsonplaceholder.typicode.com/posts/1"
    http-method="GET" expected-response-type="com.cst.entity.Post"
    charset="UTF-8" reply-timeout="5000" reply-channel="reply.channel">
</int-http:outbound-gateway>

但是我想开发一个框架,开发人员可以使用任何方法调用任何REST URL,并期望不同类型的响应类型。我找到了一种通过引入

动态设置URL的方法
public void restTest() throws Exception{

    Message<?> message = MessageBuilder.withPayload().build();
    getRequestChannel.send(message);
    Message<?> receivedMsg = receivedChannel.receive();
    Post post = (Post) receivedMsg.getPayload();

    System.out.println("############## ServerMsg ##############");
    System.out.println(post.toString());
    System.out.println("############## Done! ##############");

}

<int-http:outbound-gateway id="outbound.gateway"
    request-channel="get.request.channel" url="{fhirurl}"
    http-method="GET" expected-response-type="com.bst.pages.crm.web.Post"
    charset="UTF-8" reply-timeout="5000" reply-channel="reply.channel">
</int-http:outbound-gateway>

然后我尝试使用上面的方法实现动态响应类型的动态HTTP方法,但它不起作用,看起来我们只能使用public void restTest() throws Exception{ FHIRInput input = new FHIRInput(); input.setUrl(url); Message<?> message = MessageBuilder.withPayload(input).build(); getRequestChannel.send(message); Message<?> receivedMsg = receivedChannel.receive(); Post post = (Post) receivedMsg.getPayload(); System.out.println("############## ServerMsg ##############"); System.out.println(post.toString()); System.out.println("############## Done! ##############"); } 处理URL。

什么是理想的解决方案。感谢您的帮助

谢谢, Keth

修改

按照以下注释后,我能够实现一个框架,开发人员可以根据有效负载内容调用动态URL。下面是我对HTTP出站适配器的配置。

<int-http:uri-variable/>

然而,我仍然在寻找一种将动态请求体作为POST参数传递的方法。由于我们使用有效载荷来携带URL,http方法和预期的响应类型我无法通过请求体。

1 个答案:

答案 0 :(得分:1)

不清楚你的意思

  

然后,我尝试使用上述方法实现动态响应类型的动态HTTP方法,但它不起作用,看起来我们只能使用site-deploy处理URL。

要处理多种响应类型,请将它们作为String(JSON)获取,然后使用transformer(s)转换为类型。

<强> EDIT1

响应类型和方法可以是表达式:

<xsl:choose>
    <xsl:when test="myNode = 'site-deploy'"><xsl:text>29</xsl:text></xsl:when>
    <xsl:when test="myNode = 'none'"><xsl:text>99</xsl:text></xsl:when>
    <xsl:otherwise><xsl:text>100</xsl:text></xsl:otherwise>
</xsl:choose>

<强>解决方案

我能够为一个简单的框架提供一个解决方案,我们可以让开发人员使用不同的HTTP方法和响应类型调用不同的其他URL。

这是Spring Integration的配置

<int-http:uri-variable/>

这是我用于调用上述集成系统的Java代码。

<xsd:attribute name="expected-response-type-expression" type="xsd:string">
    <xsd:annotation>
        <xsd:documentation>
            SpEL expression to determine the type for the expected response to which the response body should be converted
            The returned value of the expression could be an instance of java.lang.Class or
            java.lang.String representing a fully qualified class name.
            This attribute cannot be provided if expected-response-type has a value
        </xsd:documentation>
    </xsd:annotation>
</xsd:attribute>

<xsd:attribute name="http-method-expression" type="xsd:string">
    <xsd:annotation>
        <xsd:documentation>
            The SpEL expression to determine HTTP method, use when executing requests with this adapter,
            dynamically. This attribute cannot be provided if http-method has a value.
        </xsd:documentation>
    </xsd:annotation>
</xsd:attribute>