使用云平台的 destination 服务消费 Internet 上的 OData service

举报
汪子熙 发表于 2021/10/24 21:46:16 2021/10/24
【摘要】 通过SAP云平台上的destination我们可以消费Internet上的OData service或者其他通过HTTP方式暴露出来的服务。创建一个新的destination:维护如下属性:点击Check Connection确保该destination正常工作:在WebIDE里新建一个Fiori Worklist Application:从Service url选择之前创建好的destin...

通过SAP云平台上的destination我们可以消费Internet上的OData service或者其他通过HTTP方式暴露出来的服务。

创建一个新的destination:

维护如下属性:

点击Check Connection确保该destination正常工作:

在WebIDE里新建一个Fiori Worklist Application:

从Service url选择之前创建好的destination:

在Object Collection里选择Alphabetical_list_of_products,Object Collection ID选择Product ID:

Fiori 应用创建成功之后,从右键菜单里选择Run->Run As->Web Application:

这样就实现了从SAP云平台消费Internet上的OData service的需求。

ABAP和Java的destination和JNDI

Netweaver里使用事务码SM59创建Destination:

Java

新建一个destination:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B3nrP4Tg-1635083096529)(https://upload-images.jianshu.io/upload_images/2085791-0b955d4f581ce6bc.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]

测试代码:


try {
            Context ctx = new InitialContext();
            ConnectivityConfiguration configuration = (ConnectivityConfiguration) ctx.lookup("java:comp/env/connectivityConfiguration");

            DestinationConfiguration destConfiguration = configuration.getConfiguration(destinationName);

            if (destConfiguration == null) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        String.format("Destination %s is not found. Hint:"
                                + " Make sure to have the destination configured.", destinationName));
                return;
            }

            // Get the destination URL
            String value = destConfiguration.getProperty("URL");
            URL url = new URL(value + "xml?origins=Walldorf&destinations=Paris");

            String proxyType = destConfiguration.getProperty("ProxyType");
            Proxy proxy = getProxy(proxyType);

            urlConnection = (HttpURLConnection) url.openConnection(proxy);

            injectHeader(urlConnection, proxyType);

            // Copy content from the incoming response to the outgoing response
            InputStream instream = urlConnection.getInputStream();
            OutputStream outstream = response.getOutputStream();
            copyStream(instream, outstream);
        } catch (Exception e) {
            // Connectivity operation failed
            String errorMessage = "Connectivity operation failed with reason: "
                    + e.getMessage()
                    + ". See "
                    + "logs for details. Hint: Make sure to have an HTTP proxy configured in your "
                    + "local environment in case your environment uses "
                    + "an HTTP proxy for the outbound Internet "
                    + "communication.";
            LOGGER.error("Connectivity operation failed", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    errorMessage);
        }

通过JNDI获得destination配置的url:

以Internet Service http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Walldorf&destinations=Berlin为例,

在浏览器里访问这个url,得到输出:从Walldorf到Berlin的距离。

如何让一个部署到SAP云平台的Java应用也能访问到该internet service呢?

首先在SAP云平台里创建一个destination,维护service的end point:

在Java代码里使用SAP云平台里创建的destination:

然后使用JNDI service读取destination里配置的url:

部署到SAP云平台之后,在Eclipse里看到preview结果:

SAP云平台Cockpit显示如下:

浏览器访问如下:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <!-- Main sample servlet mapped to / so that the integration test harness can detect readiness (generic for all samples) -->
    <servlet>
        <servlet-name>ConnectivityServlet</servlet-name>
        <servlet-class>com.sap.cloud.sample.connectivity.ConnectivityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ConnectivityServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Declare the JNDI lookup of destination -->
    <resource-ref>
    <res-ref-name>connectivityConfiguration</res-ref-name>
    <res-type>com.sap.core.connectivity.api.configuration.ConnectivityConfiguration</res-type>
    </resource-ref>
</web-app>
package com.sap.cloud.sample.connectivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sap.cloud.account.TenantContext;
import com.sap.core.connectivity.api.configuration.ConnectivityConfiguration;
import com.sap.core.connectivity.api.configuration.DestinationConfiguration;

public class ConnectivityServlet extends HttpServlet {
    @Resource
    private TenantContext  tenantContext;

    private static final long serialVersionUID = 1L;
    private static final int COPY_CONTENT_BUFFER_SIZE = 1024;
    private static final Logger LOGGER = LoggerFactory.getLogger(ConnectivityServlet.class);

    private static final String ON_PREMISE_PROXY = "OnPremise";

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpURLConnection urlConnection = null;
        String destinationName = request.getParameter("destname");

        if (destinationName == null) {
            destinationName = "google_map";
        }
        
        try {
            Context ctx = new InitialContext();
            ConnectivityConfiguration configuration = (ConnectivityConfiguration) ctx.lookup("java:comp/env/connectivityConfiguration");

            DestinationConfiguration destConfiguration = configuration.getConfiguration(destinationName);

            if (destConfiguration == null) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        String.format("Destination %s is not found. Hint:"
                                + " Make sure to have the destination configured.", destinationName));
                return;
            }

            String value = destConfiguration.getProperty("URL");
            URL url = new URL(value + "xml?origins=Walldorf&destinations=Paris");

            String proxyType = destConfiguration.getProperty("ProxyType");
            Proxy proxy = getProxy(proxyType);

            urlConnection = (HttpURLConnection) url.openConnection(proxy);

            injectHeader(urlConnection, proxyType);

            InputStream instream = urlConnection.getInputStream();
            OutputStream outstream = response.getOutputStream();
            copyStream(instream, outstream);
        } catch (Exception e) {
            String errorMessage = "Connectivity operation failed with reason: "
                    + e.getMessage()
                    + ". See "
                    + "logs for details. Hint: Make sure to have an HTTP proxy configured in your "
                    + "local environment in case your environment uses "
                    + "an HTTP proxy for the outbound Internet "
                    + "communication.";
            LOGGER.error("Connectivity operation failed", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    errorMessage);
        }
    }

    private Proxy getProxy(String proxyType) {
        Proxy proxy = Proxy.NO_PROXY;
        String proxyHost = null;
        String proxyPort = null;

        if (ON_PREMISE_PROXY.equals(proxyType)) {
            // Get proxy for on-premise destinations
            proxyHost = System.getenv("HC_OP_HTTP_PROXY_HOST");
            proxyPort = System.getenv("HC_OP_HTTP_PROXY_PORT");
        } else {
            // Get proxy for internet destinations
            proxyHost = System.getProperty("https.proxyHost");
            proxyPort = System.getProperty("https.proxyPort");
        }

        if (proxyPort != null && proxyHost != null) {
            int proxyPortNumber = Integer.parseInt(proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPortNumber));
        }

        return proxy;
    }

    private void injectHeader(HttpURLConnection urlConnection, String proxyType) {
        if (ON_PREMISE_PROXY.equals(proxyType)) {
            // Insert header for on-premise connectivity with the consumer account name
            urlConnection.setRequestProperty("SAP-Connectivity-ConsumerAccount",
                    tenantContext.getTenant().getAccount().getId());
        }
    }

    private void copyStream(InputStream inStream, OutputStream outStream) throws IOException {
        byte[] buffer = new byte[COPY_CONTENT_BUFFER_SIZE];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
    }
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。