/** 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()));
 }
 public static URL container(String resource, ClassLoader cl) {
   final URL resUrl = cl.getResource(resource);
   if (resUrl == null) {
     throw new IllegalArgumentException("Resource not found: " + resource);
   }
   final StringBuilder url = new StringBuilder(resUrl.toExternalForm());
   try {
     if ("jar".equalsIgnoreCase(resUrl.getProtocol())) {
       url.delete(0, 4).delete(url.indexOf(resource) - 2, url.length());
     } else if ("file".equalsIgnoreCase(resUrl.getProtocol())) {
       url.delete(url.indexOf(resource), url.length());
     } else {
       throw new UnsupportedOperationException(
           "Cannot get container for resource ["
               + resource
               + "]. Unsupported URL protocol ["
               + resUrl.getProtocol()
               + "].");
     }
     return new URL(url.toString());
   } catch (MalformedURLException e) {
     throw new UnsupportedOperationException(
         "Cannot get container for resource [" + resource + "]. Malformed URL [" + url + "].");
   }
 }
 private List<String> searchDependencyEngineConfigFiles(
     String prefixPackageName, Class<?> contentLoaderClass) {
   List<String> fileNames = new ArrayList<String>();
   Enumeration<?> enumFiles = findConfigFileUrls(prefixPackageName, contentLoaderClass);
   while (enumFiles != null && enumFiles.hasMoreElements()) {
     URL url = (URL) enumFiles.nextElement();
     if (url == null || url.getFile() == null || url.getFile().length() <= 1) continue;
     String fileName = getFileName(url.getPath());
     if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jar")) {
       String elementInJar = getJarFileEntryName(url.getPath());
       JarFile jarFile = openJar(url);
       List<JarEntry> entries = Collections.list(jarFile.entries());
       for (JarEntry entry : entries) {
         String entryName = entry.getName();
         if (entryName.startsWith(elementInJar)) {
           if (!entry.isDirectory() && entryName.matches(dependencyEngineConfigFileRegex)) {
             fileNames.add(fileName + "!" + "/" + entry.toString());
           }
         }
       }
     } else {
       List<String> list = searchDependencyEngineConfigFiles(new File(fileName));
       if (list != null && list.size() > 0) {
         fileNames.addAll(list);
       }
     }
   }
   return fileNames;
 }
Exemple #4
0
    private String sendPop(Transaction tx) {
      RequestBody requestBody =
          RequestBody.create(MediaType.parse("application/bitcoin-pop"), tx.toBytes());

      URL url;
      try {
        url = new URL(popRequest.getP());
        if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) {
          return "Invalid Url, expected protocol http or https: " + popRequest.getP();
        }
      } catch (MalformedURLException e) {
        return "Invalid Url: " + popRequest.getP();
      }

      Request request = new Request.Builder().url(url).post(requestBody).build();

      OkHttpClient httpClient = new OkHttpClient();
      if (_mbwManager.getTorMode() == ServerEndpointType.Types.ONLY_TOR
          && _mbwManager.getTorManager() != null) {
        httpClient = _mbwManager.getTorManager().setupClient(httpClient);
      }

      try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
          return response.body().string();
        } else {
          return "Error occurred: " + response.code();
        }
      } catch (IOException e) {
        return "Cannot communicate with server: " + e.getMessage();
      }
    }
Exemple #5
0
  public Map<String, URL> getResourcesMap(String uri) throws IOException {
    String basePath = path + uri;

    Map<String, URL> resources = new HashMap<String, URL>();
    if (!basePath.endsWith("/")) {
      basePath += "/";
    }
    Enumeration<URL> urls = getResources(basePath);

    while (urls.hasMoreElements()) {
      URL location = urls.nextElement();

      try {
        if (location.getProtocol().equals("jar")) {

          readJarEntries(location, basePath, resources);

        } else if (location.getProtocol().equals("file")) {

          readDirectoryEntries(location, resources);
        }
      } catch (Exception e) {
      }
    }

    return resources;
  }
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
          String stringValue = value.toString();

          if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);
            preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
          } else {
            preference.setSummary(stringValue);
          }

          // detect errors
          if (preference.getKey().equals("sos_uri")) {
            try {
              URL url = new URL(value.toString());
              if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https"))
                throw new Exception("SOS URL must be HTTP or HTTPS");
            } catch (Exception e) {
              AlertDialog.Builder dlgAlert = new AlertDialog.Builder(preference.getContext());
              dlgAlert.setMessage("Invalid SOS URL");
              dlgAlert.setTitle(e.getMessage());
              dlgAlert.setPositiveButton("OK", null);
              dlgAlert.setCancelable(true);
              dlgAlert.create().show();
            }
          }

          return true;
        }
Exemple #7
0
  /**
   * This is something of a hack. Velocity loads files relative to the property
   * VelocityEngine.FILE_RESOURCE_LOADER_PATH. So if we can find the template ourselves then we can
   * infer what the property value should be so that velocity works ok.
   */
  private void inferVelocityLoaderPath(VelocityEngine ve) throws IOException {
    String defaultPath = (String) ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH);
    if (null == defaultPath || StringUtils.isEmpty(defaultPath)) {
      URL url = IOUtils.getResourceAsUrl(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
      if (FILE.equals(url.getProtocol())) {
        String path =
            FileUtils.getResourcePath(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
        if (!StringUtils.isEmpty(path)) {
          File fullPath = new File(path);
          File target = new File(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE);

          // drop trailing files until we are at the relative parent
          while (null != target && !StringUtils.isEmpty(target.getPath())) {
            env.log(fullPath.getPath() + " - " + target.getPath());
            target = target.getParentFile();
            fullPath = fullPath.getParentFile();
          }

          path = fullPath.getPath();
          if (path.endsWith("!")) {
            path = path + File.separator;
          }
          getEnv().log(VelocityEngine.FILE_RESOURCE_LOADER_PATH + " = " + path);
          ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
        }
      } else if (JAR.equals(url.getProtocol())) {
        env.log(url.toString());
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        ve.setProperty(MAGIC_VELOCITY_RESOURCE_LOADER, ClasspathResourceLoader.class.getName());
      }
    }
  }
  /**
   * Open FBS file identified by {@link #fbsURL}. The stream is positioned at the entry point
   * described by <code>entryPoint</code>.
   *
   * @param entryPoint entry point information.
   * @return a newly created FBS input stream on success, <code>null</code> if any error occured and
   *     the FBS stream is not opened.
   * @throws java.io.IOException if an I/O exception occurs.
   */
  private FbsInputStream openFbsFile(FbsEntryPoint entry) throws IOException {

    System.err.println("Entering FBS at " + entry.timestamp + " ms");

    // Make sure the protocol is HTTP.
    if (!fbkURL.getProtocol().equalsIgnoreCase("http")
        || !fbsURL.getProtocol().equalsIgnoreCase("http")) {
      System.err.println("Indexed access requires HTTP protocol in URLs");
      return null;
    }

    // Seek to the keyframe.
    InputStream is = openHttpByteRange(fbkURL, entry.key_fpos, entry.key_size);
    if (is == null) {
      return null;
    }

    // Load keyframe data from the .fbk file, prepend RFB initialization data.
    DataInputStream data = new DataInputStream(is);
    byte[] keyData = new byte[rfbInitData.length + (int) entry.key_size];
    System.arraycopy(rfbInitData, 0, keyData, 0, rfbInitData.length);
    data.readFully(keyData, rfbInitData.length, (int) entry.key_size);
    data.close();

    // Open the FBS stream.
    is = openHttpByteRange(fbsURL, entry.fbs_fpos, -1);
    if (is == null) {
      return null;
    }
    return new FbsInputStream(is, entry.timestamp, keyData, entry.fbs_skip);
  }
  /**
   * @param he hiperlik Event.
   * @see
   *     javax.help.plaf.basic.BasicContentViewerUI#hyperlinkUpdate(javax.swing.event.HyperlinkEvent)
   */
  @Override
  public void hyperlinkUpdate(final HyperlinkEvent he) {

    if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      URL u = he.getURL();
      if ("mailto".equalsIgnoreCase(u.getProtocol())
          || "http".equalsIgnoreCase(u.getProtocol())
          || "ftp".equalsIgnoreCase(u.getProtocol())) {
        Desktop desktop = null;
        if (Desktop.isDesktopSupported()) {
          desktop = Desktop.getDesktop();
          if (desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
              desktop.browse(u.toURI());
            } catch (MalformedURLException e1) {
              DialogUtils.showGeneralErrorDialog(
                  new Frame(), "MalformedURLException", "Invalid URL.");
            } catch (IOException e1) {
              DialogUtils.showGeneralErrorDialog(new Frame(), "IOException", "Resource not found.");
            } catch (URISyntaxException uriSyntaxEx) {
              DialogUtils.showGeneralErrorDialog(new Frame(), "URISyntaxException", "Invalid URI.");
            }
          }
        }
      } else {
        super.hyperlinkUpdate(he);
      }
    }
  }
  protected String[] listResources() throws IOException, URISyntaxException {
    String[] files = new String[0];
    URL dirURL = ClassLoader.getSystemResource(schemaPath);
    FilenameFilter fileFilter =
        new FilenameFilter() {

          @Override
          public boolean accept(File dir, String name) {
            return ((name.lastIndexOf('.') > -1)
                && (".xml".equalsIgnoreCase(name.substring(name.lastIndexOf('.')))));
          }
        };

    if (dirURL == null) {
      throw new FileNotFoundException(schemaPath);
    }

    if (dirURL.getProtocol().equals("file")) {
      files = listFileResources(dirURL, schemaPath, fileFilter);
    }

    if (dirURL.getProtocol().equals("jar")) {
      files = listJarResources(dirURL, fileFilter);
    }

    return files;
  }
