コード例 #1
29
 /** Check if an URL is relative to another URL. */
 public static boolean relativeURL(URL url1, URL url2) {
   return ((url1.getProtocol() == null && url2.getProtocol() == null)
           || url1.getProtocol().equals(url2.getProtocol()))
       && ((url1.getAuthority() == null && url2.getAuthority() == null)
           || url1.getAuthority().equals(url2.getAuthority()))
       && ((url1.getPath() == null && url2.getPath() == null)
           || url2.getPath().startsWith(url1.getPath()));
 }
コード例 #2
0
  /**
   * This method fixes incorrect authority attribute that is set by JDK when UNC is used in
   * classpath. See JDK bug #6585937 and GlassFish issue #3209 for more details.
   */
  private static URL fixUNC(URL url)
      throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {
    String protocol = url.getProtocol();
    if (!"file".equalsIgnoreCase(protocol)) {
      return url;
    }
    String authority = url.getAuthority();
    String file = url.getFile();
    if (authority != null) {
      AbstractSessionLog.getLog()
          .finer(
              "fixUNC: before fixing: url = "
                  + url
                  + ", authority = "
                  + authority
                  + ", file = "
                  + file);
      assert (url.getPort() == -1);

      // See GlassFish issue https://glassfish.dev.java.net/issues/show_bug.cgi?id=3209 and
      // JDK issue http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6585937
      // When there is UNC path in classpath, the classloader.getResource
      // returns a file: URL with an authority component in it.
      // The URL looks like this:
      // file://ahost/afile.
      // Interestingly, authority and file components for the above URL
      // are either "ahost" and "/afile" or "" and "//ahost/afile" depending on
      // how the URL is obtained. If classpath is set as a jar with UNC,
      // the former is true, if the classpath is set as a directory with UNC,
      // the latter is true.
      String prefix = "";
      if (authority.length() > 0) {
        prefix = "////";
      } else if (file.startsWith("//")) {
        prefix = "//";
      }
      file = prefix.concat(authority).concat(file);
      url = new URL(protocol, null, file);
      AbstractSessionLog.getLog()
          .finer(
              "fixUNC: after fixing: url = "
                  + url
                  + ", authority = "
                  + url.getAuthority()
                  + ", file = "
                  + url.getFile());
    }
    return url;
  }
コード例 #3
0
  public String evaluate(String urlStr, String partToExtract) {
    if (urlStr == null || partToExtract == null) {
      return null;
    }

    if (lastUrlStr == null || !urlStr.equals(lastUrlStr)) {
      try {
        url = new URL(urlStr);
      } catch (Exception e) {
        return null;
      }
    }
    lastUrlStr = urlStr;

    if (partToExtract.equals("HOST")) return url.getHost();
    if (partToExtract.equals("PATH")) return url.getPath();
    if (partToExtract.equals("QUERY")) return url.getQuery();
    if (partToExtract.equals("REF")) return url.getRef();
    if (partToExtract.equals("PROTOCOL")) return url.getProtocol();
    if (partToExtract.equals("FILE")) return url.getFile();
    if (partToExtract.equals("AUTHORITY")) return url.getAuthority();
    if (partToExtract.equals("USERINFO")) return url.getUserInfo();

    return null;
  }
コード例 #4
0
ファイル: BaiduAPI.java プロジェクト: jibaro/stonelion
  public static URL getURL(double latitude, double longitude, String output)
      throws MalformedURLException, IOException {
    StringBuilder stringBuilder = new StringBuilder(URL_PREFIX);
    stringBuilder.append("?");
    stringBuilder.append("output=" + output + "&");
    stringBuilder.append("location=" + latitude + "," + longitude + "&");
    stringBuilder.append("key=" + PRIVATE_KEY);

    URL url = new URL(stringBuilder.toString());

    System.out.println(String.format("getProtocol %s", url.getProtocol()));
    System.out.println(String.format("getHost %s", url.getHost()));
    System.out.println(String.format("getPath %s", url.getPath()));
    System.out.println(String.format("getPort %s", url.getPort()));
    System.out.println(String.format("getDefaultPort %s", url.getDefaultPort()));
    System.out.println(String.format("getQuery %s", url.getQuery()));
    System.out.println(String.format("getAuthority %s", url.getAuthority()));
    System.out.println(String.format("getRef %s", url.getRef()));
    System.out.println(String.format("getUserInfo %s", url.getUserInfo()));
    System.out.println(String.format("getFile %s", url.getFile()));
    System.out.println(String.format("getContent %s", url.getContent()));
    System.out.println(String.format("toExternalForm %s", url.toExternalForm()));
    System.out.println("---------------");

    return url;
  }
