Coverage Report - org.owasp.dependencycheck.data.central.CentralSearch
 
Classes in this File Line Coverage Branch Coverage Complexity
CentralSearch
83%
51/61
83%
20/24
10
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2014 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.central;
 19  
 
 20  
 import java.io.FileNotFoundException;
 21  
 import java.io.IOException;
 22  
 import java.net.HttpURLConnection;
 23  
 import java.net.URL;
 24  
 import java.util.ArrayList;
 25  
 import java.util.List;
 26  
 import javax.xml.parsers.DocumentBuilder;
 27  
 import javax.xml.parsers.DocumentBuilderFactory;
 28  
 import javax.xml.xpath.XPath;
 29  
 import javax.xml.xpath.XPathConstants;
 30  
 import javax.xml.xpath.XPathFactory;
 31  
 import org.owasp.dependencycheck.data.nexus.MavenArtifact;
 32  
 import org.owasp.dependencycheck.utils.Settings;
 33  
 import org.owasp.dependencycheck.utils.URLConnectionFactory;
 34  
 import org.slf4j.Logger;
 35  
 import org.slf4j.LoggerFactory;
 36  
 import org.w3c.dom.Document;
 37  
 import org.w3c.dom.NodeList;
 38  
 
 39  
 /**
 40  
  * Class of methods to search Maven Central via Central.
 41  
  *
 42  
  * @author colezlaw
 43  
  */
 44  
 public class CentralSearch {
 45  
 
 46  
     /**
 47  
      * The URL for the Central service
 48  
      */
 49  
     private final URL rootURL;
 50  
 
 51  
     /**
 52  
      * Whether to use the Proxy when making requests
 53  
      */
 54  
     private boolean useProxy;
 55  
 
 56  
     /**
 57  
      * Used for logging.
 58  
      */
 59  1
     private static final Logger LOGGER = LoggerFactory.getLogger(CentralSearch.class);
 60  
 
 61  
     /**
 62  
      * Creates a NexusSearch for the given repository URL.
 63  
      *
 64  
      * @param rootURL the URL of the repository on which searches should execute. Only parameters are added to this (so it should
 65  
      * end in /select)
 66  
      */
 67  5
     public CentralSearch(URL rootURL) {
 68  5
         this.rootURL = rootURL;
 69  5
         if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)) {
 70  0
             useProxy = true;
 71  0
             LOGGER.debug("Using proxy");
 72  
         } else {
 73  5
             useProxy = false;
 74  5
             LOGGER.debug("Not using proxy");
 75  
         }
 76  5
     }
 77  
 
 78  
     /**
 79  
      * Searches the configured Central URL for the given sha1 hash. If the artifact is found, a <code>MavenArtifact</code> is
 80  
      * populated with the GAV.
 81  
      *
 82  
      * @param sha1 the SHA-1 hash string for which to search
 83  
      * @return the populated Maven GAV.
 84  
      * @throws IOException if it's unable to connect to the specified repository or if the specified artifact is not found.
 85  
      */
 86  
     public List<MavenArtifact> searchSha1(String sha1) throws IOException {
 87  5
         if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) {
 88  2
             throw new IllegalArgumentException("Invalid SHA1 format");
 89  
         }
 90  
 
 91  3
         final URL url = new URL(rootURL + String.format("?q=1:\"%s\"&wt=xml", sha1));
 92  
 
 93  3
         LOGGER.debug("Searching Central url {}", url);
 94  
 
 95  
         // Determine if we need to use a proxy. The rules:
 96  
         // 1) If the proxy is set, AND the setting is set to true, use the proxy
 97  
         // 2) Otherwise, don't use the proxy (either the proxy isn't configured,
 98  
         // or proxy is specifically set to false)
 99  3
         final HttpURLConnection conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
 100  
 
 101  3
         conn.setDoOutput(true);
 102  
 
 103  
         // JSON would be more elegant, but there's not currently a dependency
 104  
         // on JSON, so don't want to add one just for this
 105  3
         conn.addRequestProperty("Accept", "application/xml");
 106  3
         conn.connect();
 107  
 
 108  3
         if (conn.getResponseCode() == 200) {
 109  3
             boolean missing = false;
 110  
             try {
 111  
                 final DocumentBuilder builder = DocumentBuilderFactory
 112  3
                         .newInstance().newDocumentBuilder();
 113  3
                 final Document doc = builder.parse(conn.getInputStream());
 114  3
                 final XPath xpath = XPathFactory.newInstance().newXPath();
 115  3
                 final String numFound = xpath.evaluate("/response/result/@numFound", doc);
 116  3
                 if ("0".equals(numFound)) {
 117  1
                     missing = true;
 118  
                 } else {
 119  2
                     final List<MavenArtifact> result = new ArrayList<MavenArtifact>();
 120  2
                     final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET);
 121  5
                     for (int i = 0; i < docs.getLength(); i++) {
 122  3
                         final String g = xpath.evaluate("./str[@name='g']", docs.item(i));
 123  3
                         LOGGER.trace("GroupId: {}", g);
 124  3
                         final String a = xpath.evaluate("./str[@name='a']", docs.item(i));
 125  3
                         LOGGER.trace("ArtifactId: {}", a);
 126  3
                         final String v = xpath.evaluate("./str[@name='v']", docs.item(i));
 127  3
                         NodeList atts = (NodeList) xpath.evaluate("./arr[@name='ec']/str", docs.item(i), XPathConstants.NODESET);
 128  3
                         boolean pomAvailable = false;
 129  3
                         boolean jarAvailable = false;
 130  14
                         for (int x = 0; x < atts.getLength(); x++) {
 131  11
                             final String tmp = xpath.evaluate(".", atts.item(x));
 132  11
                             if (".pom".equals(tmp)) {
 133  3
                                 pomAvailable = true;
 134  8
                             } else if (".jar".equals(tmp)) {
 135  3
                                 jarAvailable = true;
 136  
                             }
 137  
                         }
 138  
 
 139  3
                         atts = (NodeList) xpath.evaluate("./arr[@name='tags']/str", docs.item(i), XPathConstants.NODESET);
 140  3
                         boolean useHTTPS = false;
 141  21
                         for (int x = 0; x < atts.getLength(); x++) {
 142  18
                             final String tmp = xpath.evaluate(".", atts.item(x));
 143  18
                             if ("https".equals(tmp)) {
 144  0
                                 useHTTPS = true;
 145  
                             }
 146  
                         }
 147  
 
 148  3
                         LOGGER.trace("Version: {}", v);
 149  3
                         result.add(new MavenArtifact(g, a, v, jarAvailable, pomAvailable, useHTTPS));
 150  
                     }
 151  
 
 152  2
                     return result;
 153  
                 }
 154  0
             } catch (Throwable e) {
 155  
                 // Anything else is jacked up XML stuff that we really can't recover
 156  
                 // from well
 157  0
                 throw new IOException(e.getMessage(), e);
 158  1
             }
 159  
 
 160  1
             if (missing) {
 161  1
                 throw new FileNotFoundException("Artifact not found in Central");
 162  
             }
 163  0
         } else {
 164  0
             LOGGER.debug("Could not connect to Central received response code: {} {}",
 165  0
                 conn.getResponseCode(), conn.getResponseMessage());
 166  0
             throw new IOException("Could not connect to Central");
 167  
         }
 168  
 
 169  0
         return null;
 170  
     }
 171  
 }