Exemple #11
0
  public static File toFile(final URL url) {
    if ("jar".equals(url.getProtocol())) {
      try {
        final String spec = url.getFile();

        int separator = spec.indexOf('!');
        /*
         * REMIND: we don't handle nested JAR URLs
         */
        if (separator == -1) throw new MalformedURLException("no ! found in jar url spec:" + spec);

        return toFile(new URL(spec.substring(0, separator++)));
      } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
      }
    } else if ("file".equals(url.getProtocol())) {
      String path = decode(url.getFile());
      if (path.endsWith("!")) {
        path = path.substring(0, path.length() - 1);
      }
      return new File(path);
    } else {
      throw new IllegalArgumentException("Unsupported URL scheme: " + url.toExternalForm());
    }
  }
Exemple #12
0
  /**
   * Generate the signature base that is used to produce the signature
   *
   * @param url The full url that needs to be signed including its non OAuth url parameters
   * @param httpMethod The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)
   * @param parameters
   * @param normalizedUrl
   * @param normalizedRequestParameters
   * @return
   */
  private String generateSignatureBase(
      URL url,
      String httpMethod,
      List<QParameter> parameters,
      StringBuffer normalizedUrl,
      StringBuffer normalizedRequestParameters) {

    Collections.sort(parameters);

    normalizedUrl.append(url.getProtocol());
    normalizedUrl.append("://");
    normalizedUrl.append(url.getHost());
    if ((url.getProtocol().equals("http") || url.getProtocol().equals("https"))
        && url.getPort() != -1) {
      normalizedUrl.append(":");
      normalizedUrl.append(url.getPort());
    }
    normalizedUrl.append(url.getPath());
    normalizedRequestParameters.append(formEncodeParameters(parameters));

    StringBuffer signatureBase = new StringBuffer();
    signatureBase.append(httpMethod.toUpperCase());
    signatureBase.append("&");
    signatureBase.append(encode(normalizedUrl.toString()));
    signatureBase.append("&");
    signatureBase.append(encode(normalizedRequestParameters.toString()));
    return signatureBase.toString();
  }
  /**
   * to send Head request to the server to check for content type and content size
   *
   * @param current_url
   * @return
   */
  public boolean is_valid_file(String current_url) throws IOException {
    // System.out.print("[Output from log4j] Checking validity for url +" + current_url);

    // create and send HEAD request
    // // // // System.out.println("[Output from log4j] before head request + " + current_url);
    this.response_headers = crawler_client.fetch_head_response_url(current_url);
    // // // // System.out.println("[Output from log4j] after head request + " +
    // response_headers.size());
    // // // // System.out.println("[Output from log4j] After fetching response header in
    // is_valid_file");

    // base case - no response headers recieved from the server
    if (this.response_headers == null) return false;
    // check for location header
    if (this.response_headers.containsKey("location")) {
      this.is_reloc = true;
      String re_loc = this.response_headers.get("location");
      if (re_loc.startsWith("/")) {
        URL url_obj = new URL(current_url);
        String path = url_obj.getPath();
        String abs_reloc;
        if (path.endsWith(".xml") || path.endsWith(".html") || path.endsWith("htm"))
          path = path.substring(0, path.lastIndexOf("/"));
        if (path.endsWith("/"))
          abs_reloc =
              url_obj.getProtocol()
                  + "://"
                  + url_obj.getHost()
                  + path.substring(0, path.length() - 1)
                  + re_loc;
        else abs_reloc = url_obj.getProtocol() + "://" + url_obj.getHost() + path + re_loc;
        System.err.println("[Output from log4j] Found Relocation url +" + abs_reloc);
        WebURLQueue queue = new WebURLQueue();
        queue.addToQueue(abs_reloc);
        return false;
      } else {
        WebURLQueue queue = new WebURLQueue();
        queue.addToQueue(re_loc);
        return false;
      }
    }
    // if content type is not present in response header
    if (!(this.response_headers.containsKey("content-type"))) return false;
    // check valid content types
    this.content_type = this.response_headers.get("content-type");
    // if valid content type
    if (!content_type.equals("text/xml")
        && !content_type.equals("text/html")
        && !content_type.endsWith("+xml")
        && !content_type.equals("application/xml")) return false;
    // // // // System.out.println("[Output from log4j] Chheck till Content type");
    // check content-length exists
    if (this.response_headers.containsKey("content-length")) {
      this.content_length = Double.parseDouble(this.response_headers.get("content-length"));
      // checking allowed content-length for the document
      if (this.content_length > (XPathCrawler.maxsize_doc * 1024 * 1024)) return false;
    }
    // // // // System.out.println("[Output from log4j] Chheck till Content Length");
    return true;
  }