コード例 #5
0
ファイル: R2RMLToolkit.java プロジェクト: neurolit/db2triples
 /**
  * The URL-safe version of a string is obtained by an URL encoding to a string value.
  *
  * @throws R2RMLDataError
  * @throws MalformedURLException
  */
 public static String getURLSafeVersion(String value) throws R2RMLDataError {
   if (value == null) return null;
   URL url = null;
   try {
     url = new URL(value);
   } catch (MalformedURLException mue) {
     // This template should be not a url : no encoding
     return value;
   }
   // No exception raised, this template is a valid url : perform
   // percent-encoding
   try {
     java.net.URI uri =
         new java.net.URI(
             url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef());
     String result = uri.toURL().toString();
     // Percent encoding : complete with no supported char in this
     // treatment
     result = result.replaceAll("\\,", "%2C");
     return result;
   } catch (URISyntaxException e) {
     throw new R2RMLDataError(
         "[R2RMLToolkit:getIRISafeVersion] This value "
             + value
             + " can not be percent-encoded because "
             + e.getMessage());
   } catch (MalformedURLException e) {
     throw new R2RMLDataError(
         "[R2RMLToolkit:getIRISafeVersion] This value "
             + value
             + " can not be percent-encoded because "
             + e.getMessage());
   }
 }
