Access Internet service using SAP Cloud Platform + jndi

Source: Internet
Author: User

With Internet Service http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Walldorf&destinations= Berlin, for example,

Access this URL in the browser to get the output: the distance from Walldorf to Berlin.

How can a Java application deployed to the SAP Cloud Platform also have access to the Internet service?

Start by creating a destination in the SAP Cloud platform to maintain the end point of the service:

Use the destination created in the SAP cloud Platform in Java code:

Then use the Jndi service to read the URL configured in destination:

After deploying to the SAP cloud Platform, see the preview results in eclipse:

The SAP cloud platform cockpit appears as follows:

Browser access is as follows:

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&    Gt <servlet-mapping> <servlet-name>ConnectivityServlet</servlet-name> <url-pattern>/&lt ;/url-pattern> </servlet-mapping> <!--Declare The JNDI lookup of destination--and <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, ioexcept        Ion {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 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 a 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 = Syste            M.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 (pro Xytype) {//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); }    }}

To get more original Jerry's technical articles, please follow the public number "Wang Zixi" or scan the QR code below:

Access Internet service using SAP Cloud Platform + jndi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.