DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • User-Friendly API Publishing and Testing With Retrofit
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services

Trending

  • Ethical AI in Agile
  • DGS GraphQL and Spring Boot
  • Data Quality: A Novel Perspective for 2025
  • Metrics at a Glance for Production Clusters
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. SSL-Based REST Web Service in Java JAX-RS With Spring

SSL-Based REST Web Service in Java JAX-RS With Spring

In this post, we go over how to add an SSL-based REST web service to a web applicaiton based on the Spring framework. Let's get started!

By 
Abhijit Pritam Dutta user avatar
Abhijit Pritam Dutta
·
Updated Apr. 09, 18 · Tutorial
Likes (17)
Comment
Save
Tweet
Share
44.4K Views

Join the DZone community and get the full member experience.

Join For Free

This is a continuation of my first article, and to understand it better, you should also have the knowledge of below-mentioned topics.

  1. What is an SSL certificate?
  2. What is an SSL handshake? 
  3. What is a Java Key Store (JKS)? There is lots of documentation online, read which is most suitable for you.
  4. What is a Java Trust Store (JTS)?
  5. What is a PKCS certificate/key store?
  6. What is HTTPS network protocol?

This is going to be a complete SSL-based REST project for you. You can download the project from my GitHub repo. You just need to refractor this framework/codebase and replace the existing Java classes with your classes to make this framework fulfill your business requirements. You can utilize this project as a backend or middle-tier application. I am going to add a few more classes to my earlier project to make it an SSL-based middle-tier (client) application. Also, I'm going to add a thread which can be used for health check purposes. In addition to this, I am planning to introduce one servlet as well.

I explained in my previous project/article how to create a package and class in Eclipse. Therefore, today I am going to add classes to the existing code base.

The first Java class I am going to add here is the health check thread class. First, create the package com.web.system.monitor in your existing project and add the class MonitorHeartBeat as shown below:

/****
 * This is a health check thread example. You can add more threads like this 
 * in your application as per your requirement. This class will spawns
 *  a thread at the very beginning, when this web service application will start loading.
 *  This thread will be instantiated from startup servlet. 
 */
package com.web.system.monitor;

public final class MonitorHeartBeat {
boolean keepProcessing_ = true;
public MonitorHeartBeat() {

try {
Thread t = new Thread(new HealthCheck());
t.start();
}
catch (Exception e) {
}
}

private class HealthCheck implements Runnable  {

public HealthCheck() {
}

@SuppressWarnings("unchecked")
public void run() {
do {
//your health check codes 
//For example you make some web calls from this application
//to a remote server and get some information from that server
//now you can put a web call every after 5 minutes from here to check whether remote server
//is up and running or not if not you can send mail to concern team that the remove server is down
try {
System.out.println("I will add my health check code here");
Thread.sleep(10000);
}catch(Exception e) {
e.printStackTrace();
}
}while (keepProcessing_); 
}
}

private final synchronized void stopProcessing() {
    keepProcessing_ = false;
    }

public void destroy() {
//This method need to be called from servlet 
stopProcessing(); 
    } 
}

Now create the package com.we.system.startup and add the servlet LoadOnStartUpto your project as shown below:

package com.we.system.startup;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class LoadOnStartUp extends HttpServlet
{
    private static com.web.system.monitor.MonitorHeartBeat heartBeatMonitor = null;

    private HttpServlet mServlet;

    public void init(ServletConfig servletConfig) throws ServletException
    {
    System.out.println("In LoadOnStartUp.init()");
        //super.init(servletConfig);
        //mServlet.init(servletConfig);
    new AnnotationConfigApplicationContext(com.web.common.config.InitConfig.class);
        heartBeatMonitor = new com.web.system.monitor.MonitorHeartBeat();// we created Heart beat monitor thread here
    }

    public void destroy()
    {
        //mServlet.destroy();
        heartBeatMonitor.destroy();// we are stopping the thread here.
    }
}

Provide reference to this servlet in the web.xml file like below:

