Beispiel #1
0
  /** Try and make path relative to current directory. */
  public static String getRelativePath(String path) {

    try {
      File currentDir = new File(".");
      String currentPath = null;
      currentPath = currentDir.getCanonicalPath();

      if (currentPath != null) {
        // get canonical path of file, to
        // fix case problems with drive letters in Windows.
        File pathFile = new File(path);
        String canonicalPath = pathFile.getCanonicalPath();

        if (canonicalPath.startsWith(currentPath)) {
          String relativePath = canonicalPath.substring(currentPath.length());

          // hmm, unix doesn't have trailing / on
          // current dir canonical path, so remove any
          // that are left on the front of the path here.
          while (relativePath.charAt(0) == '/' || relativePath.charAt(0) == '\\') {
            relativePath = relativePath.substring(1);
          }

          return relativePath;
        }
        return path;
      }
    } catch (Exception e) {
      return path;
    }

    return path;
  }
  private boolean checkIfRequestedFileLegal(HtmlRequest htmlRequest) throws IOException {

    String requestedFileStr = htmlRequest.requestedFile;

    // Check if it is default
    if (requestedFileStr.equals("/")) {
      htmlRequest.requestedFile = "/" + defaultPage.toString();
      requestedFileStr = htmlRequest.requestedFile;
    }
    String requestedFileFullPath = rootDirectory.getCanonicalPath() + requestedFileStr;
    File requestedFile = new File(requestedFileFullPath);

    // Checking that the requested file path is under the root directory
    if (!requestedFile.getAbsolutePath().startsWith(rootDirectory.getCanonicalPath())) {
      return false;
    }

    // Checking if it is a directory
    if (requestedFile.isDirectory()) {
      return false;
    }

    // Check if the file exists
    if (!requestedFile.exists()) {
      return false;
    }

    return true;
  }
  private String prepareResultPagesSection() {

    String resultsPath;
    try {
      resultsPath = rootDirectory.getCanonicalPath() + Crawler.RESULTS_PATH_LOCAL;
    } catch (IOException e) {
      System.out.println("HTTPRequest: Error root directory" + rootDirectory.toString());
      return "";
    }

    StringBuilder result = new StringBuilder();
    result.append("<div class=\"connectedDomains\"><ul>");
    File resultsFolder = new File(resultsPath);
    if (resultsFolder.exists() && resultsFolder.isDirectory()) {
      File[] allFiles = resultsFolder.listFiles();
      SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy-HH:mm");
      for (File file : allFiles) {
        String filename = file.getName();
        String domain = Crawler.ResultsFilenameToDomain(filename);
        Date creationDate = Crawler.ResultsFilenameToDate(filename);
        String linkFormat = domain + "-" + format.format(creationDate);
        result.append("<li><a href=");
        result.append(Crawler.RESULTS_PATH_WEB);
        result.append(filename);
        result.append(">");
        result.append(linkFormat);
        result.append("</a></li>");
      }

      result.append("</ul></div>");
    }

    return result.toString();
  }
  private String listFiles(final File cache, List<File> toDelete) throws Exception {
    boolean stopServices = false;
    if (toDelete == null) {
      toDelete = new ArrayList<File>();
    } else {
      stopServices = true;
    }
    int count = 0;
    Formatter f = new Formatter();

    f.format(" - Cache:%n    * %s%n", cache.getCanonicalPath());
    f.format(" - Commands:%n");
    for (CommandData cdata : getCommands(new File(cache, COMMANDS))) {
      f.format("    * %s \t0 handle for \"%s\"%n", cdata.bin, cdata.name);
      toDelete.add(new File(cdata.bin));
      count++;
    }
    f.format(" - Services:%n");
    for (ServiceData sdata : getServices(new File(cache, SERVICE))) {
      if (sdata != null) {
        f.format("    * %s \t0 service directory for \"%s\"%n", sdata.sdir, sdata.name);
        toDelete.add(new File(sdata.sdir));
        File initd = platform.getInitd(sdata);
        if (initd != null && initd.exists()) {
          f.format("    * %s \t0 init.d file for \"%s\"%n", initd.getCanonicalPath(), sdata.name);
          toDelete.add(initd);
        }
        if (stopServices) {
          Service s = getService(sdata);
          try {
            s.stop();
          } catch (Exception e) {
          }
        }
        count++;
      }
    }
    f.format("%n");

    String result = (count > 0) ? f.toString() : null;
    f.close();
    return result;
  }
  private byte[] readFileForResponse(HtmlRequest htmlRequest) throws IOException {

    if (htmlRequest.requestedFile.equals("/")
        || htmlRequest.requestedFile.equals("/" + defaultPage.getName())) {
      fullPathForFile = rootDirectory.getCanonicalPath() + "\\" + defaultPage.getName();
      return prepareDefaultPage(null);
    } else {
      fullPathForFile = rootDirectory.getCanonicalPath() + htmlRequest.requestedFile;
    }

    File file = new File(fullPathForFile);
    byte[] buffer = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(buffer, 0, buffer.length);
    bis.close();

    return buffer;
  }
Beispiel #6
0
 /** If RESTRICT_BROWSING = true this method checks, whether the path is allowed or not */
 public static boolean isAllowed(File path, boolean write) throws IOException {
   if (READ_ONLY && write) return false;
   if (RESTRICT_BROWSING) {
     StringTokenizer stk = new StringTokenizer(RESTRICT_PATH, ";");
     while (stk.hasMoreTokens()) {
       if (path != null && path.getCanonicalPath().startsWith(stk.nextToken()))
         return RESTRICT_WHITELIST;
     }
     return !RESTRICT_WHITELIST;
   } else return true;
 }