Exemple #14
0
  @Override
  protected URLConnection openConnection(URL u) throws IOException {
    String path = u.getPath().substring(1);
    String refr = u.getRef();

    StringBuilder test = new StringBuilder(path);
    if (refr != null && refr.length() > 0) {
      test.append(".part.");
      for (int i = 0; i < refr.length() - 1; i++) {
        test.append("0");
      }
      test.append("1");
    }

    URL local = Thread.currentThread().getContextClassLoader().getResource(test.toString());
    String base = local.toExternalForm();
    int end = base.length() - test.length();
    base = base.substring(0, end);

    if ("file".equals(local.getProtocol())) {
      return new XcfFileConnection(new URL(base), u);
    } else if ("jar".equals(local.getProtocol())) {
      return new XcfJarConnection(new URL(base), u);
    } else {
      throw new IOException("base protocol[" + local.getProtocol() + "] isn't supported");
    }
  }
 private JarURLConnection openJarURLConnection(final URL url) throws IOException {
   final URL checkedUrl;
   if ("zip".equals(url.getProtocol())) {
     // WebLogic returns URL with "zip" protocol, returning a
     // weblogic.utils.zip.ZipURLConnection when opened
     // Easy fix is to convert this URL to jar URL
     checkedUrl = new URL(url.toExternalForm().replace("zip:/", "jar:file:/"));
   } else {
     checkedUrl = url;
   }
   URLConnection urlConnection = checkedUrl.openConnection();
   // GlassFish 4.1.1 is providing a URLConnection of type:
   // http://svn.apache.org/viewvc/felix/trunk/framework/src/main/java/org/
   // apache/felix/framework/URLHandlersBundleURLConnection.java?view=markup
   // Which does _not_ extend JarURLConnection.
   // This bit of reflection allows us to call the getLocalURL method which
   // actually returns a URL to a jar file.
   if (checkedUrl.getProtocol().startsWith("bundle")) {
     try {
       final Method m = urlConnection.getClass().getDeclaredMethod("getLocalURL");
       if (!m.isAccessible()) {
         m.setAccessible(true);
       }
       final URL jarUrl = (URL) m.invoke(urlConnection);
       urlConnection = jarUrl.openConnection();
     } catch (Exception ex) {
       throw new AssertionError("Couldn't read jar file URL from bundle: " + ex);
     }
   }
   if (urlConnection instanceof JarURLConnection) {
     return (JarURLConnection) urlConnection;
   } else {
     throw new AssertionError("Unknown URLConnection type: " + urlConnection.getClass().getName());
   }
 }
  private InputStream retrieveConfigurationFileFromRemoteRepository() throws Exception {
    if (configFileURL.getProtocol().startsWith("http")) {
      HttpGet httpGet = new HttpGet(configFileURL.toURI());
      DefaultHttpClient client = new DefaultHttpClient();
      configureProxy(client);
      HttpResponse httpResponse = client.execute(httpGet);
      switch (httpResponse.getStatusLine().getStatusCode()) {
        case 200:
          log.debug("Connected to repository! Getting available Stacks");
          break;

        case 404:
          log.error("Failed! (Config file not found: " + configFileURL + ")");
          return null;

        default:
          log.error(
              "Failed! (server returned status code: "
                  + httpResponse.getStatusLine().getStatusCode());
          return null;
      }
      return httpResponse.getEntity().getContent();
    } else if (configFileURL.getProtocol().startsWith("file")) {
      return new FileInputStream(new File(configFileURL.toURI()));
    }
    return null;
  }