<servlet>
<servlet-name>StartUpServlet</servlet-name>
<servlet-class>com.we.system.startup.LoadOnStartUp</servlet-class>
<init-param>
<param-name>disable-address-updates</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
             <!-- Make this servlet 1 and previous one as 2 -->
</servlet>

What will this servlet do? Its init method will be called when you start this web service application in any web server (for example, IBM WebSphere) and it will instantiate the thread object from the Java class MonitorHeartBeat, which will keep checking the status of the remote server whether it is up or down. This is an example only and hence I have not put any server check services into the code. You can add as many threads as you want as per your requirement. Also, from the init method, it will load the class InitConfig which is a configuration class I am introducing in this part of the project.

In my previous project/article, I did not use any log files or any application config files. Here I will introduce a common configuration class to get all the config information for this application. Now I will add the below class. This class will load all the configuration information from a .properties(config) file into a Java class object which we are going to use in a different section/place in the application.

Create a new package called com.web.common.config and add the InitConfig class:

package com.web.common.config;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;


@Configuration
@PropertySource("file:C:\\Projects\\RESTService1\\mywebconfig.properties")
//you need to change this path and file name in your actual project
public class InitConfig {
@Autowired
private Environment env;

@PostConstruct
   public void init(){
     initConfig();
     System.out.println("Initialized");
   }


@Bean
public static ApplicationConfig applicationConfig(){
return ApplicationConfig.getInstance();
}

public InitConfig(){
}

public void initConfig() {

System.out.println("initConfig - CommonConfig");
String logPropertyFilePath = env.getProperty("LOG_PROPERTY_FILE_PATH");
ApplicationConfig ac = ApplicationConfig.getInstance();
ac.setKEYSTOREPATH(env.getProperty("KEYSTOREPATH"));
ac.setTRUSTSTOREPATH(env.getProperty("TRUSTSTOREPATH"));
ac.setKEYSTOREPW(env.getProperty("KEYSTOREPW"));
ac.setTRUSTSTOREPW(env.getProperty("TRUSTSTOREPW"));
ac.setKEYPASS(env.getProperty("KEYPASS"));
ac.setHTTPS_SERV_URL(env.getProperty("HTTPS_SERV_URL"));
ac.setKeystoreType(env.getProperty("keystoreType"));
ac.setTrustAllCertificate(env.getProperty("trustAllCertificate"));
ac.setKeymanageralgorithm(env.getProperty("keymanageralgorithm"));
ac.setREGEX(env.getProperty("regex"));
if (logPropertyFilePath != null) {
System.out.println("Loading log properties file: "
+ logPropertyFilePath);
PropertyConfigurator.configure(logPropertyFilePath);
} else {
System.out.println("Called BasicConfigurator.configure()");
BasicConfigurator.configure();
}
}

}

And now I am going to add the ApplicationConfig class. This class will hold all the configuration information; here I am using very minimal configuration information, but you can add as much you want:

package com.web.common.config;