コード例 #6
0
ファイル: ForceTvUtils.java プロジェクト: junwuwei/yfmcode
 public static void switch_chan(String httpurl, String hotlink, String userid, Handler handler) {
   try {
     String param = "http://127.0.0.1:9898/cmd.xml?cmd=switch_chan&";
     URL url = new URL(httpurl.replace("p2p", "http"));
     String server = url.getAuthority();
     String videoId = url.getPath();
     videoId = videoId.subSequence(1, videoId.length() - 3).toString();
     param += "id=" + videoId;
     param += "&server=" + server;
     param += "&link=" + hotlink;
     param += "&userid=" + userid;
     String playurl = "http://127.0.0.1:9898/" + videoId + ".ts";
     // String playurl="http://111.11.28.16/mrtpweb/aaaa.mp4";
     if (tvthread != null) {
       tvthread.stopreq();
     }
     LogUtils.write(TAG, param);
     LogUtils.write(TAG, playurl);
     tvthread = new ForceTvThread(param, playurl, handler);
     tvthread.start();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #7
0
ファイル: RequestAnswer.java プロジェクト: antmarpen/TFG
  private static void setValues(
      URL url,
      HttpResponse<InputStream> jsonResponse,
      AbstractMap<String, String> localHeaders,
      Long responseTime) {
    generalInfo = new HashMap<>();

    int responseCode = jsonResponse.getStatus();

    generalInfo.put("Protocol", url.getProtocol());
    generalInfo.put("Authority", url.getAuthority());
    generalInfo.put("Host", url.getHost());
    generalInfo.put("Default Port", Integer.toString(url.getDefaultPort()));
    generalInfo.put("Port ", Integer.toString(url.getPort()));
    generalInfo.put("Path", url.getPath());
    generalInfo.put("Query", url.getQuery());
    generalInfo.put("Filename", url.getFile());
    generalInfo.put("Ref", url.getRef());

    responseValues.resetProperties();
    responseValues.setRequestHeaders(localHeaders);
    responseValues.setResponseHeaders(jsonResponse.getHeaders());
    responseValues.setGeneralInfo(generalInfo);
    responseValues.setResponseTime(responseTime);
    responseValues.setResponseCode(
        Integer.toString(responseCode) + " " + jsonResponse.getStatusText());
  }
コード例 #8
0
  public URLConnection openConnection(URL url) throws IOException {
    String projectID = url.getAuthority();
    AWorkspaceProject project = WorkspaceController.getCachedProjectByID(projectID);

    if (project == null) {
      throw new IOException("project with id=" + projectID + " is missing");
    }

    URL absolutePath = resolve(project, url);
    return absolutePath.openConnection();
  }
コード例 #9
0
ファイル: URLDemo.java プロジェクト: yangjun2/java
 /**
  * @param args
  * @throws MalformedURLException
  */
 public static void main(String[] args) throws MalformedURLException {
   // TODO Auto-generated method stub
   URL url = new URL("http://www.baidu.com");
   URL tuto = new URL(url, "tutorial.intro.html#DOWNLOADING");
   System.out.println("protocal=" + tuto.getProtocol());
   System.out.println("host=" + tuto.getHost());
   System.out.println("port=" + tuto.getPort());
   System.out.println("Authority=" + tuto.getAuthority());
   System.out.println("Path=" + tuto.getPath());
   System.out.println("UserInfo=" + tuto.getUserInfo());
   System.out.println("DefaultPort=" + tuto.getDefaultPort());
 }
コード例 #10
0
ファイル: URL1.java プロジェクト: xhbang/java-class
 public static void main(String[] args) throws IOException {
   URL url = new URL("http://www.javajeff.com/articles/articles/html");
   System.out.println("Authority = " + url.getAuthority());
   System.out.println("Default port = " + url.getDefaultPort());
   System.out.println("File = " + url.getFile());
   System.out.println("Host = " + url.getHost());
   System.out.println("Path = " + url.getPath());
   System.out.println("Port = " + url.getPort());
   System.out.println("Protocol = " + url.getProtocol());
   System.out.println("Query = " + url.getQuery());
   System.out.println("Ref = " + url.getRef());
   System.out.println("User Info = " + url.getUserInfo());
 }
コード例 #11
0
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Map<String, Object> httpHeaders = new Hashtable<String, Object>();
    List<RpcHeader> headers = new ArrayList<RpcHeader>();
    Pair<Endpoint, Long> r = preprocess(httpHeaders, headers);

    Endpoint endpoint = r.getFirst();
    long iid = r.getSecond();

    URL url = endpoint.getAddress().toURL();
    String key =
        url.getProtocol()
            + "://"
            + url.getAuthority()
            + url.getPath()
            + "##"
            + method.getName()
            + "("
            + JSON.encode(args)
            + ")";
    long s = System.currentTimeMillis();
    Object ret = cache.getIfPresent(key);
    if (ret != null) {
      postprocess(
          iid, System.currentTimeMillis() - s, new MimeHeaders(), new ArrayList<RpcHeader>(), null);
      return ret;
    } else {
      Object client = clientFactory.create(interfaceClass, endpoint.getAddress().toURL());
      RequestAttributes reqAttrs = (RequestAttributes) client;
      reqAttrs.setUserId(endpoint.getUserName());
      reqAttrs.setPassword(endpoint.getPassword());
      reqAttrs.addRequestMimeHeaders(httpHeaders);
      for (RpcHeader h : headers) {
        reqAttrs.addRequestRpcHeader(h.getNamespace(), h.getName(), h.getValue());
      }
      try {
        Object result = method.invoke(client, args);
        cache.put(key, result);
        return result;
      } finally {
        ResponseAttributes resAttrs = (ResponseAttributes) client;
        postprocess(
            iid,
            System.currentTimeMillis() - s,
            MimeHeadersUtil.fromStringObjectMap(resAttrs.getResponseMimeHeaders()),
            resAttrs.getResponseRpcHeaders(),
            resAttrs.getResponseRpcFault());
      }
    }
  }
コード例 #12
0
 private void _log(@Nonnull final URL aURL) throws URISyntaxException {
   s_aLogger.info("Next URL");
   s_aLogger.info("  protocol = " + aURL.getProtocol());
   s_aLogger.info("  authority = " + aURL.getAuthority());
   s_aLogger.info("  host = " + aURL.getHost());
   s_aLogger.info("  port = " + aURL.getPort());
   s_aLogger.info("  defaultPort = " + aURL.getDefaultPort());
   s_aLogger.info("  path = " + aURL.getPath());
   s_aLogger.info("  query = " + aURL.getQuery());
   s_aLogger.info("  file = " + aURL.getFile());
   s_aLogger.info("  ref = " + aURL.getRef());
   s_aLogger.info("  externalForm = " + aURL.toExternalForm());
   s_aLogger.info("  URI          = " + aURL.toURI().toString());
 }
コード例 #13
0
ファイル: URLInfo.java プロジェクト: Ryan-han/Study-Project
 public static void main(String args[]) {
   URL url = null;
   try {
     url = new URL("hdfs://www.daum.net:80");
     log.info("Protocol : " + url.getProtocol());
     log.info("Host     : " + url.getHost());
     log.info("Port     : " + url.getPort());
     log.info("File     : " + url.getPath());
     log.info("Query    : " + url.getQuery());
     log.info("Authrioty: " + url.getAuthority());
   } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #14
0
 @Override
 public void doComplete(final CompletionInfo completions, final String partial, final int flags) {
   try {
     // If 'partial' is a well-formed "file:" URL with no host, port,
     // user or query, do completion on the path component.
     URL url = new URL(partial);
     if (url.getProtocol().equals("file")
         && (url.getAuthority() == null || url.getAuthority().length() == 0)
         && (url.getQuery() == null || url.getQuery().length() == 0)) {
       // Use a FileArgument to do the work of completing the pathname,
       // capturing the results using our own CompletionInfo object.
       CompletionInfo myCompletion = new CommandCompletions();
       new FileArgument(null, getFlags()).complete(myCompletion, url.getPath(), flags);
       // Then turn the completions back into "file:" URLs
       for (String c : myCompletion.getCompletions()) {
         // (Kludge - the 'true' argument prevents an extra space
         // character from being appended to the completions.)
         completions.addCompletion("file:" + c, true);
       }
     }
   } catch (MalformedURLException ex) {
     // No completion possible
   }
 }
コード例 #15
0
	public static void main(String[] args) throws IOException {

		URL url = new URL("http://manuli-agri.com.ua");
		URLConnection connection = url.openConnection();

		BufferedReader inputStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(url.getAuthority() + ".txt")));
		
		String line;
		
		while((line = inputStream.readLine()) != null){
			bufferedWriter.write(line);
		}

		bufferedWriter.close();
		inputStream.close();
}
コード例 #16
0
ファイル: URLTest.java プロジェクト: 281831964/dubbo
  @Test
  public void test_javaNetUrl() throws Exception {
    java.net.URL url =
        new java.net.URL(
            "http://*****:*****@10.20.130.230:20880/context/path?version=1.0.0&application=morgan#anchor1");

    assertEquals("http", url.getProtocol());
    assertEquals("admin:hello1234", url.getUserInfo());
    assertEquals("10.20.130.230", url.getHost());
    assertEquals(20880, url.getPort());
    assertEquals("/context/path", url.getPath());
    assertEquals("version=1.0.0&application=morgan", url.getQuery());
    assertEquals("anchor1", url.getRef());

    assertEquals("admin:[email protected]:20880", url.getAuthority());
    assertEquals("/context/path?version=1.0.0&application=morgan", url.getFile());
  }