Beispiel #7
0
  // TODO hhw 这个方法不太理解
  public String getPathFromClass(Class cls) throws IOException {
    String path = null;
    if (cls == null) {
      throw new NullPointerException();
    }
    URL url = getClassLocationURL(cls);
    if (url != null) {
      path = url.getPath();
      if ("jar".equalsIgnoreCase(url.getProtocol())) {
        try {
          path = new URL(path).getPath();
        } catch (MalformedURLException e) {
        }
        int location = path.indexOf("!/");
        if (location != -1) {
          path = path.substring(0, location);
        }
      }

      File file = new File(path.replaceAll("%20", " "));
      path = file.getCanonicalPath();
    }
    return path;
  }
  public String what(String key, boolean oneliner) throws Exception {
    byte[] sha;

    Matcher m = SHA_P.matcher(key);
    if (m.matches()) {
      sha = Hex.toByteArray(key);
    } else {
      m = URL_P.matcher(key);
      if (m.matches()) {
        URL url = new URL(key);
        sha = SHA1.digest(url.openStream()).digest();
      } else {
        File jarfile = new File(key);
        if (!jarfile.exists()) {
          reporter.error("File does not exist: %s", jarfile.getCanonicalPath());
        }
        sha = SHA1.digest(jarfile).digest();
      }
    }
    reporter.trace("sha %s", Hex.toHexString(sha));
    Revision revision = library.getRevision(sha);
    if (revision == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    Justif justif = new Justif(120, 20, 70, 20, 75);
    DateFormat dateFormat = DateFormat.getDateInstance();

    try {
      if (oneliner) {
        f.format("%20s %s%n", Hex.toHexString(revision._id), createCoord(revision));
      } else {
        f.format("Artifact: %s%n", revision.artifactId);
        if (revision.organization != null && revision.organization.name != null) {
          f.format(" (%s)", revision.organization.name);
        }
        f.format("%n");
        f.format("Coordinates\t0: %s%n", createCoord(revision));
        f.format("Created\t0: %s%n", dateFormat.format(new Date(revision.created)));
        f.format("Size\t0: %d%n", revision.size);
        f.format("Sha\t0: %s%n", Hex.toHexString(revision._id));
        f.format("URL\t0: %s%n", createJpmLink(revision));
        f.format("%n");
        f.format("%s%n", revision.description);
        f.format("%n");
        f.format("Dependencies\t0:%n");
        boolean flag = false;
        Iterable<RevisionRef> closure = library.getClosure(revision._id, true);
        for (RevisionRef dep : closure) {
          f.format(
              " - %s \t2- %s \t3- %s%n",
              dep.name, createCoord(dep), dateFormat.format(new Date(dep.created)));
          flag = true;
        }
        if (!flag) {
          f.format("     None%n");
        }
        f.format("%n");
      }
      f.flush();
      justif.wrap(sb);
      return sb.toString();
    } finally {
      f.close();
    }
  }
  public CommandData parseCommandData(ArtifactData artifact) throws Exception {
    File source = new File(artifact.file);
    if (!source.isFile()) throw new FileNotFoundException();

    CommandData data = new CommandData();
    data.sha = artifact.sha;
    data.jpmRepoDir = repoDir.getCanonicalPath();
    JarFile jar = new JarFile(source);
    try {
      reporter.trace("Parsing %s", source);
      Manifest m = jar.getManifest();
      Attributes main = m.getMainAttributes();
      data.name = data.bsn = main.getValue("Bundle-SymbolicName");
      String version = main.getValue("Bundle-Version");
      if (version == null) data.version = Version.LOWEST;
      else data.version = new Version(version);

      data.main = main.getValue("Main-Class");
      data.description = main.getValue("Bundle-Description");
      data.title = main.getValue("JPM-Name");

      reporter.trace("name " + data.name + " " + data.main + " " + data.title);
      DependencyCollector path = new DependencyCollector(this);
      path.add(artifact);
      DependencyCollector bundles = new DependencyCollector(this);
      if (main.getValue("JPM-Classpath") != null) {
        Parameters requires = OSGiHeader.parseHeader(main.getValue("JPM-Classpath"));

        for (Map.Entry<String, Attrs> e : requires.entrySet()) {
          path.add(e.getKey(), e.getValue().get("name")); // coordinate
        }
      } else if (!artifact.local) { // No JPM-Classpath, falling back to
        // server's revision
        // Iterable<RevisionRef> closure =
        // library.getClosure(artifact.sha,
        // false);
        // System.out.println("getting closure " + artifact.url + " " +
        // Strings.join("\n",closure));

        // if (closure != null) {
        // for (RevisionRef ref : closure) {
        // path.add(Hex.toHexString(ref.revision));
        // }
        // }
      }

      if (main.getValue("JPM-Runbundles") != null) {
        Parameters jpmrunbundles = OSGiHeader.parseHeader(main.getValue("JPM-Runbundles"));

        for (Map.Entry<String, Attrs> e : jpmrunbundles.entrySet()) {
          bundles.add(e.getKey(), e.getValue().get("name"));
        }
      }

      reporter.trace("collect digests runpath");
      data.dependencies.addAll(path.getDigests());
      reporter.trace("collect digests bundles");
      data.runbundles.addAll(bundles.getDigests());

      Parameters command = OSGiHeader.parseHeader(main.getValue("JPM-Command"));
      if (command.size() > 1) reporter.error("Only one command can be specified");

      for (Map.Entry<String, Attrs> e : command.entrySet()) {
        data.name = e.getKey();

        Attrs attrs = e.getValue();

        if (attrs.containsKey("jvmargs")) data.jvmArgs = attrs.get("jvmargs");

        if (attrs.containsKey("title")) data.title = attrs.get("title");

        if (data.title != null) data.title = data.name;
      }
      return data;
    } finally {
      jar.close();
    }
  }