public final class ApplicationConfig {

private String KEYSTOREPATH = null;
private String TRUSTSTOREPATH = null;
private String KEYSTOREPW = null;
private String TRUSTSTOREPW = null;
private String KEYPASS = null;
private String HTTPS_SERV_URL = null;
private String trustAllCertificate = "false";// DEFAULT VALUE
private String keystoreType = "JKS";// DEFAULT VALUE
private String regex = null;
private String keymanageralgorithm = null;
private int mqreadinterval = 1;
private int httpsfialureinterval = 5;
private int prodissueinterval = 1;

private static ApplicationConfig myinstance = null;

public static ApplicationConfig getInstance() {
System.out.println("in ApplicationConfig getInstance");
if (myinstance == null) {
myinstance = new ApplicationConfig();
}
return myinstance;
}

private ApplicationConfig() {

}

public String getKEYSTOREPATH() {
return KEYSTOREPATH;
}

public void setKEYSTOREPATH(String kEYSTOREPATH) {
KEYSTOREPATH = kEYSTOREPATH;
}

public String getTRUSTSTOREPATH() {
return TRUSTSTOREPATH;
}

public void setTRUSTSTOREPATH(String tRUSTSTOREPATH) {
TRUSTSTOREPATH = tRUSTSTOREPATH;
}

public String getKEYSTOREPW() {
return KEYSTOREPW;
}

public void setKEYSTOREPW(String kEYSTOREPW) {
KEYSTOREPW = kEYSTOREPW;
}

public String getTRUSTSTOREPW() {
return TRUSTSTOREPW;
}

public void setTRUSTSTOREPW(String tRUSTSTOREPW) {
TRUSTSTOREPW = tRUSTSTOREPW;
}

public String getKEYPASS() {
return KEYPASS;
}

public void setKEYPASS(String kEYPASS) {
KEYPASS = kEYPASS;
}

public String getHTTPS_SERV_URL() {
return HTTPS_SERV_URL;
}

public void setHTTPS_SERV_URL(String hTTPS_SERV_URL) {
HTTPS_SERV_URL = hTTPS_SERV_URL;
}

public String getTrustAllCertificate() {
return trustAllCertificate;
}

public void setTrustAllCertificate(String trustAllCertificate) {
this.trustAllCertificate = trustAllCertificate;
}

public String getKeystoreType() {
return keystoreType;
}

public void setKeystoreType(String keystoreType) {
this.keystoreType = keystoreType;
}

public String getKeymanageralgorithm() {
return keymanageralgorithm;
}

public void setKeymanageralgorithm(String keymanageralgorithm) {
this.keymanageralgorithm = keymanageralgorithm;
}

public int getMqreadinterval() {
return mqreadinterval;
}

public void setMqreadinterval(int mqreadinterval) {
this.mqreadinterval = mqreadinterval;
}

public int getHttpsfialureinterval() {
return httpsfialureinterval;
}

public void setHttpsfialureinterval(int httpsfialureinterval) {
this.httpsfialureinterval = httpsfialureinterval;
}

public int getProdissueinterval() {
return prodissueinterval;
}

public void setProdissueinterval(int prodissueinterval) {
this.prodissueinterval = prodissueinterval;
}

public void setREGEX(String regex) {
this.regex = regex;
}

public String getREGEX() {
return this.regex;
}

public static ApplicationConfig getMyinstance() {
return myinstance;
}

public static void setMyinstance(ApplicationConfig myinstance) {
ApplicationConfig.myinstance = myinstance;
}
}

To make this an SSL-based project, I am going to introduce the SSLConfig class to load a jks/p12 key and trust store, including a certificate to the application. You have to get the certificate from your target application and import it into your key store. You need to contact your target application server team for the certificate. You can either ask them for a certificate or you can provide your own certificate to the server team to install on their end. First, add the below SSLContextConfig class to your project:

package com.web.common.ssl.config;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

import org.apache.log4j.Logger;
import com.web.common.config.ApplicationConfig;
import javax.net.ssl.KeyManager;



public class SSLContextConfig { 

private static final Logger LOGGER = Logger.getLogger(SSLContextConfig.class);
private ApplicationConfig config_ = ApplicationConfig.getInstance();
private TrustManager[] trustAllCerts = null;
private String keymanageralgorithm = null;
public SSLContext setupSslContext(){

SSLContext sslContext = null;
boolean trustall = false;
try {

String keyStorePath = config_.getKEYSTOREPATH();
String trustStorePath = config_.getTRUSTSTOREPATH();
String keyStorePw = config_.getKEYSTOREPW();
String trustStorePw = config_.getTRUSTSTOREPW();
String keyPass = config_.getKEYPASS();
String trustAllCertificate = config_.getTrustAllCertificate();
String keystoreType = config_.getKeystoreType();
keymanageralgorithm = config_.getKeymanageralgorithm();
trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

       }
    };
if(trustAllCertificate.equalsIgnoreCase("True")){
trustall = true;
}
if (keystoreType.equalsIgnoreCase("JKS"))
sslContext = initializeSSLContext(keyStorePath, keyStorePw, trustStorePath, trustStorePw, keyPass,trustall);
else
sslContext = initializeSSLContextP12Cert(keyStorePath, keyStorePw, trustStorePath, trustStorePw, keyPass,trustall);

}  catch (Exception exp) {
LOGGER.error("ConfigException exception occurred while reading the config file : " +exp.getMessage());
exp.printStackTrace();
} 
return sslContext;
}