コード例 #17
0
  private String getPageUrlFromIconUrl(String iconUrl) {
    // Addon icon URLs come with a query argument that is usually
    // used for expiration purposes. We want the "page URL" here to be
    // stable enough to avoid unnecessary duplicate records of the
    // same addon.
    String pageUrl = iconUrl;

    try {
      URL urlForIcon = new URL(iconUrl);
      URL urlForPage =
          new URL(urlForIcon.getProtocol(), urlForIcon.getAuthority(), urlForIcon.getPath());
      pageUrl = urlForPage.toString();
    } catch (MalformedURLException e) {
      // Defaults to pageUrl = iconUrl in case of error
    }

    return pageUrl;
  }
コード例 #18
0
  /**
   * Takes a URL and converts it to a File. The attempts to deal with Windows UNC format specific
   * problems, specifically files located on network shares and different drives.
   *
   * <p>If the URL.getAuthority() returns null or is empty, then only the url's path property is
   * used to construct the file. Otherwise, the authority is prefixed before the path.
   *
   * <p>It is assumed that url.getProtocol returns "file".
   *
   * <p>Authority is the drive or network share the file is located on. Such as "C:", "E:",
   * "\\fooServer"
   *
   * @param url a URL object that uses protocol "file"
   * @return a File that corresponds to the URL's location
   */
  public static File urlToFile(URL url) {
    if (!"file".equals(url.getProtocol())) {
      return null; // not a File URL
    }
    String string = url.toExternalForm();
    if (string.contains("+")) {
      // this represents an invalid URL created using either
      // file.toURL(); or
      // file.toURI().toURL() on a specific version of Java 5 on Mac
      string = string.replace("+", "%2B");
    }
    try {
      string = URLDecoder.decode(string, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Could not decode the URL to UTF-8 format", e);
    }

    String path3;

    String simplePrefix = "file:/";
    String standardPrefix = "file://";
    String os = System.getProperty("os.name");

    if (os.toUpperCase().contains("WINDOWS") && string.startsWith(standardPrefix)) {
      // win32: host/share reference
      path3 = string.substring(standardPrefix.length() - 2);
    } else if (string.startsWith(standardPrefix)) {
      path3 = string.substring(standardPrefix.length());
    } else if (string.startsWith(simplePrefix)) {
      path3 = string.substring(simplePrefix.length() - 1);
    } else {
      String auth = url.getAuthority();
      String path2 = url.getPath().replace("%20", " ");
      if (auth != null && !auth.equals("")) {
        path3 = "//" + auth + path2;
      } else {
        path3 = path2;
      }
    }

    return new File(path3);
  }
コード例 #19
0
  private String getRootUrl() throws NotFoundException, ReportableError {
    URL manageUrl = null;
    try {
      manageUrl = new URL(this.appSettings.getString("webUrl", ""));
    } catch (MalformedURLException e) {
      throw new ReportableError(
          r.getString(R.string.error_bad_url, (manageUrl == null) ? "" : manageUrl.toString()), e);
    }

    String urlPath = manageUrl.getPath();
    String[] pathElements = urlPath.split("/");
    String directoryActual = "/";
    if (pathElements.length > 1) {
      for (int idx = 0; idx < pathElements.length - 1; idx++) {
        if (pathElements[idx].length() > 0) {
          directoryActual += pathElements[idx] + "/";
        }
      }
    }
    return manageUrl.getProtocol() + "://" + manageUrl.getAuthority() + directoryActual;
  }
コード例 #20
0
ファイル: AbstractStorageItem.java プロジェクト: usnews/dari
 private String createPublicUrl(String baseUrl, String path) {
   if (!ObjectUtils.isBlank(baseUrl)) {
     path = StringUtils.ensureEnd(baseUrl, "/") + path;
     try {
       URL url = new URL(path);
       path =
           new URI(
                   url.getProtocol(),
                   url.getAuthority(),
                   url.getPath(),
                   url.getQuery(),
                   url.getRef())
               .toASCIIString();
     } catch (MalformedURLException error) {
       // Return the path as is if the given path is malformed.
     } catch (URISyntaxException error) {
       // Return the path as is if the resolved path is malformed.
     }
   }
   return path;
 }
コード例 #21
0
 /**
  * Constructs a store from a given URL. The URL should either specify the <code>jar:</code>
  * protocol, in which case the sub-URL should point to a JAR or ZIP file; or the URL should itself
  * specify a JAR or ZIP file. Query and reference part of the URL are ignored. The store is
  * immutable.
  *
  * @param url source location of the underlying persistent storage; should refer to a ZIP or JAR
  *     file.
  * @throws IllegalArgumentException if <code>location</code> does not specify the correct protocol
  * @throws IOException if the URL has the JAR protocol, but cannot be opened
  */
 public DefaultArchiveSystemStore(URL url) throws IllegalArgumentException, IOException {
   // first strip query and anchor part
   try {
     url = new URL(url.getProtocol(), url.getAuthority(), url.getPath());
   } catch (MalformedURLException exc) {
     assert false : String.format("Stripping URL '%s' throws exception: %s", url, exc);
   }
   this.location = url.toString();
   // artificially append the jar protocol, if it is not yet there
   if (!url.getProtocol().equals(JAR_PROTOCOL)) {
     if (!JAR.hasExtension(url.getPath()) && !ZIP.hasExtension(url.getPath())) {
       throw new IllegalArgumentException(String.format("URL '%s' is not a JAR or ZIP file", url));
     }
     url = new URL(JAR_PROTOCOL, null, url.toString() + "!/");
   }
   this.entryName = extractEntryName(url);
   // take the last part of the entry name as grammar name
   File fileFromEntry = new File(this.entryName);
   this.grammarName = GRAMMAR.stripExtension(fileFromEntry.getName());
   this.url = url;
   this.file = null;
 }
コード例 #22
0
 // for get url reqs, serialise the data map into the url
 private static void serialiseRequestUrl(Connection.Request req) throws IOException {
   URL in = req.url();
   StringBuilder url = new StringBuilder();
   boolean first = true;
   // reconstitute the query, ready for appends
   url.append(in.getProtocol())
       .append("://")
       .append(in.getAuthority()) // includes host, port
       .append(in.getPath())
       .append("?");
   if (in.getQuery() != null) {
     url.append(in.getQuery());
     first = false;
   }
   for (Connection.KeyVal keyVal : req.data()) {
     if (!first) url.append('&');
     else first = false;
     url.append(URLEncoder.encode(keyVal.key(), DataUtil.defaultCharset))
         .append('=')
         .append(URLEncoder.encode(keyVal.value(), DataUtil.defaultCharset));
   }
   req.url(new URL(url.toString()));
   req.data().clear(); // moved into url as get params
 }
コード例 #23
0
ファイル: Node.java プロジェクト: biins/couchbase-auto-views
 @Override
 public String toString() {
   return "<URI:" + restUrl.getAuthority() + "," + NSOtpNode + ">";
 }
コード例 #24
0
ファイル: UrlUtils.java プロジェクト: dawenzi80/test
 /**
  * Creates and returns a new URL identical to the specified URL, except using the specified query
  * string.
  *
  * @param u the URL on which to base the returned URL
  * @param newQuery the new query string to use in the returned URL
  * @return a new URL identical to the specified URL, except using the specified query string
  * @throws MalformedURLException if there is a problem creating the new URL
  */
 public static URL getUrlWithNewQuery(final URL u, final String newQuery)
     throws MalformedURLException {
   return createNewUrl(u.getProtocol(), u.getAuthority(), u.getPath(), u.getRef(), newQuery);
 }
コード例 #25
0
  /**
   * Creates a new URL to the specified resource {@code spec}. This URL is relative to the given
   * {@code context}. The {@code handler} will be used to parse the URL string representation. If
   * this argument is {@code null} the default {@code URLStreamHandler} will be used. If the
   * protocol of the parsed URL does not match with the protocol of the context URL, then the newly
   * created URL is absolute and bases only on the given URL represented by {@code spec}. Otherwise
   * the protocol is defined by the context URL.
   *
   * @param context the URL which is used as the context.
   * @param spec the URL string representation which has to be parsed.
   * @param handler the specific stream handler to be used by this URL.
   * @throws IOException if the given string {@code spec} could not be parsed as a URL or an invalid
   *     protocol has been found.
   */
  public URL(URL context, String spec) throws MalformedURLException {

    if (spec == null) {
      throw new MalformedURLException();
    }
    spec = spec.trim();

    this.spec = spec;

    // The spec includes a protocol if it includes a colon character
    // before the first occurrence of a slash character. Note that,
    // "protocol" is the field which holds this URLs protocol.
    int index;
    try {
      index = spec.indexOf(':');
    } catch (NullPointerException e) {
      throw new MalformedURLException(e.toString());
    }
    int startIPv6Addr = spec.indexOf('[');
    if (index >= 0) {
      if ((startIPv6Addr == -1) || (index < startIPv6Addr)) {
        protocol = spec.substring(0, index);
        // According to RFC 2396 scheme part should match
        // the following expression:
        // alpha *( alpha | digit | "+" | "-" | "." )
        char c = protocol.charAt(0);
        boolean valid = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
        for (int i = 1; valid && (i < protocol.length()); i++) {
          c = protocol.charAt(i);
          valid =
              ('a' <= c && c <= 'z')
                  || ('A' <= c && c <= 'Z')
                  || ('0' <= c && c <= '9')
                  || (c == '+')
                  || (c == '-')
                  || (c == '.');
        }
        if (!valid) {
          protocol = null;
          index = -1;
        } else {
          // Ignore case in protocol names.
          // Scheme is defined by ASCII characters.
          protocol = protocol.toLowerCase();
        }
      }
    }

    if (protocol != null) {
      // If the context was specified, and it had the same protocol
      // as the spec, then fill in the receiver's slots from the values
      // in the context but still allow them to be over-ridden later
      // by the values in the spec.
      if (context != null && protocol.equals(context.getProtocol())) {
        String cPath = context.getPath();
        if (cPath != null && cPath.startsWith("/")) {
          set(
              protocol,
              context.getHost(),
              context.getPort(),
              context.getAuthority(),
              context.getUserInfo(),
              cPath,
              context.getQuery(),
              null);
        }
      }
    } else {
      // If the spec did not include a protocol, then the context
      // *must* be specified. Fill in the receiver's slots from the
      // values in the context, but still allow them to be over-ridden
      // by the values in the ("relative") spec.
      if (context == null) {
        throw new MalformedURLException("Protocol not found: " + spec);
      }
      set(
          context.getProtocol(),
          context.getHost(),
          context.getPort(),
          context.getAuthority(),
          context.getUserInfo(),
          context.getPath(),
          context.getQuery(),
          null);
    }

    if (port < -1) {
      throw new MalformedURLException("Port out of range: " + port);
    }
  }
コード例 #26
0
ファイル: PageUrls.java プロジェクト: GeeChao/serenity-core
 private String pathFrom(String url) throws MalformedURLException {
   URL defaultUrl = new URL(url);
   return url.substring(
       url.indexOf(defaultUrl.getAuthority()) + defaultUrl.getAuthority().length());
 }
コード例 #27
0
  /**
   * Generates the service endpoint element from the swagger object.
   *
   * @param swaggerObject swagger document object.
   * @param swaggerVersion swagger version.
   */
  private void createEndpointElement(JsonObject swaggerObject, String swaggerVersion)
      throws RegistryException {
    /*
    Extracting endpoint url from the swagger document.
     */
    if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) {
      JsonElement endpointUrlElement = swaggerObject.get(SwaggerConstants.BASE_PATH);
      if (endpointUrlElement == null) {
        log.warn(
            "Endpoint url is not specified in the swagger document. Endpoint creation might fail. ");
        return;
      } else {
        endpointUrl = endpointUrlElement.getAsString();
      }
    } else if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) {
      JsonElement transportsElement = swaggerObject.get(SwaggerConstants.SCHEMES);
      JsonArray transports =
          (transportsElement != null) ? transportsElement.getAsJsonArray() : null;
      String transport =
          (transports != null) ? transports.get(0).getAsString() + "://" : DEFAULT_TRANSPORT;
      JsonElement hostElement = swaggerObject.get(SwaggerConstants.HOST);
      String host = (hostElement != null) ? hostElement.getAsString() : null;
      if (host == null) {
        log.warn(
            "Endpoint(host) url is not specified in the swagger document. "
                + "The host serving the documentation is to be used(including the port) as endpoint host");

        if (requestContext.getSourceURL() != null) {
          URL sourceURL = null;
          try {
            sourceURL = new URL(requestContext.getSourceURL());
          } catch (MalformedURLException e) {
            throw new RegistryException("Error in parsing the source URL. ", e);
          }
          host = sourceURL.getAuthority();
        }
      }

      if (host == null) {
        log.warn(
            "Can't derive the endpoint(host) url when uploading swagger from file. "
                + "Endpoint creation might fail. ");
        return;
      }

      JsonElement basePathElement = swaggerObject.get(SwaggerConstants.BASE_PATH);
      String basePath =
          (basePathElement != null) ? basePathElement.getAsString() : DEFAULT_BASE_PATH;

      endpointUrl = transport + host + basePath;
    }
    /*
    Creating endpoint artifact
     */
    OMFactory factory = OMAbstractFactory.getOMFactory();
    endpointLocation = EndpointUtils.deriveEndpointFromUrl(endpointUrl);
    String endpointName = EndpointUtils.deriveEndpointNameWithNamespaceFromUrl(endpointUrl);
    String endpointContent =
        EndpointUtils.getEndpointContentWithOverview(
            endpointUrl, endpointLocation, endpointName, documentVersion);
    try {
      endpointElement = AXIOMUtil.stringToOM(factory, endpointContent);
    } catch (XMLStreamException e) {
      throw new RegistryException("Error in creating the endpoint element. ", e);
    }
  }
