开发者社区> jerrywangsap> 正文

使用SAP云平台 + JNDI访问Internet Service

简介:
+关注继续查看

以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);
        }
    }
}

要获取更多Jerry的原创技术文章,请关注公众号"汪子熙"或者扫描下面二维码:

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
使用SAP portal service创建Fiori Launchpad
使用SAP portal service创建Fiori Launchpad
36 0
如何打破边界,接入各家云,使用阿里云的数据产品作游戏数据分析?
背景:       某某游戏公司的业务逻辑图,其实可以从中发现这基本上跟大多数的游戏公司一样,通过阿里云作数据分析,其他云作数据接入。原因在于阿里云的数据产品比较贴合使用习惯、全面丰富的良好产品体验。       但是,接入的通路问题,采集问题,甚至集成问题,都是困扰一大部分用户的。这篇文章,就是希望打开这方面的脑洞。细化到网络层面,
922 0
Spring JDBCTemplate使用JNDI数据源
xml配置: 1 3 4 5 6 7 在weblogic/jboss中配置好JNDI数据源后,上述节点改为: 1 2 3 j...
937 0
HBase数据访问的一些常用方式
类型 特点 场合 优缺点分析 Native Java API 最常规和高效的访问方式 适合MapReduce作业并行批处理HBase表数据     Hbase Shell HBase的命令行工具,最简单的访问方式 适合HBase管理使用   T...
1479 0
阿里云 PB 级 Kubernetes 日志平台建设实践
阿里云日志服务技术专家元乙即将在 QCon 北京 2019 分享Kubernetes 日志平台建设最佳实践。 本来来自InfoQ对元乙的采访。
3493 0
+关注
2624
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载