Exemple #17
0
 /**
  * Encodes illegal characters in the specified URL's path, query string and anchor according to
  * the URL encoding rules observed in real browsers.
  *
  * <p>For example, this method changes <tt>"http://first/?a=b c"</tt> to
  * <tt>"http://first/?a=b%20c"</tt>.
  *
  * @param url the URL to encode
  * @param minimalQueryEncoding whether or not to perform minimal query encoding, like IE does
  * @param charset the charset
  * @return the encoded URL
  */
 public static URL encodeUrl(
     final URL url, final boolean minimalQueryEncoding, final String charset) {
   final String p = url.getProtocol();
   if ("javascript".equalsIgnoreCase(p)
       || "about".equalsIgnoreCase(p)
       || "data".equalsIgnoreCase(p)) {
     // Special exception.
     return url;
   }
   try {
     String path = url.getPath();
     if (path != null) {
       path = encode(path, PATH_ALLOWED_CHARS, "UTF-8");
     }
     String query = url.getQuery();
     if (query != null) {
       if (minimalQueryEncoding) {
         query = org.apache.commons.lang3.StringUtils.replace(query, " ", "%20");
       } else {
         query = encode(query, QUERY_ALLOWED_CHARS, charset);
       }
     }
     String anchor = url.getRef();
     if (anchor != null) {
       anchor = encode(anchor, ANCHOR_ALLOWED_CHARS, "UTF-8");
     }
     return createNewUrl(url.getProtocol(), url.getHost(), url.getPort(), path, anchor, query);
   } catch (final MalformedURLException e) {
     // Impossible... I think.
     throw new RuntimeException(e);
   }
 }
