Java tutorial
package com.pari.swim; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; import com.pari.nm.gui.guiservices.PariException; public class ImagePropertyCCOHelper { private static final Logger logger = Logger.getLogger(ImagePropertyCCOHelper.class); private static final Pattern valuePattern = Pattern.compile(".*<option.*selected.*>(.*)<.*"); private static final Pattern featValuePattern = Pattern.compile(".*<A class=.*&featureId=.*>(.*)<.*"); private static final Pattern minValuesPattern = Pattern.compile("\\s*([0-9]+)\\s*/\\s*([0-9]+).*"); /** * populateImagePropertiesFromCCO * * @param imageName * imageName * * @return DOCUMENT ME! * * @throws PariException * PariException */ public static SoftwareImage populateImagePropertiesFromCCO(String imageName) throws PariException { // This URL need to be changed once NCCM use SWIM/BSD api provide by CCO. String url = "http://tools.cisco.com/ITDIT/CFN/jsp/Image.data?_dc=1360865397887&imageName="; url += imageName; url += "&ostype=?platformid=&mrel=&release=&fsetid=&productCode=&page=1&start=0&limit=50"; SoftwareImage image = new SoftwareImage(); populateImagePropertiesFromCCOInternal(image, imageName, url, true, true); return image; } private static void populateImagePropertiesFromCCOInternal(SoftwareImage image, String imageName, String url, boolean populateVersion, boolean populatePforms) throws PariException { HttpClient httpClient = new HttpClient(); GetMethod method = new GetMethod(url); method.setFollowRedirects(true); try { httpClient.executeMethod(method); int statuscode = method.getStatusCode(); if (statuscode != HttpStatus.SC_OK) { throw new PariException(-1, "Unable to connect to cisco.com to get image properites for image: " + imageName + " Status: " + method.getStatusText()); } populateImagePropertiesFromHTTPOutput(method.getResponseBodyAsStream(), image, imageName, populateVersion, populatePforms); } catch (PariException pex) { logger.error("Pari Exception while getting image properties for image: " + imageName, pex); throw pex; } catch (Exception ex) { logger.error("Exception while getting image properties for image: " + imageName, ex); throw new PariException(-1, "Error while getting image properties from www.cisco.com for image: " + imageName); } } /** * populateImagePropertiesFromHTTPOutput * * @param inputStream * responseBodyAsString * @param image * image * @param imageName * imageName * @param populateVersion * populateVersion * @param populatePforms * populatePforms * * @throws PariException * PariException * @throws IOException */ public static void populateImagePropertiesFromHTTPOutput(InputStream inputStream, SoftwareImage image, String imageName, boolean populateVersion, boolean populatePforms) throws PariException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } String lines[] = sb.toString().split("\\n"); String pageType = getHTMLPageType(lines); if (pageType.equals("no_image")) { throw new PariException(-1, "Unable to obtain any information from www.cisco.com"); } if (pageType.equals("illegal")) { throw new PariException(-1, "Unable to parse the output from www.cisco.com"); } if (pageType.equals("table_type")) { populateImagePropsType1(lines, image, imageName); return; } if (pageType.equals("single_type")) { populateImagePropsType2(lines, image, populateVersion, populatePforms); return; } if (pageType.equals("single_record")) { populateImagePropsType3(lines, image, imageName); } } private static void populateImagePropsType2(String[] lines, SoftwareImage image, boolean populateVersion, boolean populatePforms) { boolean insideReleases = false; boolean insidePforms = false; boolean insideMinVals = false; String release = null; Set<String> pformSet = new LinkedHashSet<String>(); Set<String> featSet = new LinkedHashSet<String>(); int minRAM = -1; int minFlash = -1; Boolean deferred = false; Boolean psirt = false; for (String line : lines) { if (!insideReleases && populateVersion && (line.contains("All Releases"))) { insideReleases = true; insidePforms = false; insideMinVals = false; continue; } if (!insidePforms && populatePforms && line.contains("All Platforms")) { insidePforms = true; insideReleases = false; insideMinVals = false; continue; } if (!insideMinVals && line.contains("RAM / Min Flash")) { insideMinVals = true; insidePforms = false; insideReleases = false; } if (insideReleases && line.contains("selected")) { Matcher m = valuePattern.matcher(line); if (m.matches()) { release = m.group(1).trim(); insideReleases = false; } } if (insidePforms && line.contains("selected")) { Matcher m = valuePattern.matcher(line); if (m.matches()) { pformSet.add(m.group(1).trim()); insidePforms = false; } } if (insideMinVals) { Matcher m = minValuesPattern.matcher(line); if (m.matches()) { String val1Str = m.group(1); String val2Str = m.group(2); try { minRAM = Integer.parseInt(val1Str); } catch (Exception ex) { } try { minFlash = Integer.parseInt(val2Str); } catch (Exception e) { } insideMinVals = false; } } if (line.toLowerCase().contains("deferred image")) { deferred = true; } if (line.toLowerCase().contains("has software advisories")) { psirt = true; } if (line.contains("featureId")) { Matcher m = featValuePattern.matcher(line); if (m.matches()) { featSet.add(m.group(1).trim()); continue; } } } if ((release != null) && populateVersion && (image.getOsVersion() == null)) { image.setOsVersion(release); } if (populatePforms && (pformSet != null) && !pformSet.isEmpty()) { String[] existingPforms = image.getApplicablePlatforms(); if (existingPforms != null) { for (String pf : existingPforms) { pformSet.add(pf); } } image.setApplicablePlatforms(pformSet.toArray(new String[pformSet.size()])); } if ((featSet != null) && !featSet.isEmpty()) { String[] existingFeats = image.getFeatureList(); if (existingFeats != null) { for (String f : existingFeats) { pformSet.add(f); } } image.setFeatureList(featSet.toArray(new String[featSet.size()])); } if ((minRAM >= 0) && (image.getMinRAMSize() < 0)) { image.setMinRAMSize(minRAM); } if ((minFlash >= 0) && (image.getMinFlashSize() < 0)) { image.setMinFlashSize(minFlash); } image.setDeferred(deferred); image.setHasAdvisories(psirt); } private static void populateImagePropsType1(String[] lines, SoftwareImage image, String imageName) throws PariException { boolean insideTable = false; boolean insideCorrectTable = false; boolean insideTr = false; boolean insideTd = false; int releaseCol = -1; int pformCol = -1; int currentCol = 0; boolean pformFound = false; boolean rlsFound = false; Set<String> pformSet = new HashSet<String>(); String nextLink = null; for (String line : lines) { String lowerLine = line.toLowerCase(); if ((nextLink == null) && lowerLine.contains("href") && line.contains(imageName)) { Pattern p = Pattern.compile(".*<A .*HREF=\"(.*Dispatch.*HDDMPlatFamDet.*)\">.*</A>.*"); Matcher m = p.matcher(line); if (m.matches()) { nextLink = m.group(1); if (nextLink.startsWith("/")) { nextLink = "http://tools.cisco.com" + nextLink; } else { nextLink = "http://tools.cisco.com/" + nextLink; } } } if (!insideTable) { if (lowerLine.contains("<table")) { if (!lowerLine.matches(".*/.*table>")) { insideTable = true; } } continue; } else { if (lowerLine.contains("</table")) { insideTable = false; if (insideCorrectTable) { break; } insideTr = false; insideTd = false; currentCol = -1; continue; } if (!insideTr) { if (lowerLine.contains("<tr")) { if (!lowerLine.matches(".*/.*tr>")) { insideTr = true; currentCol = -1; } } continue; } else { if (lowerLine.contains("</tr")) { insideTr = false; insideTd = false; currentCol = -1; continue; } if (!insideTd) { if (lowerLine.contains("<td")) { currentCol++; if (line.contains("Release")) { releaseCol = currentCol; rlsFound = true; } if (line.contains("Platform")) { pformCol = currentCol; pformFound = true; } if (!lowerLine.matches(".*\\/.*td>")) { insideTd = true; } } } else { if (lowerLine.contains("</td")) { if (lowerLine.matches(".*/td>.*<td.*")) { insideTd = true; currentCol++; } else { insideTd = false; } } else if (insideCorrectTable) { if (currentCol == releaseCol) { image.setOsVersion(line.trim()); } else if (currentCol == pformCol) { pformSet.add(line.trim().toLowerCase()); } } if (line.contains("Release")) { releaseCol = currentCol; rlsFound = true; } if (line.contains("Platform")) { pformCol = currentCol; pformFound = true; } } if (rlsFound && pformFound) { insideCorrectTable = true; } } } } if (!pformSet.isEmpty()) { image.setApplicablePlatforms(pformSet.toArray(new String[pformSet.size()])); } if (nextLink != null) { populateImagePropertiesFromCCOInternal(image, imageName, nextLink, false, false); } } // Pasrsing CCO output(From Feature Navigator ) : {"totalCount": // "1","imageList":{"image":[{"imageId":1577323,"image":"c3750-ipbasek9-mz.122-53.SE1.bin","platformId":"217","releaseId":"30589","platform":"CAT3750", /* * "trainName":"12.2SE","featureSetId":"448","featureSet":"IP BASE","dram":"128","flash":"16","productCode":"null", * "releaseNumber":"12.2(53)SE1","softwareType":"null","deploymentStatus":"ED","osType":"IOS", * "baseImageName":"c3750-ipbasek9-mz" * ,"orderable":"false","swAdvised":"true","swDeffered":"false","defferedUrl":"null", * "swAdvUrl":"http:\/\/www.cisco.com\/web\/software\/DefTracker\/280805679\/SA\/ac104481.html", * "swUnavailable":"false","swLicensed":"false","eolStatus":"false"}]}} */ private static void populateImagePropsType3(String[] lines, SoftwareImage image, String imageName) throws PariException { // int index; String line; if (lines.length > 0) { line = lines[0]; } else { logger.error("Pari Exception while populating Image properties for image: " + imageName); throw new PariException(-1, "Pari Exception while populating Image properties for image: " + imageName); } if (line == null) { logger.error("Pari Exception while populating Image properties for image: " + imageName); throw new PariException(-1, "Pari Exception while populating Image properties for image: " + imageName); } String imageDets = line.substring(line.indexOf("[") + 1, line.indexOf("]")); imageDets = imageDets.substring(imageDets.indexOf("{") + 1, imageDets.indexOf("}")); StringTokenizer st = new StringTokenizer(imageDets, ","); while (st.hasMoreElements()) { String token = (String) st.nextElement(); String value; if (token.contains("osType")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setOsName(value); } else if (token.contains("releaseNumber")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setOsVersion(value); } else if (token.contains("dram")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setMinRAMSize(Long.valueOf(value)); } else if (token.contains("flash")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setMinFlashSize(Long.valueOf(value)); } else if (token.contains("platform")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); String[] applicablePlatforms = { value }; image.setApplicablePlatforms(applicablePlatforms); } else if (token.contains("swAdvised")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setHasAdvisories(Boolean.valueOf(value)); } else if (token.contains("swDeffered")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setDeferred(Boolean.valueOf(value)); } else if (token.contains("baseImageName")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); image.setBuildName(value); } else if (token.contains("featureSet")) { value = token.substring(token.indexOf(":") + 2, token.lastIndexOf("\"")); String[] featureList = { value }; image.setFeatureList(featureList); } } } private static String getHTMLPageType(String[] lines) { boolean insideTd = false; boolean imageNameFound = false; boolean releaseFound = false; boolean platformFound = false; for (String line : lines) { /* * {"totalCount": * "1","imageList":{"image":[{"imageId":1577323,"image":"c3750-ipbasek9-mz.122-53.SE1.bin","platformId" * :"217","releaseId":"30589", * "platform":"CAT3750","trainName":"12.2SE","featureSetId":"448","featureSet":"IP BASE" * ,"dram":"128","flash":"16","productCode":"null", * "releaseNumber":"12.2(53)SE1","softwareType":"null","deploymentStatus" * :"ED","osType":"IOS","baseImageName":"c3750-ipbasek9-mz","orderable":"false", * "swAdvised":"true","swDeffered":"false","defferedUrl":"null","swAdvUrl": * "http:\/\/www.cisco.com\/web\/software\/DefTracker\/280805679\/SA\/ac104481.html", * "swUnavailable":"false", "swLicensed":"false","eolStatus":"false"}]}} */ if (line.contains("[") && line.contains("]") && line.contains("image")) { return "single_record"; } if (line.contains("The Image Name you entered does not match") || line.contains("No records found")) { return "no_image"; } if (line.contains("Your Selections:")) { return "single_type"; } if (line.matches(".*<td.*")) { if (line.contains("Image Name")) { imageNameFound = true; } else if (line.contains("Release")) { releaseFound = true; } else if (line.contains("Platform")) { platformFound = true; } if (!line.matches("/.*>")) { insideTd = true; } } else if (insideTd) { if (line.contains("Image Name")) { imageNameFound = true; } else if (line.contains("Release")) { releaseFound = true; } else if (line.contains("Platform")) { platformFound = true; } if (line.matches("/.*>")) { insideTd = false; } } if (imageNameFound && releaseFound && platformFound) { return "table_type"; } } return "illegal"; } }