/**
 * 
 * @param keyStorePath
 * @param pwKeyStore
 * @param trustStorePath
 * @param pwTrustStore
 * @param keyPass
 * @return
 * @throws Exception
 */
private SSLContext initializeSSLContext(final String keyStorePath, final String pwKeyStore, final String trustStorePath, final String pwTrustStore, final String keyPass, final boolean trustall) {
LOGGER.info(" In initializeSSLContext");
char[] keyStorePw = pwKeyStore.toCharArray();
char[] trustStorePw = pwTrustStore.toCharArray();
char[] keyPw = keyPass.toCharArray();
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextInt();

KeyStore ks = null;
try {
ks = KeyStore.getInstance("JKS");
} catch (KeyStoreException exp) {
LOGGER.error("KeyStoreException exception occurred while reading the config file : " +exp.getMessage());
}
FileInputStream fis = null;
try {
try {
fis = new FileInputStream(keyStorePath);
} catch (FileNotFoundException exp) {
LOGGER.error("FileNotFoundException exception occurred " +exp.getMessage());
}
try {
ks.load(fis, keyStorePw);
} catch (NoSuchAlgorithmException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (CertificateException exp) {
LOGGER.error("CertificateException exception occurred " +exp.getMessage());
} catch (IOException exp) {
LOGGER.error("CertificateException exception occurred " +exp.getMessage());
}
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException exp) {
LOGGER.error("IOException exception occurred " +exp.getMessage());
}
}

LOGGER.info("[initializeSSLContext] KMF keystorepw loaded.");

KeyManagerFactory kmf = null;
try {
kmf = KeyManagerFactory.getInstance(keymanageralgorithm);
} catch (NoSuchAlgorithmException exp) {
LOGGER.error("IOException exception occurred " +exp.getMessage());
}
try {
kmf.init(ks, keyPw);
} catch (UnrecoverableKeyException exp) {
LOGGER.error("UnrecoverableKeyException exception occurred " +exp.getMessage());
} catch (KeyStoreException exp) {
LOGGER.error("KeyStoreException exception occurred " +exp.getMessage());
} catch (NoSuchAlgorithmException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
}

LOGGER.info("[initializeSSLContext] KMF init done.");

KeyStore ts = null;
try {
ts = KeyStore.getInstance("JKS");
} catch (KeyStoreException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
}
FileInputStream tfis = null;
SSLContext sslContext = null;
try {
tfis = new FileInputStream(trustStorePath);
ts.load(tfis, trustStorePw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(keymanageralgorithm);
tmf.init(ts);
LOGGER.info("[initializeSSLContext] Truststore initialized");
sslContext = SSLContext.getInstance("TLS");

if(trustall)
sslContext.init(kmf.getKeyManagers(), trustAllCerts,secureRandom);
else
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers() ,secureRandom);

} catch (NoSuchAlgorithmException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (CertificateException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (IOException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (KeyStoreException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (KeyManagementException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} finally {
if (tfis != null)
try {
tfis.close();
} catch (IOException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
}
}

if((sslContext == null)){
LOGGER.error("[initializeSSLContext] sslContext is null");
System.exit(-1);
}
return sslContext;
}

/**
 * 
 * @param keyStorePath
 * @param pwKeyStore
 * @param trustStorePath
 * @param pwTrustStore
 * @param keyPass
 * @return
 * @throws Exception
 */
private SSLContext initializeSSLContextP12Cert(final String keyStorePath, final String pwKeyStore, final String trustStorePath, final String pwTrustStore, final String keyPass,final boolean trustall) {
LOGGER.info("In initializeSSLContextP12Cert");
SSLContext sslContext = null;
    String keystore = keyStorePath;
    String keystorepass = pwKeyStore;
    String truststore = trustStorePath;
    String truststorepass = pwTrustStore;

    try{
    KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream(keystore), keystorepass.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keymanageralgorithm);
        kmf.init(clientStore, keystorepass.toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream(truststore), truststorepass.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(keymanageralgorithm);
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();
        sslContext = SSLContext.getInstance("TLS");

        if(trustall)
        sslContext.init(kms, trustAllCerts, new SecureRandom());
        else
        sslContext.init(kms, tms, new SecureRandom());

    } catch (NoSuchAlgorithmException exp) {
LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage());
} catch (CertificateException exp) {
LOGGER.error("CertificateException exception occurred " +exp.getMessage());
} catch (IOException exp) {
LOGGER.error("IOException occurred while reading the key file  " +exp.getMessage());
} catch (KeyStoreException exp) {
LOGGER.error("KeyStoreException exception occurred " +exp.getMessage());
} catch (KeyManagementException exp) {
LOGGER.error("KeyManagementException exception occurred " +exp.getMessage());
}catch (UnrecoverableKeyException exp) {
LOGGER.error("UnrecoverableKeyException exception occurred " +exp.getMessage());
}

    if((sslContext == null)){
LOGGER.error("[initializeSSLContext] sslContext is null");
LOGGER.error("[initializeSSLContext] verify ssl config");
LOGGER.error("MyREST application exit with status code -1");
//System.exit(-1);
}
    LOGGER.info("[initializeSSLContextP12Cert] Truststore and KeyStore initialized");
return sslContext;
  }


}

I have designed the above class in such a way so that you can use both the p12 key store as well as the jks key store. See the configuration file for details.

This class will load the certificate and generate an sslContext object which we need to attach to an HTTPS connection object before making any remote HTTPS SSL-based call. Please keep in mind that if your target application does not want an SSL handshake you don’t really need any certificate. In this project, we are going to make a GET request to a GitHub server that does not require an SSL handshake. Hence, I have commented out the assigning of the sslContext object in the HTTPS connection object. You can uncomment the code and see what happens.

Now add the below webserviceManager class to your project. This class will connect to the remote web server through the HTTPS connection object and return the response back to the client application that initiated the REST call to this server. This is the crucial part of HTTPS communication. Here you might face lots of problems. Some of them are:

  • Handshake issues.

  • Various certificate related issues.

  • URL related issues.

You have to carefully analyze each issue and fix it. Fixing these issues is not covered here.

But for the purpose of successfully testing our app, I have commented out the certificate attachment part in the code, as I am going to make a call to some open source remote server where you don’t need a certificate.

package com.web.webservice.manager;
import com.web.common.config.ApplicationConfig;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;

import com.web.common.ssl.config.SSLContextConfig;

import org.apache.cxf.helpers.IOUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

public class WebServiceManager {

static int _responseCode = -1;
static private ApplicationConfig config_ = ApplicationConfig.getInstance();
private static final Logger LOGGER = Logger.getLogger(WebServiceManager.class);

static HttpsURLConnection connection_ = null;
static SSLContext sslContext = null;
    static  {

    //SSLContextConfig sslconfig = new SSLContextConfig();
//sslContext = sslconfig.setupSslContext();
    LOGGER.info("Webservice is loading...");
}

//------------------------------------------------------------------

static public boolean setSSLConnection(UriInfo info) {
System.out.println("In setSSLConnection");
URL url = null;
//HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
//.getSocketFactory());

try {
url = new URL(null, WebServiceManager.generateTargetURL(info),
new sun.net.www.protocol.https.Handler());
} catch (Exception e1) {
LOGGER.error("MalformedURLException occurred " + e1.getMessage());
}

try {
connection_ = (HttpsURLConnection) url.openConnection();
//connection_.setSSLSocketFactory(sslContext.getSocketFactory());
            connection_.setDoOutput( true );
            connection_.setRequestProperty( "Content-Type", "text/xml"  );
            connection_.connect();
return true;
} catch (Exception e) {
LOGGER.error("Exception occurred while establishing connection to SSL server. Error :"
+ e.getMessage());
connection_.disconnect();
connection_ = null;
return false;
}
}
//----------------------------------------------------------------------------------

static public String generateTargetURL(UriInfo info) {
LOGGER.info("In generateTargetURL()");
String url = null;
String regex = config_.getREGEX();
String sevcURL[] = info.getRequestUri().toString().split(regex);
String serviceURL = config_.getHTTPS_SERV_URL();
url = serviceURL + sevcURL[1].replace("/"+"Github.json","").replace("/v/github/", "");
LOGGER.info("URL is : " + url);
return url;

}

static public Response sendGETmsg(UriInfo info) {
LOGGER.info("In sendGETmsg");
String response = null;
int retcode = 500;
if(!WebServiceManager.setSSLConnection(info)) {
       response = "Failed to setSSLConnection ";
       return Response.status(Status.INTERNAL_SERVER_ERROR).entity(response).type(MediaType.APPLICATION_JSON).build();
       }
try {

//connection_.setRequestMethod("GET");
retcode = connection_.getResponseCode();
System.out.println("In sendGETmsg2 :" + retcode);
if(retcode != 401 && retcode != 500)
    response = IOUtils.toString(connection_.getInputStream());
else
response="Failed to connect to remote server :";
}catch(Exception e) {
e.printStackTrace();
}
connection_.disconnect();
return Response.status(retcode).entity(response).type(MediaType.APPLICATION_JSON).build();
}

//Now send the message to the server:-

public static Response sendPOSTmsg(UriInfo info, Object sendObject) {

String response = null;

       if(!WebServiceManager.setSSLConnection(info)) {
       response = "Failed to setSSLConnection ";
       return Response.status(Status.INTERNAL_SERVER_ERROR).entity(response).type(MediaType.APPLICATION_JSON).build();
       }

       ObjectMapper mapper = new ObjectMapper();       

try{
connection_.setRequestMethod("POST");
Writer strWriter = new StringWriter();
mapper.writeValue(strWriter, sendObject);
String reqJSONData = strWriter.toString();
        //Sending the request to Remote server
      OutputStreamWriter writer = new OutputStreamWriter(connection_.getOutputStream());
          writer.write(reqJSONData);
          writer.flush();
          writer.close();

          _responseCode = connection_.getResponseCode();

          LOGGER.info("Response Code :" + _responseCode);

     // reading the response
          InputStreamReader reader = new InputStreamReader(connection_.getInputStream());
          StringBuilder buf = new StringBuilder();
          char[] cbuf = new char[ 2048 ];
          int num;
          while ( -1 != (num = reader.read( cbuf )))
          {
              buf.append( cbuf, 0, num );
          }
          response = buf.toString();

 }catch(Exception e){
 response = "<EXCEPTION>Exception occurred while sending message</EXCEPTION>";
 e.printStackTrace();
 }
connection_.disconnect();
return Response.status(Status.OK).entity(response).type(MediaType.APPLICATION_JSON).build();
}


}

Finally, we are done with everything. Even though I have introduced the POST call here I am not providing any test results, as I did not find any open source POST call available online.

Now, right click on your project, select 'Run,' and select the server. Once the web service starts running successfully, perform the following test.

In your SOAPI tool, select File and then select “New REST Project” and put the below URL in and follow the instructions provided in my previous post:

http://localhost:9080/ RESTService1/rest/example/v/github/Github.json/repositories?sort=stars&q="Apps Script" stars:">=100"

Most of the necessary functionalities have been added in this REST SSL-based web service project. You can even utilize this framework for your company for business purposes. Please provide me any feedback you have!

Thanks for reading this article!

REST Web Protocols Web Service Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • User-Friendly API Publishing and Testing With Retrofit
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!