Exemple #18
0
 /**
  * Comparison that does not consider Ref.
  *
  * @param url1 the url1
  * @param url2 the url2
  * @return true, if successful
  */
 public static boolean sameNoRefURL(URL url1, URL url2) {
   return Objects.equals(url1.getHost(), url2.getHost())
       && Objects.equals(url1.getProtocol(), url2.getProtocol())
       && (url1.getPort() == url2.getPort())
       && Objects.equals(url1.getFile(), url2.getFile())
       && Objects.equals(url1.getUserInfo(), url2.getUserInfo());
 }
  private void addPluginArtifact(Set<URI> artifactsPath) {
    // for Maven 2.x, the actual artifact isn't in the list....  need to try and find it
    URL url = getClass().getResource(getClass().getSimpleName() + ".class");

    try {
      if ("jar".equals(url.getProtocol())) {
        String s = url.getPath();
        if (s.contains("!")) {
          s = s.substring(0, s.indexOf('!'));
          url = new URL(s);
        }
      }
      URI uri = new URI(url.getProtocol(), null, url.getPath(), null, null);
      if (uri.getSchemeSpecificPart().endsWith(".class")) {
        String s = uri.toString();
        s = s.substring(0, s.length() - 6 - getClass().getName().length());
        uri = new URI(s);
      }
      File file = new File(uri);
      if (file.exists()) {
        artifactsPath.add(file.toURI());
      }
    } catch (Exception ex) {
      // ex.printStackTrace();
    }
  }