コード例 #28
0
 /**
  * Determine the URL path to the persistence unit
  *
  * @param pxmlURL - Encoded URL containing the pu
  * @return
  * @throws IOException
  */
 public static URL computePURootURL(URL pxmlURL, String descriptorLocation)
     throws IOException, URISyntaxException {
   StringTokenizer tokenizer = new StringTokenizer(descriptorLocation, "/\\");
   int descriptorDepth = tokenizer.countTokens() - 1;
   URL result;
   String protocol = pxmlURL.getProtocol();
   if ("file".equals(protocol)) { // NOI18N
     StringBuffer path = new StringBuffer();
     boolean firstElement = true;
     for (int i = 0; i < descriptorDepth; i++) {
       if (!firstElement) {
         path.append("/"); // 315097 URL use standard separators
       }
       path.append("..");
       firstElement = false;
     }
     // e.g. file:/tmp/META-INF/persistence.xml
     // 210280: any file url will be assumed to always reference a file (not a directory)
     result = new URL(pxmlURL, path.toString()); // NOI18N
   } else if ("jar".equals(protocol)) { // NOI18N
     // e.g. jar:file:/tmp/a_ear/b.jar!/META-INF/persistence.xml
     JarURLConnection conn = JarURLConnection.class.cast(pxmlURL.openConnection());
     result = conn.getJarFileURL();
   } else if ("zip".equals(protocol)) { // NOI18N
     // e.g. zip:/tmp/a_ear/b.jar!/META-INF/persistence.xml
     // stolen from java.net.JarURLConnection.parseSpecs method
     String spec = pxmlURL.getFile();
     int separator = spec.lastIndexOf("!/");
     if (separator == -1) {
       separator = spec.length() - 1;
     }
     result = new File(spec.substring(0, separator++)).toURL();
   } else if ("wsjar".equals(protocol)) { // NOI18N
     // e.g. wsjar:file:/tmp/a_ear/b.jar!/META-INF/persistence.xml
     // but WS gives use jar:file:..., so we need to match it.
     String spec = pxmlURL.getFile();
     int separator = spec.lastIndexOf("!/");
     if (separator == -1) {
       separator = spec.length();
     } else {
       // If this doesn't reference a war file with a properly located persistence.xml,
       // then chop off everything after the "!/" marker and assume it is a normal jar.
       // Else, if the wsjar URL references a file with a ".war" extension, and its entry
       // starts with WEB-INF/classes/, then the calculated persistence unit root should
       // be wsjar:path/to/a.war!/WEB-INF/classes/ as per JPA 2.1 Spec section 8.2 "Persistence
       // Unit Packaging".
       separator += 2;
       // Filter out invalid scenarios such as
       // wsjar:file:/a/path/to/my.war!/foo/WEB-INF/classes/META-INF/persistence.xml
       if (spec.regionMatches(true, separator - 6, ".war", 0, 4)
           && spec.regionMatches(true, separator, WEBINF_CLASSES_STR, 0, WEBINF_CLASSES_LEN)) {
         separator += WEBINF_CLASSES_LEN;
       }
     }
     result = new URL("jar", "", spec.substring(0, separator));
   } else if ("bundleentry".equals(protocol)) {
     // mkeith - add bundle protocol cases
     result = new URL("bundleentry://" + pxmlURL.getAuthority());
   } else if ("bundleresource".equals(protocol)) {
     result = new URL("bundleresource://" + pxmlURL.getAuthority());
   } else {
     StringBuffer path = new StringBuffer();
     for (int i = 0; i < descriptorDepth; i++) {
       path.append("../"); // 315097 URL use standard separators
     }
     // some other protocol
     result = new URL(pxmlURL, path.toString()); // NOI18N
   }
   result = fixUNC(result);
   return result;
 }
