I have included a Java code where I need to find a way to convert HashMap to JSO
ID: 3748355 • Letter: I
Question
I have included a Java code where I need to find a way to convert HashMap to JSON. Is there a way that I can do this as I am not familiar with how to use JSON?
//Response Header Imports
import java.net.*;
import java.util.List;
import java.util.Map;
import java.io.IOException;
/////////////////////////////////
import org.apache.catalina.Server;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
import java.security.cert.X509Certificate;
import javax.net.*;
import java.net.URL;
import javax.net.ssl.*;
import java.security.cert.Certificate;
import java.net.MalformedURLException;
import java.io.IOException;
import java.security.cert.*;
public class ServerAnalyzerBackEnd {
private String url;
private boolean validURL;
public ServerAnalyzerBackEnd(String url) {
this.url = url;
this.validURL = validateURLSyntax();
}
public ModelAndView start() {
String host;
Map params = new HashMap<>();
params.put("url", url);
String secureURL = "";
URL testURL;
int port;
String cert_chain = "";
if (!validURL)
{
System.out.println("We should probably stop it here or something.");
}
//url is not null, assign to secureURL to create https connection
if(url != null){
secureURL = url;
}
//Initialize Strings for later output
String response_header = "";
String cipherSuite = "";
//create URL object from 'url'
//create https connection based off of url and then call getCertChain method to pull that cert chain
try {
testURL = new URL(secureURL);
port = testURL.getPort();
host = testURL.getHost();
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket socket = socketFactory.createSocket(host, port);
SSLSession session = ((SSLSocket) socket).getSession();
cipherSuite = session.getCipherSuite();
System.out.println("Cipher is " + session.getCipherSuite());
HttpsURLConnection connection = (HttpsURLConnection)testURL.openConnection();
cert_chain = getCertChain(session);
System.out.println(cert_chain);
response_header = getResponseHeader(connection);
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
//Put strings into Hash Map to be displayed in output
params.put("response_header", response_header);
params.put("certificate_chain", cert_chain);
params.put("cipher_suite", cipherSuite);
return new ModelAndView("showURL", params);
}
public String getCertChain(SSLSession session){
String result = "";
try{
//make array of Certificate objects and grab the cert chain from the https connection
Certificate[] certificates = session.getPeerCertificates();
//foreach c in Certificates print cert details to console.
for(int i = 0; i < certificates.length; i++){
X509Certificate cert = (X509Certificate) certificates[i];
result += (cert.getSubjectX500Principal());
}
}
/*
catch (SSLPeerUnverifiedException e){
e.printStackTrace();
} */
catch (IOException e){
e.printStackTrace();
}
//System.out.println(result);
return result;
}
public String getResponseHeader(HttpsURLConnection connection){
String result = "Key 'Content-Type' is not found!";
//Response Header Function
try {
System.out.println("HTTP Headers");
System.out.println();
Map> map = connection.getHeaderFields();
for (Map.Entry> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
System.out.println("Get Header by key:");
String server = connection.getHeaderField("Content-Type");
if (server != null) {
result = "Content-Type: " + server;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
return result;
}
public boolean validateURLSyntax()
{
int firstColon;
int secondColon;
boolean URLsyntax = true;
//Checks if the first four characters are http
if (!this.url.substring(0,4).equals("http"))
{
URLsyntax = false;
}
//Checks if a port number was specified. If not, appends :443 to the URL.
firstColon = this.url.indexOf(":");
secondColon = this.url.lastIndexOf(':');
if (secondColon == -1 || firstColon == secondColon)
{
this.url = this.url + ":443";
}
//Something like https://www.google.com: and no port actually specified or junk is after the port.
secondColon = this.url.lastIndexOf(':');
if (this.url.charAt(this.url.length() - 1) == ':' || !Character.isDigit(this.url.charAt(secondColon + 1)))
{
URLsyntax = false;
}
return URLsyntax;
}
}
Explanation / Answer
Solution:
/*IF I CONSIDER THAT YOU WANT TO
* CONVERT THIS params MAP TO JSON
* THE MOST SIMPLE WAY TO DO IT
* IS USING JSONObject CLASS FROM org.json PACKAGE.
* YOU HAVE TO INCLUDE org.json JAR IN YOUR
* CLASS PATH IN ORDER TO USE IT. THE FULLY
* QUALIFIED CLASS NAME IS org.json.JSONObject
*/
Please find below the code of start() method where the map is converted into JSON object.
package aug9;
//Response Header Imports
import java.net.*;
import java.util.List;
import java.util.Map;
import java.io.IOException;
/////////////////////////////////
import org.apache.catalina.Server;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
import java.security.cert.X509Certificate;
import javax.net.*;
import java.net.URL;
import javax.net.ssl.*;
import java.security.cert.Certificate;
import java.net.MalformedURLException;
import java.io.IOException;
import java.security.cert.*;
public class ServerAnalyzerBackEnd {
private String url;
private boolean validURL;
public ServerAnalyzerBackEnd(String url) {
this.url = url;
this.validURL = validateURLSyntax();
}
public ModelAndView start() {
String host;
Map params = new HashMap<>();
params.put("url", url);
String secureURL = "";
URL testURL;
int port;
String cert_chain = "";
if (!validURL)
{
System.out.println("We should probably stop it here or something.");
}
//url is not null, assign to secureURL to create https connection
if(url != null){
secureURL = url;
}
//Initialize Strings for later output
String response_header = "";
String cipherSuite = "";
//create URL object from 'url'
//create https connection based off of url and then call getCertChain method to pull that cert chain
try {
testURL = new URL(secureURL);
port = testURL.getPort();
host = testURL.getHost();
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket socket = socketFactory.createSocket(host, port);
SSLSession session = ((SSLSocket) socket).getSession();
cipherSuite = session.getCipherSuite();
System.out.println("Cipher is " + session.getCipherSuite());
HttpsURLConnection connection = (HttpsURLConnection)testURL.openConnection();
cert_chain = getCertChain(session);
System.out.println(cert_chain);
response_header = getResponseHeader(connection);
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
//Put strings into Hash Map to be displayed in output
params.put("response_header", response_header);
params.put("certificate_chain", cert_chain);
params.put("cipher_suite", cipherSuite);
/*IF I CONSIDER THAT YOU WANT TO
* CONVERT THIS params MAP TO JSON
* THE MOST SIMPLE WAY TO DO IT
* IS USING JSONObject CLASS FROM org.json PACKAGE.
* YOU HAVE TO INCLUDE org.json JAR IN YOUR
* CLASS PATH IN ORDER TO USE IT. THE FULLY
* QUALIFIED CLASS NAME IS org.json.JSONObject
*/
JSONObject json = new JSONObject(params);
return new ModelAndView("showURL", params);
}
public String getCertChain(SSLSession session){
String result = "";
try{
//make array of Certificate objects and grab the cert chain from the https connection
Certificate[] certificates = session.getPeerCertificates();
//foreach c in Certificates print cert details to console.
for(int i = 0; i < certificates.length; i++){
X509Certificate cert = (X509Certificate) certificates[i];
result += (cert.getSubjectX500Principal());
}
}
/*
catch (SSLPeerUnverifiedException e){
e.printStackTrace();
} */
catch (IOException e){
e.printStackTrace();
}
//System.out.println(result);
return result;
}
public String getResponseHeader(HttpsURLConnection connection){
String result = "Key 'Content-Type' is not found!";
//Response Header Function
try {
System.out.println("HTTP Headers");
System.out.println();
Map> map = connection.getHeaderFields();
for (Map.Entry> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
System.out.println("Get Header by key:");
String server = connection.getHeaderField("Content-Type");
if (server != null) {
result = "Content-Type: " + server;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
return result;
}
public boolean validateURLSyntax()
{
int firstColon;
int secondColon;
boolean URLsyntax = true;
//Checks if the first four characters are http
if (!this.url.substring(0,4).equals("http"))
{
URLsyntax = false;
}
//Checks if a port number was specified. If not, appends :443 to the URL.
firstColon = this.url.indexOf(":");
secondColon = this.url.lastIndexOf(':');
if (secondColon == -1 || firstColon == secondColon)
{
this.url = this.url + ":443";
}
//Something like https://www.google.com: and no port actually specified or junk is after the port.
secondColon = this.url.lastIndexOf(':');
if (this.url.charAt(this.url.length() - 1) == ':' || !Character.isDigit(this.url.charAt(secondColon + 1)))
{
URLsyntax = false;
}
return URLsyntax;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.