Exemple #20
0
  public static URL removeRef(URL url) throws MalformedURLException {
    int port = url.getPort();
    if (port == 80 && url.getProtocol().equalsIgnoreCase("http")) port = -1;
    else if (port == 443 && url.getProtocol().equalsIgnoreCase("https")) port = -1;

    URL u = new URL(url.getProtocol(), url.getHost(), port, url.getFile());
    return u;
  }
Exemple #21
0
 public static Transport getTransportForURL(URL url) {
   Transport retVal = null;
   if (url.getProtocol().equals("http")) {
     retVal = new HTTPTransport();
   } else if (url.getProtocol().equals("https")) {
     retVal = new HTTPTransport();
   }
   return retVal;
 }
 /** A couple quick checks on the url */
 public static final boolean isPostGIS(URL url) {
   if (url == null) {
     return false;
   }
   return url.getProtocol().toLowerCase().equals("postgis")
       || url.getProtocol().toLowerCase().equals("postgis.jdbc")
       || //$NON-NLS-1$ //$NON-NLS-2$
       url.getProtocol().toLowerCase().equals("jdbc.postgis"); // $NON-NLS-1$
 }
  private T requestInfo(URI baseUrl, RenderingContext context)
      throws IOException, URISyntaxException, ParserConfigurationException, SAXException {
    URL url = loader.createURL(baseUrl, context);

    GetMethod method = null;
    try {
      final InputStream stream;

      if ((url.getProtocol().equals("http") || url.getProtocol().equals("https"))
          && context.getConfig().localHostForwardIsFrom(url.getHost())) {
        String scheme = url.getProtocol();
        final String host = url.getHost();
        if (url.getProtocol().equals("https")
            && context.getConfig().localHostForwardIsHttps2http()) {
          scheme = "http";
        }
        URL localUrl = new URL(scheme, "localhost", url.getPort(), url.getFile());
        HttpURLConnection connexion = (HttpURLConnection) localUrl.openConnection();
        connexion.setRequestProperty("Host", host);
        for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
          connexion.setRequestProperty(entry.getKey(), entry.getValue());
        }
        stream = connexion.getInputStream();
      } else {
        method = new GetMethod(url.toString());
        for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
          method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        context.getConfig().getHttpClient(baseUrl).executeMethod(method);
        int code = method.getStatusCode();
        if (code < 200 || code >= 300) {
          throw new IOException(
              "Error "
                  + code
                  + " while reading the Capabilities from "
                  + url
                  + ": "
                  + method.getStatusText());
        }
        stream = method.getResponseBodyAsStream();
      }
      final T result;
      try {
        result = loader.parseInfo(stream);
      } finally {
        stream.close();
      }
      return result;
    } finally {
      if (method != null) {
        method.releaseConnection();
      }
    }
  }
