Java tutorial
/******************************************************************************* * Copyright 2010 David Harrison. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.sfs.jbtimporter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * The Class JBTProcessor. */ public class JBTProcessor { /** The username. */ private String username; /** The password. */ private String password; /** The base url. */ private String baseUrl = "http://localhost:8080/"; /** The export base. */ private String exportBase; /** The xslt filename. */ private String xsltFileName; /** The revert flag. */ private boolean revert = false; /** The http client. */ private HttpClient httpClient; private Map<Character, String> specialCharacterMap; /** The jira key path. */ private final String jiraKeyPath = "secure/admin/util/JellyRunner!default.jspa"; /** The jira runner path. */ private final String jiraRunnerPath = "secure/admin/util/JellyRunner.jspa"; /** * Instantiates a new jBT processor. * * @param usernameValue the username * @param passwordValue the password * @param baseUrlValue the base url * @param exportBaseValue the export base * @param xsltFileNameValue the xslt file name * @param revertValue the revert flag * @throws JBTException the jBT exception */ public JBTProcessor(final String usernameValue, final String passwordValue, final String baseUrlValue, final String exportBaseValue, final String xsltFileNameValue, final boolean revertValue) throws JBTException { if (StringUtils.isBlank(exportBaseValue)) { throw new JBTException("A valid export directory is required"); } // If the XSLT filename is not supplied and revert flag not set. // Check to see if a user and password has been defined. if (StringUtils.isNotBlank(xsltFileNameValue) || revertValue == true) { // In these two cases no further validation needs to be performed } else { if (StringUtils.isBlank(usernameValue)) { throw new JBTException("A valid username is required"); } if (StringUtils.isBlank(passwordValue)) { throw new JBTException("A valid password is required"); } } // Set the configuration parameters this.username = usernameValue; this.password = passwordValue; this.xsltFileName = xsltFileNameValue; this.revert = revertValue; if (StringUtils.isNotBlank(exportBaseValue)) { if (exportBaseValue.endsWith("/")) { this.exportBase = exportBaseValue; } else { this.exportBase = exportBaseValue + "/"; } } if (StringUtils.isNotBlank(baseUrlValue)) { if (baseUrlValue.endsWith("/")) { this.baseUrl = baseUrlValue; } else { this.baseUrl = baseUrlValue + "/"; } } // Setup the HttpClient to handle connections this.httpClient = new HttpClient(); // Proxy configuration String proxyHost = System.getProperty("http.proxyHost);"); String proxyPortString = System.getProperty("http.proxyPort"); int proxyPort = -1; if (this.getBaseUrl().startsWith("https")) { proxyHost = System.getProperty("https.proxyHost"); proxyPortString = System.getProperty("https.proxyPort"); } try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException nfe) { proxyPort = -1; } if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { this.httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } this.specialCharacterMap = this.initialiseSpecialCharacterMap(); } /** * Gets the username. * * @return the username */ public final String getUsername() { return this.username; } /** * Gets the password. * * @return the password */ public final String getPassword() { return this.password; } /** * Gets the base url. * * @return the base url */ public final String getBaseUrl() { return this.baseUrl; } /** * Gets the export base. * * @return the export base */ public final String getExportBase() { return this.exportBase; } /** * Gets the xslt filename. * * @return the xslt file name */ public final String getXsltFileName() { return this.xsltFileName; } /** * Gets the revert flag. * * @return the revert flag */ public final boolean getRevert() { return this.revert; } /** * Gets the special character map. * * @return the special character map */ public final Map<Character, String> getSpecialCharacterMap() { return this.specialCharacterMap; } /** * Gets the Jira security key. * * @return the jira security key * @throws IOException Signals that an I/O exception has occurred. */ public final String getKey() throws IOException { String key = ""; final String jellyUrl = this.getBaseUrl() + this.jiraKeyPath; final PostMethod postMethod = new PostMethod(jellyUrl); final NameValuePair[] data = { new NameValuePair("os_username", this.getUsername()), new NameValuePair("os_password", this.getPassword()) }; final String raw = postData(postMethod, data); // Get the value of the alt_token input field as the key if (raw.indexOf("name=\"atl_token\"") > 0) { final int charcount = 16; final int valuelength = 20; // Value returned String result = raw.substring(raw.indexOf("name=\"atl_token\"") + charcount, raw.length()); result = result.substring(result.indexOf("\""), result.indexOf("\"") + valuelength); key = result.substring(result.indexOf("\"") + 1, result.lastIndexOf("\"")); } return key; } /** * Passes the XML to Jira's Jelly runner. * * @param key the key * @param xmldata the xmldata * @return the result from the jelly runner * @throws IOException Signals that an I/O exception has occurred. */ public final String importXML(final String key, final String xmldata) throws IOException { String result = ""; final String runnerUrl = this.getBaseUrl() + this.jiraRunnerPath; PostMethod postMethod = new PostMethod(runnerUrl); NameValuePair[] data = { new NameValuePair("os_username", this.getUsername()), new NameValuePair("os_password", this.getPassword()), new NameValuePair("atl_token", key), new NameValuePair("file", ""), new NameValuePair("script", xmldata) }; final String raw = postData(postMethod, data); if (raw.indexOf("xmlns:j='jelly:core'") > 0 || raw.indexOf("xmlns:j=\"jelly:core\"") > 0) { // The Jelly script has successfully run, capture outcome final int precount = 24; final int postcount = 4; // Value returned String startResult = raw.substring(raw.indexOf("xmlns:j='jelly:core'") + precount, raw.length()); result = startResult.substring(0, startResult.indexOf("/JiraJelly") - postcount); } if (raw.indexOf("xmlns:j="jelly:core"") > 0) { // The Jelly script has been run, capture outcome final int precount = 34; final int postcount = 4; // Value returned String startResult = raw.substring(raw.indexOf("xmlns:j="jelly:core"") + precount, raw.length()); result = startResult.substring(0, startResult.indexOf("/JiraJelly") - postcount); } if (raw.indexOf("id=\"scriptException\"") > 0) { // A script exception has been thrown. i.e. The script couldn't be run final int precount = 203; final int postcount = 1; // Value returned String startResult = raw.substring(raw.indexOf("id=\"scriptException\"") + precount, raw.length()); result = startResult.substring(0, startResult.indexOf("/div") - postcount); } return reformatHtml(result); } /** * Parses the xml index. * * @return the list * @throws SAXException the SAX exception * @throws IOException Signals that an I/O exception has occurred. */ public final List<JBTIssue> parseXmlIndex() throws SAXException, IOException { final List<JBTIssue> issues = new ArrayList<JBTIssue>(); final File file = new File(this.getExportBase() + "index.xml"); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new SAXException("Error configuring XML parser: " + pce.getMessage()); } final Document doc = db.parse(file); doc.getDocumentElement().normalize(); final NodeList bugList = doc.getElementsByTagName("bug"); for (int s = 0; s < bugList.getLength(); s++) { final Node bugNode = bugList.item(s); if (bugNode.getNodeType() == Node.ELEMENT_NODE) { final JBTIssue issue = new JBTIssue(this); final Element bugElmnt = (Element) bugNode; issue.setId(bugElmnt.getAttribute("id")); issue.setBase(bugElmnt.getAttribute("base")); NodeList fileElmntLst = bugNode.getChildNodes(); for (int t = 0; t < fileElmntLst.getLength(); t++) { final Node fileNode = fileElmntLst.item(t); if (fileNode.getNodeType() == Node.ELEMENT_NODE) { final Element fileElmnt = (Element) fileNode; final NodeList chldFile = fileElmnt.getChildNodes(); final Node filenameNode = (Node) chldFile.item(0); if (StringUtils.equals(fileElmnt.getAttribute("primary"), "true")) { issue.setFileName(filenameNode.getNodeValue()); // Add the issue to the array issues.add(issue); } } } } } return issues; } /** * Load xml data from the supplied file. * * @param filepath the filepath * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public final String loadXmlDataFile(final String filepath) throws IOException { StringBuffer contents = new StringBuffer(); Reader reader = new InputStreamReader(new FileInputStream(filepath), "UTF-8"); int ch; do { ch = reader.read(); if (ch != -1) { contents.append((char) ch); } } while (ch != -1); reader.close(); return contents.toString(); } /** * Post the data to the service. * * @param postMethod the post method * @param data the data * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private String postData(final PostMethod postMethod, final NameValuePair[] data) throws IOException { final StringBuffer raw = new StringBuffer(); postMethod.setRequestBody(data); // Execute the post request httpClient.executeMethod(postMethod); try { Reader reader = new InputStreamReader(postMethod.getResponseBodyAsStream(), postMethod.getResponseCharSet()); // consume the response entity int dataread = reader.read(); while (dataread != -1) { char theChar = (char) dataread; raw.append(theChar); dataread = reader.read(); } } finally { postMethod.releaseConnection(); } return raw.toString(); } /** * Reformat html. * * @param input the input * @return the string */ private String reformatHtml(final String input) { String result = StringUtils.replace(input, "<BR>", "\n"); result = StringUtils.replace(result, "<b>", ""); result = StringUtils.replace(result, "</b>", ""); result = StringUtils.replace(result, " ", " "); result = StringUtils.replace(result, ">", ">"); result = StringUtils.replace(result, "<", "<"); result = StringUtils.replace(result, """, "\""); result = StringUtils.replace(result, ".<br/>", ""); result = StringUtils.replace(result, ".<BR/>", ""); result = StringUtils.replace(result, ".<br>", ""); result = StringUtils.replace(result, ".<BR>", ""); return result; } /** * Gets the special character map. * * @return the special character map */ private final Map<Character, String> initialiseSpecialCharacterMap() { final Map<Character, String> map = new HashMap<Character, String>(); map.put(new Character('\u0100'), "Ā"); map.put(new Character('\u0101'), "ā"); map.put(new Character('\u0102'), "Ă"); map.put(new Character('\u0103'), "ă"); map.put(new Character('\u0104'), "Ą"); map.put(new Character('\u0105'), "ą"); map.put(new Character('\u0106'), "Ć"); map.put(new Character('\u0107'), "ć"); map.put(new Character('\u0108'), "Ĉ"); map.put(new Character('\u0108'), "ĉ"); map.put(new Character('\u010C'), "Č"); map.put(new Character('\u010D'), "č"); map.put(new Character('\u010E'), "Ď"); map.put(new Character('\u010F'), "ď"); map.put(new Character('\u0110'), "Đ"); map.put(new Character('\u0111'), "đ"); map.put(new Character('\u0112'), "Ē"); map.put(new Character('\u0113'), "ē"); map.put(new Character('\u0118'), "Ę"); map.put(new Character('\u0119'), "ę"); map.put(new Character('\u011A'), "Ě"); map.put(new Character('\u011B'), "ě"); map.put(new Character('\u011C'), "Ĝ"); map.put(new Character('\u011D'), "ĝ"); map.put(new Character('\u011E'), "Ğ"); map.put(new Character('\u011F'), "ğ"); map.put(new Character('\u0122'), "Ģ"); map.put(new Character('\u0123'), "ģ"); map.put(new Character('\u0124'), "Ĥ"); map.put(new Character('\u0125'), "ĥ"); map.put(new Character('\u012A'), "Ī"); map.put(new Character('\u012B'), "ī"); map.put(new Character('\u0130'), "İ"); map.put(new Character('\u0131'), "ı"); map.put(new Character('\u0134'), "Ĵ"); map.put(new Character('\u0135'), "ĵ"); map.put(new Character('\u0136'), "Ķ"); map.put(new Character('\u0137'), "ķ"); map.put(new Character('\u0139'), "Ĺ"); map.put(new Character('\u013A'), "ĺ"); map.put(new Character('\u013B'), "Ļ"); map.put(new Character('\u013C'), "ļ"); map.put(new Character('\u013D'), "Ľ"); map.put(new Character('\u013E'), "ľ"); map.put(new Character('\u0141'), "Ł"); map.put(new Character('\u0142'), "ł"); map.put(new Character('\u0143'), "Ń"); map.put(new Character('\u0144'), "ń"); map.put(new Character('\u0145'), "Ņ"); map.put(new Character('\u0146'), "ņ"); map.put(new Character('\u0147'), "Ň"); map.put(new Character('\u0148'), "ň"); map.put(new Character('\u0150'), "Ő"); map.put(new Character('\u0151'), "ő"); map.put(new Character('\u0154'), "Ŕ"); map.put(new Character('\u0155'), "ŕ"); map.put(new Character('\u0156'), "Ŗ"); map.put(new Character('\u0157'), "ŗ"); map.put(new Character('\u0158'), "Ř"); map.put(new Character('\u0159'), "ř"); map.put(new Character('\u015A'), "Ś"); map.put(new Character('\u015B'), "ś"); map.put(new Character('\u015C'), "Ŝ"); map.put(new Character('\u015D'), "ŝ"); map.put(new Character('\u015E'), "Ş"); map.put(new Character('\u015F'), "ş"); map.put(new Character('\u0160'), "Š"); map.put(new Character('\u0161'), "š"); map.put(new Character('\u0162'), "Ţ"); map.put(new Character('\u0163'), "ţ"); map.put(new Character('\u0164'), "Ť"); map.put(new Character('\u0165'), "ť"); map.put(new Character('\u016A'), "Ū"); map.put(new Character('\u016B'), "ū"); map.put(new Character('\u016C'), "Ŭ"); map.put(new Character('\u016D'), "ŭ"); map.put(new Character('\u016E'), "Ů"); map.put(new Character('\u016F'), "ů"); map.put(new Character('\u0170'), "Ű"); map.put(new Character('\u0171'), "ű"); map.put(new Character('\u0178'), "Ÿ"); map.put(new Character('\u0179'), "Ź"); map.put(new Character('\u017A'), "ź"); map.put(new Character('\u017B'), "Ż"); map.put(new Character('\u017C'), "ż"); map.put(new Character('\u017D'), "Ž"); map.put(new Character('\u017E'), "ž"); map.put(new Character('\u2116'), "№"); map.put(new Character('\u00C1'), "Á"); map.put(new Character('\u00E1'), "á"); map.put(new Character('\u00C2'), "Â"); map.put(new Character('\u00E2'), "â"); map.put(new Character('\u00C6'), "Æ"); map.put(new Character('\u00E6'), "æ"); map.put(new Character('\u00E0'), "à"); map.put(new Character('\u00C0'), "À"); map.put(new Character('\u00C5'), "Å"); map.put(new Character('\u00E5'), "å"); map.put(new Character('\u00C3'), "Ã"); map.put(new Character('\u00E3'), "ã"); map.put(new Character('\u00C4'), "Ä"); map.put(new Character('\u00E4'), "ä"); map.put(new Character('\u2022'), "•"); map.put(new Character('\u00C7'), "Ç"); map.put(new Character('\u00E7'), "ç"); map.put(new Character('\u00A9'), "©"); map.put(new Character('\u2020'), "†"); map.put(new Character('\u00B0'), "°"); map.put(new Character('\u00C9'), "É"); map.put(new Character('\u00E9'), "é"); map.put(new Character('\u00CA'), "Ê"); map.put(new Character('\u00EA'), "ê"); map.put(new Character('\u00C8'), "È"); map.put(new Character('\u00E8'), "è"); map.put(new Character('\u00D0'), "Ð"); map.put(new Character('\u00F0'), "ð"); map.put(new Character('\u00CB'), "Ë"); map.put(new Character('\u00EB'), "ë"); map.put(new Character('\u20AC'), "€"); map.put(new Character('\u00CD'), "Í"); map.put(new Character('\u00ED'), "í"); map.put(new Character('\u00CE'), "Î"); map.put(new Character('\u00EE'), "î"); map.put(new Character('\u00A1'), "¡"); map.put(new Character('\u00CC'), "Ì"); map.put(new Character('\u00EC'), "ì"); map.put(new Character('\u00BF'), "¿"); map.put(new Character('\u00CF'), "Ï"); map.put(new Character('\u00EF'), "ï"); map.put(new Character('\u00AB'), "«"); map.put(new Character('\u2014'), "—"); map.put(new Character('\u00B5'), "µ"); map.put(new Character('\u00B7'), "·"); map.put(new Character('\u2013'), "–"); map.put(new Character('\u00D1'), "Ñ"); map.put(new Character('\u00F1'), "ñ"); map.put(new Character('\u00D3'), "Ó"); map.put(new Character('\u00F3'), "ó"); map.put(new Character('\u00D4'), "Ô"); map.put(new Character('\u00F4'), "ô"); map.put(new Character('\u0152'), "Œ"); map.put(new Character('\u0153'), "œ"); map.put(new Character('\u00D2'), "Ò"); map.put(new Character('\u00F2'), "ò"); map.put(new Character('\u00AA'), "ª"); map.put(new Character('\u00BA'), "º"); map.put(new Character('\u00D8'), "Ø"); map.put(new Character('\u00F8'), "ø"); map.put(new Character('\u00D5'), "Õ"); map.put(new Character('\u00F5'), "õ"); map.put(new Character('\u00D6'), "Ö"); map.put(new Character('\u00F6'), "ö"); map.put(new Character('\u00A3'), "£"); map.put(new Character('\u00BB'), "»"); map.put(new Character('\u00AE'), "®"); map.put(new Character('\u00DF'), "ß"); map.put(new Character('\u00DE'), "Þ"); map.put(new Character('\u00FE'), "þ"); map.put(new Character('\u00DA'), "Ú"); map.put(new Character('\u00FA'), "ú"); map.put(new Character('\u00DB'), "Û"); map.put(new Character('\u00FB'), "û"); map.put(new Character('\u00D9'), "Ù"); map.put(new Character('\u00F9'), "ù"); map.put(new Character('\u00F6'), "¨"); map.put(new Character('\u00DC'), "Ü"); map.put(new Character('\u00FC'), "ü"); map.put(new Character('\u00DD'), "Ý"); map.put(new Character('\u00FD'), "ý"); map.put(new Character('\u00FF'), "ÿ"); return map; } }