コード例 #29
0
  /**
   * List directory contents for a resource folder. Not recursive. This is basically a brute-force
   * implementation. Works for regular files and also JARs.
   *
   * @author Greg Briggs
   * @param clazz Any java class that lives in the same place as the resources you want.
   * @param path Should end with "/", but not start with one.
   * @return Just the name of each member item, not the full paths.
   * @throws URISyntaxException
   * @throws IOException
   */
  public static String[] getResourceListing(Class clazz, String path)
      throws URISyntaxException, IOException {

    ClassLoader classLoader = clazz.getClassLoader();

    URL dirURL = clazz.getClassLoader().getResource(path);

    if (dirURL != null && dirURL.getProtocol().equals("file")) {
      /* A file path: easy enough */

      System.out.println("dirURL.getAuthority(); = |" + dirURL.getAuthority() + "|.");

      System.out.println("dirURL.getPath(); = |" + dirURL.getPath() + "|.");

      String[] resourceListing = new File(dirURL.toURI()).list();

      printList(resourceListing, path);

      return resourceListing;
    }

    if (dirURL == null) {
      /*
       * In case of a jar file, we can't actually find a directory.
       * Have to assume the same jar as clazz.
       */
      String me = clazz.getName().replace(".", "/") + ".class";
      dirURL = clazz.getClassLoader().getResource(me);
    }

    log.info(
        "after dirURL == null and reset dirURL: dirURL.getAuthority(); = |"
            + dirURL.getAuthority()
            + "|.");

    log.info(
        "after dirURL == null and reset dirURL: dirURL.getPath(); = |" + dirURL.getPath() + "|.");

    if (dirURL.getProtocol().equals("jar")) {
      /* A JAR path */
      String jarPath =
          dirURL
              .getPath()
              .substring(5, dirURL.getPath().indexOf("!")); // strip out only the JAR file
      JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
      Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
      Set<String> result = new HashSet<String>(); // avoid duplicates in case it is a subdirectory
      while (entries.hasMoreElements()) {
        String name = entries.nextElement().getName();
        if (name.startsWith(path)) { // filter according to the path
          String entry = name.substring(path.length());
          int checkSubdir = entry.indexOf("/");
          if (checkSubdir >= 0) {
            // if it is a subdirectory, we just return the directory name
            entry = entry.substring(0, checkSubdir);
          }
          result.add(entry);
        }
      }

      String[] resourceListing = result.toArray(new String[result.size()]);

      printList(resourceListing, path);

      return resourceListing;
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
  }