Exemple #24
0
 /** Convenience method for setPage(String) */
 @Override
 public void setPage(URL url) {
   if ("file".equals(url.getProtocol()) || "jar".equals(url.getProtocol())) {
     // Creating file by url.toString() and using file.getName() preserves anchors
     File file = new File(url.toString());
     setPage(file.getName(), JabRef.class);
   } else {
     //  open all external URLs externally
     JabRef.jrf.openBrowser(url.toString());
   }
 }
  /* this code is workaround for subtle bug/feature in JDK1.3.1 and 1.4,
  related to loading applets behind proxy */
  protected PermissionCollection getPermissions(CodeSource codesource) {
    PermissionCollection sysPerms = null;
    Policy policy =
        (Policy)
            AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    return Policy.getPolicy();
                  }
                });
    if (policy != null) sysPerms = policy.getPermissions(new CodeSource(null, null));
    else sysPerms = new Permissions();

    final PermissionCollection perms = sysPerms;
    if (base != null && base.getHost() != null)
      perms.add(new SocketPermission(base.getHost() + ":1-", "accept,connect,resolve"));
    URL url = codesource.getLocation();

    if (url.getProtocol().equals("file")) {

      String path = url.getFile().replace('/', File.separatorChar);

      if (!path.endsWith(File.separator)) {
        int endIndex = path.lastIndexOf(File.separatorChar);
        if (endIndex != -1) {
          path = path.substring(0, endIndex + 1) + "-";
          perms.add(new FilePermission(path, "read"));
        }
      }
      perms.add(new SocketPermission("localhost", "connect,accept"));
      AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
              try {
                String host = InetAddress.getLocalHost().getHostName();
                perms.add(new SocketPermission(host, "connect,accept"));
              } catch (UnknownHostException uhe) {
              }
              return null;
            }
          });

      if (base.getProtocol().equals("file")) {
        String bpath = base.getFile().replace('/', File.separatorChar);
        if (bpath.endsWith(File.separator)) {
          bpath += "-";
        }
        perms.add(new FilePermission(bpath, "read"));
      }
    }
    // for (Enumeration e=perms.elements();e.hasMoreElements();)
    // System.err.println("p="+e.nextElement());
    return perms;
  }
  public static List<GenerationTarget> getTargets() {
    if (m_targets != null) {
      return m_targets;
    }

    m_targets = new ArrayList<GenerationTarget>();

    URL location = getClassLocation();

    if (location == null) return m_targets;

    if (location.getProtocol().equals("file")) {
      String encoded = location.getFile();
      File classFileLocation = null;
      try {
        String decoded = URLDecoder.decode(encoded, "UTF-8"); // important
        classFileLocation = new File(decoded);

      } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
      } // end try
      if (classFileLocation != null) {
        File root = classFileLocation;
        String classname = GenerationTarget.class.getName();
        int levels = countNbChars(classname, '.');

        // iterate to the root
        for (int i = 0; i < levels; i++) {
          root = root.getParentFile();
        } // end while

        scanFolder(classFileLocation.getParentFile(), root, m_targets);
      }
    } else if (location.getProtocol().equals("jar")) {
      String jarname = location.toExternalForm();
      int index = jarname.indexOf(".jar!");
      if (index > -1) jarname = jarname.substring(0, index + 4);
      index = jarname.indexOf("jar:");
      if (index > -1) {
        jarname = jarname.substring(4);
      }
      index = jarname.indexOf("file:/");
      if (index > -1) {
        jarname = jarname.substring(6);
      }
      index = jarname.indexOf("file:");
      if (index > -1) {
        jarname = jarname.substring(5);
      }
      scanJar(new File(jarname), new File(System.getProperty("java.io.tmpdir")), m_targets);
    }

    return m_targets;
  }
  /**
   * Whether the requested redirect URI "matches" the specified redirect URI. For a URL, this
   * implementation tests if the user requested redirect starts with the registered redirect, so it
   * would have the same host and root path if it is an HTTP URL.
   *
   * <p>For other (non-URL) cases, such as for some implicit clients, the redirect_uri must be an
   * exact match.
   *
   * @param requestedRedirect The requested redirect URI.
   * @param redirectUri The registered redirect URI.
   * @return Whether the requested redirect URI "matches" the specified redirect URI.
   */
  protected boolean redirectMatches(String requestedRedirect, String redirectUri) {
    try {
      URL req = new URL(requestedRedirect);
      URL reg = new URL(redirectUri);

      if (reg.getProtocol().equals(req.getProtocol()) && reg.getHost().equals(req.getHost())) {
        return requestedRedirect.startsWith(redirectUri);
      }
    } catch (MalformedURLException e) {
    }
    return requestedRedirect.equals(redirectUri);
  }
 public static String convertHref(URL baseURL, String href) {
   if (href == null) return href;
   if (href.startsWith("/")) return baseURL.getProtocol() + "://" + baseURL.getHost() + href;
   if (!href.startsWith("http://"))
     return baseURL.getProtocol()
         + "://"
         + baseURL.getHost()
         + "/"
         + baseURL.getPath()
         + "/"
         + href;
   return href;
 }
