Skip to content

Commit

Permalink
Fix central connection
Browse files Browse the repository at this point in the history
  • Loading branch information
pramodya1994 committed Mar 16, 2021
1 parent a3bac05 commit 4609ffe
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 126 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,21 @@
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.core.HttpHeaders;

import static org.ballerinalang.cli.module.util.CliModuleConstants.BALLERINA_PLATFORM;
import static org.ballerinalang.cli.module.util.CliModuleConstants.BAL_LANG_SPEC_VERSION;
import static org.ballerinalang.cli.module.util.CliModuleConstants.IDENTITY;
import static org.ballerinalang.cli.module.util.CliModuleConstants.RESOLVED_REQUESTED_URI;
import static org.ballerinalang.cli.module.util.Utils.convertToUrl;
import static org.ballerinalang.cli.module.util.Utils.createHttpUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.createHttpsUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.getStatusCode;
import static org.ballerinalang.cli.module.util.Utils.initializeSsl;
import static org.ballerinalang.cli.module.util.Utils.setRequestMethod;

/**
Expand Down Expand Up @@ -84,11 +83,10 @@ public static void execute(String url, String modulePathInBaloCache, String modu
logFormatter = new BuildLogFormatter();
}

HttpURLConnection conn = null;
HttpsURLConnection conn = null;
try {
initializeSsl();
conn = createHttpUrlConnection(convertToUrl(url + supportedVersionRange), proxyHost, proxyPort,
proxyUsername, proxyPassword);
conn = createHttpsUrlConnection(convertToUrl(url + supportedVersionRange), proxyHost, proxyPort,
proxyUsername, proxyPassword);

conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.GET);
Expand All @@ -101,7 +99,7 @@ public static void execute(String url, String modulePathInBaloCache, String modu
boolean redirect = false;
// 302 - Module is found
// Other - Error occurred, json returned with the error message
if (getStatusCode(conn) == HttpURLConnection.HTTP_MOVED_TEMP) {
if (getStatusCode(conn) == HttpsURLConnection.HTTP_MOVED_TEMP) {
redirect = true;
} else {
handleErrorResponse(conn, url, moduleNameWithOrg);
Expand All @@ -112,8 +110,8 @@ public static void execute(String url, String modulePathInBaloCache, String modu
String newUrl = conn.getHeaderField(HttpHeaders.LOCATION);
String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION);

conn = createHttpUrlConnection(convertToUrl(newUrl), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn = createHttpsUrlConnection(convertToUrl(newUrl), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn.setRequestProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);

createBaloInHomeRepo(conn, modulePathInBaloCache, moduleNameWithOrg, isNightlyBuild, newUrl,
Expand All @@ -132,14 +130,14 @@ public static void execute(String url, String modulePathInBaloCache, String modu
/**
* Create the balo in home repo.
*
* @param conn http connection
* @param conn https connection
* @param modulePathInBaloCache module path in balo cache, <user.home>.ballerina/balo_cache/<org-name>/<module-name>
* @param moduleNameWithOrg module name with org, <org-name>/<module-name>
* @param isNightlyBuild is nightly build
* @param newUrl new redirect url
* @param contentDisposition content disposition header
*/
private static void createBaloInHomeRepo(HttpURLConnection conn, String modulePathInBaloCache,
private static void createBaloInHomeRepo(HttpsURLConnection conn, String modulePathInBaloCache,
String moduleNameWithOrg, boolean isNightlyBuild, String newUrl, String contentDisposition) {
long responseContentLength = conn.getContentLengthLong();
if (responseContentLength <= 0) {
Expand Down Expand Up @@ -170,12 +168,12 @@ private static void createBaloInHomeRepo(HttpURLConnection conn, String modulePa
/**
* Write balo file to the home repo.
*
* @param conn http connection
* @param conn https connection
* @param baloPath path of the balo file
* @param fullModuleName full module name, <org-name>/<module-name>:<module-version>
* @param resContentLength response content length
*/
private static void writeBaloFile(HttpURLConnection conn, Path baloPath, String fullModuleName,
private static void writeBaloFile(HttpsURLConnection conn, Path baloPath, String fullModuleName,
long resContentLength) {
try (InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(baloPath.toString())) {
Expand Down Expand Up @@ -268,11 +266,11 @@ private static void createBaloFileDirectory(Path fullPathToStoreBalo) {
/**
* Handle error response.
*
* @param conn http connection
* @param conn https connection
* @param url remote repository url
* @param moduleFullName module name with org and version
*/
private static void handleErrorResponse(HttpURLConnection conn, String url, String moduleFullName) {
private static void handleErrorResponse(HttpsURLConnection conn, String url, String moduleFullName) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,18 @@
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import static org.ballerinalang.cli.module.util.CliModuleConstants.PUSH_ORGANIZATION;
import static org.ballerinalang.cli.module.util.Utils.convertToUrl;
import static org.ballerinalang.cli.module.util.Utils.createHttpUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.createHttpsUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.getStatusCode;
import static org.ballerinalang.cli.module.util.Utils.initializeSsl;
import static org.ballerinalang.cli.module.util.Utils.setRequestMethod;

/**
Expand Down Expand Up @@ -76,9 +75,8 @@ private Push() {
*/
public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
String accessToken, String orgName, String moduleName, String version, Path baloPath) {
initializeSsl();
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.POST);

Expand Down Expand Up @@ -115,21 +113,21 @@ public static void execute(String url, String proxyHost, int proxyPort, String p
/**
* Handle the http response.
*
* @param conn http connection
* @param conn https connection
* @param orgName org name
* @param moduleName module name
* @param version module version
*/
private static void handleResponse(HttpURLConnection conn, String orgName, String moduleName, String version) {
private static void handleResponse(HttpsURLConnection conn, String orgName, String moduleName, String version) {
try {
int statusCode = getStatusCode(conn);
// 200 - Module pushed successfully
// Other - Error occurred, json returned with the error message
if (statusCode == HttpURLConnection.HTTP_OK) {
if (statusCode == HttpsURLConnection.HTTP_OK) {
outStream.println(orgName + "/" + moduleName + ":" + version + " pushed to central successfully");
} else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
} else if (statusCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
errStream.println("unauthorized access token for organization: " + orgName);
} else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
} else if (statusCode == HttpsURLConnection.HTTP_BAD_REQUEST) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.net.ssl.HttpsURLConnection;

import static org.ballerinalang.cli.module.util.Utils.convertToUrl;
import static org.ballerinalang.cli.module.util.Utils.createHttpUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.createHttpsUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.getStatusCode;
import static org.ballerinalang.cli.module.util.Utils.initializeSsl;
import static org.ballerinalang.cli.module.util.Utils.setRequestMethod;

/**
Expand All @@ -63,9 +63,8 @@ private Search() {
*/
public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
String terminalWidth) {
initializeSsl();
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.GET);
handleResponse(conn, getStatusCode(conn), terminalWidth);
Expand All @@ -75,16 +74,16 @@ public static void execute(String url, String proxyHost, int proxyPort, String p
/**
* Handle http response.
*
* @param conn http connection
* @param conn https connection
* @param statusCode status code of the response
* @param terminalWidth terminal width of the CLI
*/
private static void handleResponse(HttpURLConnection conn, int statusCode, String terminalWidth) {
private static void handleResponse(HttpsURLConnection conn, int statusCode, String terminalWidth) {
try {
// 200 - modules found
// Other - Error occurred, json returned with the error message
MapValue payload;
if (statusCode == HttpURLConnection.HTTP_OK) {
if (statusCode == HttpsURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Collections;

import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.core.HttpHeaders;

import static org.ballerinalang.cli.module.util.CliModuleConstants.SETTINGS_TOML_FILE;
Expand Down Expand Up @@ -104,8 +104,8 @@ static class TokenUpdateHandler implements HttpHandler {
String response = "<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
httpExchange.getResponseHeaders()
.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList("image/svg+xml"));
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,
response.getBytes(StandardCharsets.UTF_8).length);
httpExchange.sendResponseHeaders(HttpsURLConnection.HTTP_OK,
response.getBytes(StandardCharsets.UTF_8).length);
os = httpExchange.getResponseBody();
os.write(response.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,14 @@

import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import static org.ballerinalang.cli.module.util.CliModuleConstants.SSL;

/**
* Class contains miscellaneous utility methods.
Expand All @@ -49,20 +41,6 @@ public enum RequestMethod {
GET, POST
}

private static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}

public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
} };

/**
* Get proxy for http connection.
*
Expand Down Expand Up @@ -103,20 +81,7 @@ public static URL convertToUrl(String url) {
}

/**
* Initialize SSL.
*/
public static void initializeSsl() {
try {
SSLContext sc = SSLContext.getInstance(SSL);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw ErrorUtil.createCommandException("initializing SSL failed: " + e.getMessage());
}
}

/**
* Create http URL connection.
* Create https URL connection.
*
* @param url connection URL
* @param proxyHost proxy host
Expand All @@ -125,15 +90,15 @@ public static void initializeSsl() {
* @param proxyPassword proxy password
* @return http URL connection
*/
public static HttpURLConnection createHttpUrlConnection(URL url, String proxyHost, int proxyPort,
public static HttpsURLConnection createHttpsUrlConnection(URL url, String proxyHost, int proxyPort,
String proxyUsername, String proxyPassword) {
try {
Proxy proxy = getProxy(proxyHost, proxyPort, proxyUsername, proxyPassword);
// set proxy if exists.
if (proxy == null) {
return (HttpURLConnection) url.openConnection();
return (HttpsURLConnection) url.openConnection();
} else {
return (HttpURLConnection) url.openConnection(proxy);
return (HttpsURLConnection) url.openConnection(proxy);
}
} catch (IOException e) {
throw ErrorUtil.createCommandException(e.getMessage());
Expand All @@ -143,10 +108,10 @@ public static HttpURLConnection createHttpUrlConnection(URL url, String proxyHos
/**
* Set request method of the http connection.
*
* @param conn http connection
* @param conn https connection
* @param method request method
*/
public static void setRequestMethod(HttpURLConnection conn, RequestMethod method) {
public static void setRequestMethod(HttpsURLConnection conn, RequestMethod method) {
try {
conn.setRequestMethod(getRequestMethodAsString(method));
} catch (ProtocolException e) {
Expand All @@ -168,10 +133,10 @@ private static String getRequestMethodAsString(RequestMethod method) {
/**
* Get status code of http response.
*
* @param conn http connection
* @param conn https connection
* @return status code
*/
public static int getStatusCode(HttpURLConnection conn) {
public static int getStatusCode(HttpsURLConnection conn) {
try {
return conn.getResponseCode();
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
import org.testng.Assert;
import org.testng.annotations.Test;

import java.net.HttpURLConnection;
import java.net.Proxy;

import javax.net.ssl.HttpsURLConnection;

import static org.ballerinalang.cli.module.util.Utils.convertToUrl;
import static org.ballerinalang.cli.module.util.Utils.createHttpUrlConnection;
import static org.ballerinalang.cli.module.util.Utils.createHttpsUrlConnection;

/**
* Unit tests for Utils class.
Expand All @@ -50,20 +51,20 @@ public void testGetProxy() {

}

@Test(description = "Test create http URL connection without proxy")
@Test(description = "Test create https URL connection without proxy")
public void testCreateHttpUrlConnection() {
HttpURLConnection conn;
HttpsURLConnection conn;
// Test without proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Assert.assertNotNull(conn);
// Test with the proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
Assert.assertNotNull(conn);
}

@Test(description = "Test set request")
public void testSetRequestMethod() {
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Utils.setRequestMethod(conn, Utils.RequestMethod.POST);
Assert.assertEquals(conn.getRequestMethod(), "POST");
}
Expand Down
Loading

0 comments on commit 4609ffe

Please sign in to comment.