import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
//Include dependency in pom.xml file
//<dependency>
//<groupId>net.sourceforge.htmlunit</groupId>
//<artifactId>htmlunit</artifactId>
//<version>2.13</version>
//</dependency>
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
//Include dependency in pom.xml file
//<dependency>
// <groupId>org.json</groupId>
// <artifactId>json</artifactId>
// <version>20080701</version>
//</dependency>
import org.json.JSONArray;
import org.json.JSONObject;
public class JiraAutoFiler {
public static String JIRA_HOST = "jira.com";
public static String JIRA_USERNAME = "myusername";
public static String JIRA_PASSWORD = "password";
public static IssueTypeAttributes addJIRAIssueInformation(String projectKey, String issueTypeID) {
IssueTypeAttributes issueTypeAttributes = new IssueTypeAttributes();
issueTypeAttributes.projectKey = projectKey;
issueTypeAttributes.issueTypeID = issueTypeID;
try {
System.out.println("Step 1a: Setup Authentication Information");
System.out.println("Step 1b: Install SSL Certificate");
SSLHandler.setupSSLContextByInstallingCertification(JIRA_HOST);
System.out.println("Step 2: Query Server for Projects");
HttpGet httpGet = new HttpGet("https://"+JIRA_HOST+"/rest/api/2/issue/createmeta?projectKeys="+issueTypeAttributes.projectKey+"&issuetypeIds="+issueTypeAttributes.issueTypeID+"&expand=projects.issuetypes.fields");
String basic_auth = new String(Base64.encodeBase64((JIRA_USERNAME+":"+JIRA_PASSWORD).getBytes())); //
httpGet.addHeader("Authorization", "Basic " + basic_auth);
CloseableHttpResponse response = new DefaultHttpClient().execute(httpGet);
String projectResponsJSON = EntityUtils.toString(response.getEntity());
response.close();
System.out.println("projectResponse:"+projectResponsJSON);
JSONObject metaData = new JSONObject(projectResponsJSON);
JSONArray projects = metaData.getJSONArray("projects");
// holder.errorMessages = holder.errorMessages + projects.toString();
JSONObject project = projects.getJSONObject(0);
// holder.errorMessages = holder.errorMessages + project.toString();
issueTypeAttributes.jiraProjectName = project.getString("name");
issueTypeAttributes.jiraProjectID = project.getString("id");
JSONArray issuetypes = project.getJSONArray("issuetypes");
JSONObject issuetype = issuetypes.getJSONObject(0);
issueTypeAttributes.issueName = issuetype.getString("name");
JSONObject fields = issuetype.getJSONObject("fields");
for(String fieldName: JSONObject.getNames(fields)) {
JSONObject fieldJSON = fields.getJSONObject(fieldName);
IssueTypeFieldAttributes field = new IssueTypeFieldAttributes();
field.fieldName = fieldName;
field.fieldDisplayName = fieldJSON.getString("name");
field.isRequired = fieldJSON.getBoolean("required");
JSONObject schema = fieldJSON.getJSONObject("schema");
field.type = schema.getString("type");
try {
JSONArray allowedValues = fieldJSON.getJSONArray("allowedValues");
for (int i = 0; i < allowedValues.length(); i++) {
JSONObject allowedValueJSON = allowedValues.getJSONObject(i);
IssueTypeFieldAllowedValue allowedValue = new IssueTypeFieldAllowedValue();
allowedValue.valueID = allowedValueJSON.getString("id");
allowedValue.valueName = allowedValueJSON.getString("value");
field.allowedValues.add(allowedValue);
}
} catch (Exception ex) {}
issueTypeAttributes.fields.add(field);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return issueTypeAttributes;
}
public static class IssueTypeAttributes{
public String projectKey;
public String issueTypeID;
public String jiraProjectName;
public String jiraProjectID;
public String issueName;
public List<IssueTypeFieldAttributes> fields = new ArrayList<IssueTypeFieldAttributes>();
public String buildCURLCommand() {
String curlCommand = "curl -k -H \"Content-Type: application/json\" -D- -X POST --data \'{\"fields\": {";
curlCommand = curlCommand + "\"project\":{\"key\":\""+projectKey+"\"}, \"issuetype\": {\"id\":\""+issueTypeID+"\"}";
for(IssueTypeFieldAttributes field: fields) {
if(field.isRequired && (field.type.equals("string") || field.type.equals("array"))) {
String defaultValue = null;
try {
defaultValue = "{\"id\":\""+field.allowedValues.get(0).valueID+"\"}";
} catch (Exception ex) {
defaultValue = "\"Test\"";
}
if(field.type.equals("string")) {
curlCommand = curlCommand + ", \""+field.fieldName+"\":"+defaultValue;
} else if (field.type.equals("array")) {
curlCommand = curlCommand + ", \""+field.fieldName+"\":["+defaultValue+"]";
}
}
}
curlCommand = curlCommand + "}}\' https://"+JIRA_HOST+"/rest/api/2/issue -u "+JIRA_USERNAME;
return curlCommand;
}
public String buildJSPALink() {
String jspaLink = "https://"+JIRA_HOST+"/secure/CreateIssueDetails!init.jspa?";
jspaLink = jspaLink + "pid="+ jiraProjectID +"&issuetype="+issueTypeID;
for(IssueTypeFieldAttributes field: fields) {
if(field.isRequired && (field.type.equals("string") || field.type.equals("array"))) {
String defaultValueID = null;
try {
defaultValueID = field.allowedValues.get(0).valueID;
} catch (Exception ex) {
defaultValueID = "Test";
}
jspaLink = jspaLink + "&"+field.fieldName+"="+defaultValueID;
}
}
return jspaLink;
}
}
public static class IssueTypeFieldAttributes{
public String fieldName;
public String fieldDisplayName;
public Boolean isRequired;
public String type;
public List<IssueTypeFieldAllowedValue> allowedValues = new ArrayList<IssueTypeFieldAllowedValue>();
}
public static class IssueTypeFieldAllowedValue{
public String valueID;
public String valueName;
}
public static class SSLHandler{
/**
* Should be called right before connection
*
* Installs C:\Program Files\Java\jdk1.7.0_51\jre\lib\security\jssecacerts file
* @param host
* @throws Exception
*/
static Set<String> hostsInstalled = new HashSet<String>();
public static void setupSSLContextByInstallingCertification(String host) {
if(hostsInstalled.contains(host)) {
return;
} else {
hostsInstalled.add(host);
}
System.out.println("Installing SSLContext Certification into Java Home...");
try {
int port = 443;
char[] passphrase = "changeit".toCharArray();
char SEP = File.separatorChar;
File file = new File("jssecacerts");
if (file.isFile() == false) {
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
final List<X509Certificate> chainList = new ArrayList<X509Certificate>();
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException { }
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
chainList.clear();
if(arg0 != null) {
for (int i = 0; i < arg0.length; i++) {
chainList.add(arg0[i]);
}
}
defaultTrustManager.checkServerTrusted(arg0, arg1); }
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
socket.startHandshake();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) { }
socket.close();
if (chainList.isEmpty()) {
System.out.println("Could not obtain server certificate chain");
return;
}
System.out.println("Server sent " + chainList.size() + " certificate(s):");
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chainList.size(); i++) {
X509Certificate cert = chainList.get(i);
System.out.println
(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
}
int k = 0;
X509Certificate cert = chainList.get(k);
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
OutputStream out = new FileOutputStream(file);
ks.store(out, passphrase);
out.close();
System.out.println("Installed SSLContext Certification into Java Home: "+file.getAbsolutePath());
} catch (Exception ex) { }
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
//Include dependency in pom.xml file
//<dependency>
//<groupId>net.sourceforge.htmlunit</groupId>
//<artifactId>htmlunit</artifactId>
//<version>2.13</version>
//</dependency>
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
//Include dependency in pom.xml file
//<dependency>
// <groupId>org.json</groupId>
// <artifactId>json</artifactId>
// <version>20080701</version>
//</dependency>
import org.json.JSONArray;
import org.json.JSONObject;
public class JiraAutoFiler {
public static String JIRA_HOST = "jira.com";
public static String JIRA_USERNAME = "myusername";
public static String JIRA_PASSWORD = "password";
public static IssueTypeAttributes addJIRAIssueInformation(String projectKey, String issueTypeID) {
IssueTypeAttributes issueTypeAttributes = new IssueTypeAttributes();
issueTypeAttributes.projectKey = projectKey;
issueTypeAttributes.issueTypeID = issueTypeID;
try {
System.out.println("Step 1a: Setup Authentication Information");
System.out.println("Step 1b: Install SSL Certificate");
SSLHandler.setupSSLContextByInstallingCertification(JIRA_HOST);
System.out.println("Step 2: Query Server for Projects");
HttpGet httpGet = new HttpGet("https://"+JIRA_HOST+"/rest/api/2/issue/createmeta?projectKeys="+issueTypeAttributes.projectKey+"&issuetypeIds="+issueTypeAttributes.issueTypeID+"&expand=projects.issuetypes.fields");
String basic_auth = new String(Base64.encodeBase64((JIRA_USERNAME+":"+JIRA_PASSWORD).getBytes())); //
httpGet.addHeader("Authorization", "Basic " + basic_auth);
CloseableHttpResponse response = new DefaultHttpClient().execute(httpGet);
String projectResponsJSON = EntityUtils.toString(response.getEntity());
response.close();
System.out.println("projectResponse:"+projectResponsJSON);
JSONObject metaData = new JSONObject(projectResponsJSON);
JSONArray projects = metaData.getJSONArray("projects");
// holder.errorMessages = holder.errorMessages + projects.toString();
JSONObject project = projects.getJSONObject(0);
// holder.errorMessages = holder.errorMessages + project.toString();
issueTypeAttributes.jiraProjectName = project.getString("name");
issueTypeAttributes.jiraProjectID = project.getString("id");
JSONArray issuetypes = project.getJSONArray("issuetypes");
JSONObject issuetype = issuetypes.getJSONObject(0);
issueTypeAttributes.issueName = issuetype.getString("name");
JSONObject fields = issuetype.getJSONObject("fields");
for(String fieldName: JSONObject.getNames(fields)) {
JSONObject fieldJSON = fields.getJSONObject(fieldName);
IssueTypeFieldAttributes field = new IssueTypeFieldAttributes();
field.fieldName = fieldName;
field.fieldDisplayName = fieldJSON.getString("name");
field.isRequired = fieldJSON.getBoolean("required");
JSONObject schema = fieldJSON.getJSONObject("schema");
field.type = schema.getString("type");
try {
JSONArray allowedValues = fieldJSON.getJSONArray("allowedValues");
for (int i = 0; i < allowedValues.length(); i++) {
JSONObject allowedValueJSON = allowedValues.getJSONObject(i);
IssueTypeFieldAllowedValue allowedValue = new IssueTypeFieldAllowedValue();
allowedValue.valueID = allowedValueJSON.getString("id");
allowedValue.valueName = allowedValueJSON.getString("value");
field.allowedValues.add(allowedValue);
}
} catch (Exception ex) {}
issueTypeAttributes.fields.add(field);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return issueTypeAttributes;
}
public static class IssueTypeAttributes{
public String projectKey;
public String issueTypeID;
public String jiraProjectName;
public String jiraProjectID;
public String issueName;
public List<IssueTypeFieldAttributes> fields = new ArrayList<IssueTypeFieldAttributes>();
public String buildCURLCommand() {
String curlCommand = "curl -k -H \"Content-Type: application/json\" -D- -X POST --data \'{\"fields\": {";
curlCommand = curlCommand + "\"project\":{\"key\":\""+projectKey+"\"}, \"issuetype\": {\"id\":\""+issueTypeID+"\"}";
for(IssueTypeFieldAttributes field: fields) {
if(field.isRequired && (field.type.equals("string") || field.type.equals("array"))) {
String defaultValue = null;
try {
defaultValue = "{\"id\":\""+field.allowedValues.get(0).valueID+"\"}";
} catch (Exception ex) {
defaultValue = "\"Test\"";
}
if(field.type.equals("string")) {
curlCommand = curlCommand + ", \""+field.fieldName+"\":"+defaultValue;
} else if (field.type.equals("array")) {
curlCommand = curlCommand + ", \""+field.fieldName+"\":["+defaultValue+"]";
}
}
}
curlCommand = curlCommand + "}}\' https://"+JIRA_HOST+"/rest/api/2/issue -u "+JIRA_USERNAME;
return curlCommand;
}
public String buildJSPALink() {
String jspaLink = "https://"+JIRA_HOST+"/secure/CreateIssueDetails!init.jspa?";
jspaLink = jspaLink + "pid="+ jiraProjectID +"&issuetype="+issueTypeID;
for(IssueTypeFieldAttributes field: fields) {
if(field.isRequired && (field.type.equals("string") || field.type.equals("array"))) {
String defaultValueID = null;
try {
defaultValueID = field.allowedValues.get(0).valueID;
} catch (Exception ex) {
defaultValueID = "Test";
}
jspaLink = jspaLink + "&"+field.fieldName+"="+defaultValueID;
}
}
return jspaLink;
}
}
public static class IssueTypeFieldAttributes{
public String fieldName;
public String fieldDisplayName;
public Boolean isRequired;
public String type;
public List<IssueTypeFieldAllowedValue> allowedValues = new ArrayList<IssueTypeFieldAllowedValue>();
}
public static class IssueTypeFieldAllowedValue{
public String valueID;
public String valueName;
}
public static class SSLHandler{
/**
* Should be called right before connection
*
* Installs C:\Program Files\Java\jdk1.7.0_51\jre\lib\security\jssecacerts file
* @param host
* @throws Exception
*/
static Set<String> hostsInstalled = new HashSet<String>();
public static void setupSSLContextByInstallingCertification(String host) {
if(hostsInstalled.contains(host)) {
return;
} else {
hostsInstalled.add(host);
}
System.out.println("Installing SSLContext Certification into Java Home...");
try {
int port = 443;
char[] passphrase = "changeit".toCharArray();
char SEP = File.separatorChar;
File file = new File("jssecacerts");
if (file.isFile() == false) {
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
final List<X509Certificate> chainList = new ArrayList<X509Certificate>();
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException { }
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
chainList.clear();
if(arg0 != null) {
for (int i = 0; i < arg0.length; i++) {
chainList.add(arg0[i]);
}
}
defaultTrustManager.checkServerTrusted(arg0, arg1); }
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
socket.startHandshake();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) { }
socket.close();
if (chainList.isEmpty()) {
System.out.println("Could not obtain server certificate chain");
return;
}
System.out.println("Server sent " + chainList.size() + " certificate(s):");
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chainList.size(); i++) {
X509Certificate cert = chainList.get(i);
System.out.println
(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
}
int k = 0;
X509Certificate cert = chainList.get(k);
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
OutputStream out = new FileOutputStream(file);
ks.store(out, passphrase);
out.close();
System.out.println("Installed SSLContext Certification into Java Home: "+file.getAbsolutePath());
} catch (Exception ex) { }
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
}
}
No comments:
Post a Comment