Exemple #29
0
  /**
   * Enumerates the resouces in a give package name. This works even if the resources are loaded
   * from a jar file!
   *
   * <p>Adapted from code by mikewse on the java.sun.com message boards.
   * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
   *
   * @param packageName The package to enumerate
   * @return A Set of Strings for each resouce in the package.
   */
  public static Set getResoucesInPackage(String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
      localPackageName = packageName;
    } else {
      localPackageName = packageName + '/';
    }

    Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName);

    Set names = new HashSet();

    // Loop CLASSPATH directories
    while (dirEnum.hasMoreElements()) {
      URL resUrl = (URL) dirEnum.nextElement();

      // Pointing to filesystem directory
      if (resUrl.getProtocol().equals("file")) {
        File dir = new File(resUrl.getFile());
        File[] files = dir.listFiles();
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) continue;
            names.add(localPackageName + file.getName());
          }
        }

        // Pointing to Jar file
      } else if (resUrl.getProtocol().equals("jar")) {
        JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
        JarFile jfile = jconn.getJarFile();
        Enumeration entryEnum = jfile.entries();
        while (entryEnum.hasMoreElements()) {
          JarEntry entry = (JarEntry) entryEnum.nextElement();
          String entryName = entry.getName();
          // Exclude our own directory
          if (entryName.equals(localPackageName)) continue;
          String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
          if (!parentDirName.equals(localPackageName)) continue;
          names.add(entryName);
        }
      } else {
        // Invalid classpath entry
      }
    }

    return names;
  }
  public URLConnection openConnection(URL url) throws IOException {
    if (expectedUrl == null) {
      throw new IllegalStateException("expectedUrl was not set");
    }

    // the caller copied the URL reusing a stream handler from a previous call
    if (!expectedUrl.equals(url)) {
      // the new url is supposed to be within our context, so it must have a jar protocol
      if (!url.getProtocol().equals("jar")) {
        throw new IllegalArgumentException("Unsupported protocol " + url.getProtocol());
      }

      // split the path at "!/" into the file part and entry part
      String path = url.getPath();
      String[] chunks = path.split("!/", 2);

      // if we only got only one chunk, it didn't contain the required "!/" delimiter
      if (chunks.length == 1) {
        throw new MalformedURLException("Url does not contain a '!' character: " + url);
      }

      String file = chunks[0];
      String entryPath = chunks[1];

      // this handler only supports jars on the local file system
      if (!file.startsWith("file:")) {
        // let the system handler deal with this
        return new URL(url.toExternalForm()).openConnection();
      }
      file = file.substring("file:".length());

      // again the new url is supposed to be within our context so it must reference the same jar
      // file
      if (!jarFile.getName().equals(file)) {
        // let the system handler deal with this
        return new URL(url.toExternalForm()).openConnection();
      }

      // get the entry
      JarEntry newEntry = jarFile.getJarEntry(entryPath);
      if (newEntry == null) {
        throw new FileNotFoundException("Entry not found: " + url);
      }
      return new JarFileUrlConnection(url, jarFile, newEntry);
    }

    return new JarFileUrlConnection(url, jarFile, jarEntry);
  }