/**
   * If <code>f</code> is a file, this method will make a single call to S3. If <code>f</code> is a
   * directory, this method will make a maximum of (<i>n</i> / 1000) + 2 calls to S3, where <i>n</i>
   * is the total number of files and directories contained directly in <code>f</code>.
   */
  @Override
  public FileStatus[] listStatus(Path f) throws IOException {

    Path absolutePath = makeAbsolute(f);
    String key = pathToKey(absolutePath);

    if (key.length() > 0) {
      FileMetadata meta = store.retrieveMetadata(key);
      if (meta != null) {
        return new FileStatus[] {newFile(meta, absolutePath)};
      }
    }

    URI pathUri = absolutePath.toUri();
    Set<FileStatus> status = new TreeSet<FileStatus>();
    String priorLastKey = null;
    do {
      PartialListing listing = store.list(key, S3_MAX_LISTING_LENGTH, priorLastKey, false);
      for (FileMetadata fileMetadata : listing.getFiles()) {
        Path subpath = keyToPath(fileMetadata.getKey());
        String relativePath = pathUri.relativize(subpath.toUri()).getPath();

        if (fileMetadata.getKey().equals(key + "/")) {
          // this is just the directory we have been asked to list
        } else if (relativePath.endsWith(FOLDER_SUFFIX)) {
          status.add(
              newDirectory(
                  new Path(
                      absolutePath,
                      relativePath.substring(0, relativePath.indexOf(FOLDER_SUFFIX)))));
        } else {
          status.add(newFile(fileMetadata, subpath));
        }
      }
      for (String commonPrefix : listing.getCommonPrefixes()) {
        Path subpath = keyToPath(commonPrefix);
        String relativePath = pathUri.relativize(subpath.toUri()).getPath();
        status.add(newDirectory(new Path(absolutePath, relativePath)));
      }
      priorLastKey = listing.getPriorLastKey();
    } while (priorLastKey != null);

    if (status.isEmpty()
        && key.length() > 0
        && store.retrieveMetadata(key + FOLDER_SUFFIX) == null) {
      throw new FileNotFoundException("File " + f + " does not exist.");
    }

    return status.toArray(new FileStatus[status.size()]);
  }
Esempio n. 2
0
  public void test_relativizeBasedOneEclipseCoreResources() throws URISyntaxException {
    URI one = new URI("file:/C:/test/ws");
    URI two = new URI("file:/C:/test/ws");

    URI empty = new URI("");
    assertEquals(empty, one.relativize(two));

    one = new URI("file:/C:/test/ws");
    two = new URI("file:/C:/test/ws/p1");
    URI result = new URI("p1");
    assertEquals(result, one.relativize(two));

    one = new URI("file:/C:/test/ws/");
    assertEquals(result, one.relativize(two));
  }
Esempio n. 3
0
  /**
   * adapt recursively
   *
   * @param file
   * @param elements
   * @param container
   */
  private void adapt(File file, List<IElement> elements, IElement container) {
    FileElement newElement = null;
    if (PluginInfosExtractor.isAPlugin(file)) {
      try {
        // Unzipped plugin
        if (file.isDirectory()) {
          newElement =
              PluginInfosExtractor.getPluginInfosFromManifest(
                  file.getAbsolutePath() + "/META-INF/MANIFEST.MF");
        } else {
          // Jar plugin
          newElement = PluginInfosExtractor.getPluginInfosFromJar(file.getAbsolutePath());
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      newElement = new FileElement();
    }

    // Set the relevant information
    newElement.setUri(file.toURI());
    newElement.setRelativeURI(rootURI.relativize(file.toURI()));

    // Add dependency to the parent folder
    if (container != null) {
      newElement.addDependency("container", container);
    }

    // Add the bundles info
    if (newElement instanceof PluginElement) {
      PluginElement plugin = (PluginElement) newElement;
      String line = bundlesInfoLines.get(plugin.getSymbName());
      // in the case of source code plugins, line will be null but no
      // problem
      plugin.setBundleInfoLine(line);

      if (plugin.getName() == null || plugin.getName().contains("%")) {
        System.out.println(
            "EclipseAdapter.adapt() No name found for: "
                + plugin.isFragment()
                + "  "
                + plugin.getSymbName());
      }
    }

    // Add to the list
    elements.add(newElement);

    // Go for the files in case of folder
    if (file.isDirectory()) {
      // Exclude the features folder
      if (!newElement.getRelativeURI().toString().equals("features/")) {
        File[] files = file.listFiles();
        for (File subFile : files) {
          adapt(subFile, elements, newElement);
        }
      }
    }
  }
Esempio n. 4
0
 private static void addFile(ZipOutputStream zipOutputStream, URI base, File file)
     throws IOException {
   String name = base.relativize(file.toURI()).getPath();
   zipOutputStream.putNextEntry(new ZipEntry(name));
   copy(file, zipOutputStream);
   zipOutputStream.closeEntry();
 }
  public InputStream openResource(URI uri) throws IOException {
    if (uri.isAbsolute() && uri.getScheme().equals("file")) {
      try {
        return uri.toURL().openStream();
      } catch (Exception except) {
        log.error("openResource: unable to open file URL " + uri + "; " + except.toString());
        return null;
      }
    }

    // Note that if we get an absolute URI, the relativize operation will simply
    // return the absolute URI.
    URI relative = baseUri.relativize(uri);

    if (relative.isAbsolute() && relative.getScheme().equals("http")) {
      try {
        return relative.toURL().openStream();
      } catch (Exception except) {
        log.error("openResource: unable to open http URL " + uri + "; " + except.toString());
        return null;
      }
    }

    if (relative.isAbsolute() && !relative.getScheme().equals("urn")) {
      log.error("openResource: invalid scheme (should be urn:)  " + uri);
      return null;
    }

    File f = new File(baseUri.getPath(), relative.getPath());
    if (!f.exists()) {
      log.error("openResource: file not found " + f);
      return null;
    }
    return new FileInputStream(f);
  }
Esempio n. 6
0
    private void joinFileFromLocalBase() throws Exception {

      String theLocalBaseDir = myProperties.getProperty("LOCALBASEDIR");
      File theLocalBase = new File(theLocalBaseDir);
      validateDirectory(theLocalBase);
      List<File> theList = getFileListingNoSort(theLocalBase);
      URI theLocalBaseURI = theLocalBase.toURI();
      Iterator it3 = theList.iterator();
      File theFile;
      URI theFileURI;
      String relative;
      String[] theFileSelectionList = new String[theList.size()];
      int j = 0;
      while (it3.hasNext()) {
        theFile = (File) it3.next();
        theFileURI = theFile.toURI();
        relative = theLocalBaseURI.relativize(theFileURI).getPath();
        theFileSelectionList[j] = relative;
        j++;
      }

      String[] theStr = FileSelectionListFrame.getFileList(theFileSelectionList);
      for (int i = 0; i < theStr.length; i++) {
        URI theJoinFileURI = new URI(theLocalBaseURI.toString() + theStr[i]);
        File theMD5File = new File(theJoinFileURI.getPath());
        // System.out.print(String.format("File %1$s Exists? %2$s",
        // theLocalBase.getAbsolutePath()+"test.txt",theMD5File.exists()));
        join(theMD5File);
      }
      System.out.println("Out of joinFileFromLocalBase");
    }
 /** Walk project references recursively, adding thrift files to the provided list. */
 List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files)
     throws IOException {
   HashFunction hashFun = Hashing.md5();
   if (dependencyIncludes.contains(project.getArtifactId())) {
     File dir = new File(new File(project.getFile().getParent(), "target"), outputDirectory);
     if (dir.exists()) {
       URI baseDir = getFileURI(dir);
       for (File f : findThriftFilesInDirectory(dir)) {
         URI fileURI = getFileURI(f);
         String relPath = baseDir.relativize(fileURI).getPath();
         File destFolder = getResourcesOutputDirectory();
         destFolder.mkdirs();
         File destFile = new File(destFolder, relPath);
         if (!destFile.exists()
             || (destFile.isFile()
                 && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {
           getLog()
               .info(
                   format("copying %s to %s", f.getCanonicalPath(), destFile.getCanonicalPath()));
           copyFile(f, destFile);
         }
         files.add(destFile);
       }
     }
   }
   Map<String, MavenProject> refs = project.getProjectReferences();
   for (String name : refs.keySet()) {
     getRecursiveThriftFiles(refs.get(name), outputDirectory, files);
   }
   return files;
 }
  /** Copies all entries under the file path. */
  private void copyFileEntries(
      File baseDir, String entryRoot, Set<String> entries, JarOutputStream jarOut)
      throws IOException {
    URI baseUri = baseDir.toURI();
    File packageFile = new File(baseDir, entryRoot);
    Queue<File> queue = Lists.newLinkedList();
    queue.add(packageFile);
    while (!queue.isEmpty()) {
      File file = queue.remove();

      String entry = baseUri.relativize(file.toURI()).getPath();
      if (entries.add(entry)) {
        jarOut.putNextEntry(new JarEntry(entry));
        if (file.isFile()) {
          Files.copy(file, jarOut);
        }
        jarOut.closeEntry();
      }

      if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
          queue.addAll(Arrays.asList(files));
        }
      }
    }
  }
  private void createFileSyncConfig(MavenProject prj) throws Exception {
    File configFile = new File(prj.getBasedir(), FILE_SYNC_CONFIG_FILE);
    getLog().info("[WarSync] Create FileSync Config: " + configFile.getAbsolutePath());
    URI BaseURI = prj.getBasedir().toURI();
    configFile.getParentFile().mkdirs();
    String filterFile = projectFilters.get(getProjectReferenceId(prj.getArtifact()));
    if (filterFile == null && !prj.getFilters().isEmpty()) {
      filterFile = (String) prj.getFilters().get(0);
      if (filterFile != null) {
        filterFile = BaseURI.relativize(new File(filterFile).toURI()).getPath();
      }
    }
    PrintWriter writer = null;
    try {
      int index = 0;
      writer = new PrintWriter(configFile);
      writer.println("defaultDestination=" + FileSyncMap.formatPath(warDir.getAbsolutePath()));
      writer.println("eclipse.preferences.version=1");
      writer.println("includeTeamPrivateFiles=false");
      writer.println("useCurrentDateForDestinationFiles=false");
      if (prj == project) {
        FileSyncMap webRootMap = new FileSyncMap(index++);
        webRootMap.setSourceFolder(BaseURI.relativize(warSrcDir.toURI()).getPath());
        webRootMap.setExcludePatterns("WEB-INF/");
        writer.println(webRootMap.render());

        FileSyncMap webInfoMap = new FileSyncMap(index++);
        webInfoMap.setSourceFolder(
            BaseURI.relativize(new File(warSrcDir, "WEB-INF").toURI()).getPath());
        webInfoMap.setDestFolder(new File(warDir, "WEB-INF").getAbsolutePath());
        webInfoMap.setFilterFile(filterFile);
        writer.println(webInfoMap.render());
      }

      FileSyncMap classMap = new FileSyncMap(index++);
      classMap.setSourceFolder(
          BaseURI.relativize(new File(prj.getBuild().getOutputDirectory()).toURI()).getPath());
      classMap.setDestFolder(new File(warDir, "WEB-INF/classes").getAbsolutePath());
      classMap.setFilterFile(filterFile);
      writer.println(classMap.render());
    } finally {
      if (writer != null) {
        writer.flush();
        writer.close();
      }
    }
  }
 private String getId(PublishArtifact artifact, Project project) {
   // Assume that each artifact points to a unique file, and use the relative path from the project
   // as the id
   URI artifactUri = artifact.getFile().toURI();
   URI projectDirUri = project.getProjectDir().toURI();
   URI relativeUri = projectDirUri.relativize(artifactUri);
   return relativeUri.getPath();
 }
  /**
   * Get a {@link org.kitesdk.data.PartitionKey} corresponding to a partition's filesystem path
   * represented as a {@link URI}. If the path is not a valid partition, then {@link
   * IllegalArgumentException} is thrown. Note that the partition does not have to exist.
   *
   * @param dataset the filesystem dataset
   * @param partitionPath a directory path where the partition data is stored
   * @return a partition key representing the partition at the given path
   * @since 0.4.0
   */
  @SuppressWarnings("deprecation")
  public static PartitionKey partitionKeyForPath(Dataset dataset, URI partitionPath) {
    Preconditions.checkState(
        dataset.getDescriptor().isPartitioned(),
        "Attempt to get a partition on a non-partitioned dataset (name:%s)",
        dataset.getName());

    Preconditions.checkArgument(
        dataset instanceof FileSystemDataset, "Dataset is not a FileSystemDataset");
    FileSystemDataset fsDataset = (FileSystemDataset) dataset;

    FileSystem fs = fsDataset.getFileSystem();
    URI partitionUri = fs.makeQualified(new Path(partitionPath)).toUri();
    URI directoryUri = fsDataset.getDirectory().toUri();
    URI relativizedUri = directoryUri.relativize(partitionUri);

    if (relativizedUri.equals(partitionUri)) {
      throw new IllegalArgumentException(
          String.format(
              "Partition URI %s has different " + "root directory to dataset (directory: %s).",
              partitionUri, directoryUri));
    }

    Iterable<String> parts = Splitter.on('/').split(relativizedUri.getPath());

    PartitionStrategy partitionStrategy = dataset.getDescriptor().getPartitionStrategy();
    List<FieldPartitioner> fieldPartitioners = partitionStrategy.getFieldPartitioners();
    if (Iterables.size(parts) > fieldPartitioners.size()) {
      throw new IllegalArgumentException(
          String.format(
              "Too many partition directories " + "for %s (%s), expecting %s.",
              partitionUri, Iterables.size(parts), fieldPartitioners.size()));
    }

    List<Object> values = Lists.newArrayList();
    int i = 0;
    for (String part : parts) {
      Iterator<String> split = Splitter.on('=').split(part).iterator();
      String fieldName = split.next();
      FieldPartitioner fp = fieldPartitioners.get(i++);
      if (!fieldName.equals(fp.getName())) {
        throw new IllegalArgumentException(
            String.format(
                "Unrecognized partition name " + "'%s' in partition %s, expecting '%s'.",
                fieldName, partitionUri, fp.getName()));
      }
      if (!split.hasNext()) {
        throw new IllegalArgumentException(
            String.format(
                "Missing partition value for " + "'%s' in partition %s.", fieldName, partitionUri));
      }
      String stringValue = split.next();
      Object value = fp.valueFromString(stringValue);
      values.add(value);
    }
    return org.kitesdk.data.impl.Accessor.getDefault()
        .newPartitionKey(values.toArray(new Object[values.size()]));
  }
Esempio n. 12
0
  /** @tests java.net.URI#relativize(java.net.URI) */
  public void test_relativizeLjava_net_URI() throws URISyntaxException {
    URI a = new URI("http://host/dir");
    URI b = new URI("http://host/dir/file?query");
    assertEquals("Assert 0: URI relativized incorrectly,", new URI("file?query"), a.relativize(b));

    // One URI with empty host
    a = new URI("file:///~/first");
    b = new URI("file://tools/~/first");
    assertEquals(
        "Assert 1: URI relativized incorrectly,", new URI("file://tools/~/first"), a.relativize(b));
    assertEquals(
        "Assert 2: URI relativized incorrectly,", new URI("file:///~/first"), b.relativize(a));

    // Both URIs with empty hosts
    b = new URI("file:///~/second");
    assertEquals(
        "Assert 3: URI relativized incorrectly,", new URI("file:///~/second"), a.relativize(b));
    assertEquals(
        "Assert 4: URI relativized incorrectly,", new URI("file:///~/first"), b.relativize(a));
  }
Esempio n. 13
0
  public void testRelativeResolve() {
    String sa = "file:///D:/a/a";
    String sb = "file:///D:/a/a/b";
    URI ua = URI.create(sa);
    URI ub = URI.create(sb);
    Path a = Paths.get(ua);
    Path b = Paths.get(ub);
    System.out.println(sa + " vs " + sb);
    System.out.println("Relativize: " + a.relativize(b)); // = b - a
    System.out.println("Resolve: " + a.resolve(b)); // = a + b

    System.out.println(ua.relativize(ub));
  }
Esempio n. 14
0
 /**
  * Create a ResearchObject from given zip as input stream.
  *
  * @param id Research Object id
  * @param input The content of the zip aggreagated ResearchObject
  * @return a instance of ResearchObject
  */
 @SuppressWarnings("resource")
 public static ResearchObjectSerializable toResearchObject(URI id, InputStream input) {
   File tmpZipFile = null;
   ZipFile zipFile = null;
   try {
     tmpZipFile = File.createTempFile("zipInput", ".zip");
     IOUtils.copy(input, new FileOutputStream(tmpZipFile));
     zipFile = new ZipFile(tmpZipFile);
   } catch (IOException e) {
     LOGGER.error("Can't create a tmpFile for a RO " + id + " given from dArceo", e);
     return null;
   }
   Enumeration<? extends ZipEntry> entries = zipFile.entries();
   // first get Manifest build Jena and parese it
   ResearchObject researchObject = new ResearchObject(id);
   while (entries.hasMoreElements()) {
     ZipEntry entry = entries.nextElement();
     if (entry.getName().equals("content/.ro/manifest.rdf")) {
       OntModel model = ModelFactory.createOntologyModel();
       try {
         model.read(zipFile.getInputStream(entry), id.toString() + ".ro/");
         Individual roIndividual = model.getResource(id.toString()).as(Individual.class);
         for (RDFNode node : roIndividual.listPropertyValues(ORE.aggregates).toList()) {
           if (node.isURIResource()) {
             URI resourceUri = URI.create(node.asResource().getURI());
             URI entryName =
                 URI.create("content/")
                     .resolve(id.relativize(URI.create(node.asResource().getURI())).toString());
             InputStream entryInput = zipFile.getInputStream(new ZipEntry(entryName.toString()));
             researchObject.addSerializable(new ResearchObjectComponent(resourceUri, entryInput));
           }
         }
         // add manifest
         InputStream entryInput = zipFile.getInputStream(new ZipEntry("content/.ro/manifest.rdf"));
         researchObject.addSerializable(
             new ResearchObjectComponent(id.resolve(".ro/manifest.rdf"), entryInput));
         break;
       } catch (IOException e) {
         LOGGER.error("can't load the manifest from zip for RO " + id, e);
         tmpZipFile.delete();
         return researchObject;
       }
     }
   }
   tmpZipFile.delete();
   return researchObject;
 }
Esempio n. 15
0
  public URI newId(URI graphURI, URI type) throws MetadataRepositoryException {
    String shorttype = "UnknownTypeNS";
    for (URI ns : KnownPrefixes.getNamespaces()) {
      URI typeFrag = ns.relativize(type);
      if (!typeFrag.equals(type)) {
        if (typeFrag.getScheme() != null
            || typeFrag.getAuthority() != null
            || typeFrag.getQuery() != null) {
          logger.warn("Unexpected resolved shorttype. type:{} ns:{} short:{}", type, ns, typeFrag);
          continue;
        }
        String fragment = typeFrag.getFragment();
        String path = typeFrag.getPath();
        if ((fragment == null || fragment.isEmpty()) && (path == null || path.isEmpty())) {
          logger.info(
              "No fragment or path found in shorttype. type:{} ns:{} short:{}", type, ns, typeFrag);
          continue;
        } else if (fragment == null || fragment.isEmpty()) {
          shorttype = path;
        } else if (path == null || path.isEmpty()) {
          shorttype = fragment;
        } else {
          logger.info(
              "Both fragment or path found in shorttype. "
                  + "type:{} ns:{} short:{} fragment:'{}' path:'{}'",
              type,
              ns,
              typeFrag,
              fragment,
              path);
        }
      }
    }

    logger.info("Resolving {} against {}", shorttype, graphURI);
    URI entityBase = graphURI.resolve(shorttype);

    String id = getNextIdForUser(graphURI);

    try {
      return new URI(entityBase.getScheme(), entityBase.getSchemeSpecificPart(), id);
    } catch (URISyntaxException eu) {
      logger.error("Invalid URI generated by newAnnotationId", eu);
      throw new MetadataRepositoryException("Invalid URI generated by newAnnotationId", eu);
    }
  }
Esempio n. 16
0
  private static void addDirectory(
      ZipOutputStream zipOutputStream, Deque<File> queue, Set<String> names, URI base, File file)
      throws IOException {
    String name = base.relativize(file.toURI()).getPath();
    name = name.endsWith("/") ? name : name + "/";

    if (names.add(name)) {
      zipOutputStream.putNextEntry(new ZipEntry(name));
    }

    File[] files = file.listFiles();
    if (files != null) {
      for (File kid : files) {
        queue.push(kid);
      }
    }
  }
Esempio n. 17
0
  public static URI getLocalName(URI prefix, URI identifier)
      throws InvalidIdentifierException, NamingAuthorityConfigurationException {
    try {
      verifyPrefix(prefix);
    } catch (Exception e) {
      throw new NamingAuthorityConfigurationException(e.getMessage());
    }

    String idStr = identifier.normalize().toString();
    String prefixStr = prefix.normalize().toString();
    if (!idStr.startsWith(prefixStr) || prefixStr.length() >= idStr.length()) {
      throw new InvalidIdentifierException(
          "Identifier (" + identifier + ") is not local to prefix (" + prefix + ").");
    }

    return prefix.relativize(identifier);
  }
Esempio n. 18
0
  /**
   * Creates the directories for the specified target, except that if the target is/would be a
   * descendant of the base and the base does not exist don't create anything.
   *
   * <p>This helps avoid a race condition in which the user stops the domain (which apparently
   * reports success long before it actually finishes) then deletes the domain. The delete can run
   * before the server has finished stopping. In some cases, the autodeployer has run in the
   * meantime and
   *
   * @param baseDir
   * @param dir
   * @return true if the directory and all intervening ones were created; false otherwise
   */
  boolean mkdirs(final File baseDir, final File targetDir) {
    final URI baseURI = baseDir.toURI().normalize();
    final URI targetURI = targetDir.toURI().normalize();

    /*
     * Go ahead and create all directories if the target falls outside the
     * base OR if the target falls inside the base and the base exists.
     */
    if (baseURI.relativize(targetURI).equals(targetURI) || baseDir.exists()) {
      return targetDir.mkdirs();
    } else {
      /*
       * The target would fall inside the base but the base does not exist.
       */
      return false;
    }
  }
  public void zip(File from, String to) throws FITTESTException {
    File toFile = new File(to);
    try {
      FileOutputStream fos = new FileOutputStream(toFile);
      ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
      byte data[] = new byte[BUFFER];

      Vector<File> files = collectFiles(from);
      URI base = null;
      if (from.isDirectory()) {
        base = from.toURI();
      }

      for (File f : files) {
        String name = null;
        if (base != null) {
          name = from.getName() + "/" + base.relativize(f.toURI()).getPath();
        } else {
          name = f.getName();
        }

        if (f.isDirectory()) {
          name = name.endsWith("/") ? name : name + "/";
        }

        ZipEntry entry = new ZipEntry(name);
        entry.setTime(f.lastModified());
        zos.putNextEntry(entry);

        if (f.isFile()) {
          BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f), BUFFER);
          int count;
          while ((count = bis.read(data, 0, BUFFER)) != -1) {
            zos.write(data, 0, count);
          }
          bis.close();
        }
        zos.closeEntry();
      }
      zos.close();
    } catch (Exception e) {
      throw new FITTESTException(e.getMessage());
    }
  }
Esempio n. 20
0
  private static MockHttpRequest initWithUri(URI absoluteUri, URI baseUri) {
    if (baseUri == null) baseUri = EMPTY_URI;
    MockHttpRequest request = new MockHttpRequest();
    request.httpHeaders = new ResteasyHttpHeaders(new CaseInsensitiveMap<String>());
    // request.uri = new UriInfoImpl(absoluteUri, absoluteUri, absoluteUri.getPath(),
    // absoluteUri.getQuery(), PathSegmentImpl.parseSegments(absoluteUri.getPath()));

    // remove query part
    URI absolutePath = UriBuilder.fromUri(absoluteUri).replaceQuery(null).build();
    // path must be relative to the application's base uri
    URI relativeUri = baseUri.relativize(absoluteUri);
    relativeUri =
        UriBuilder.fromUri(relativeUri.getRawPath())
            .replaceQuery(absoluteUri.getRawQuery())
            .build();

    request.uri = new ResteasyUriInfo(baseUri, relativeUri);
    return request;
  }
Esempio n. 21
0
    @Override
    protected Object[] doInBackground() throws Exception {
      IOFileFilter pdfFilter = FileFilterUtils.asFileFilter(this);
      IOFileFilter suffixFilter = FileFilterUtils.notFileFilter(new SuffixFileFilter(".fo"));
      IOFileFilter sheetFilter =
          FileFilterUtils.prefixFileFilter(Constants.CHARACTER_TEMPLATE_PREFIX);
      IOFileFilter fileFilter = FileFilterUtils.and(pdfFilter, suffixFilter, sheetFilter);

      IOFileFilter dirFilter = FileFilterUtils.makeSVNAware(TrueFileFilter.INSTANCE);
      File dir = new File(ConfigurationSettings.getOutputSheetsDir());
      Collection<File> files = FileUtils.listFiles(dir, fileFilter, dirFilter);
      URI osPath = new File(ConfigurationSettings.getOutputSheetsDir()).toURI();
      Object[] uriList = new Object[files.size()];
      int i = 0;
      for (File file : files) {
        uriList[i] = osPath.relativize(file.toURI());
        i++;
      }
      return uriList;
    }
  /** @return java class FQN */
  protected String getClassName(final File classesDirectory, final File classFile) {

    final URI folderURI = classesDirectory.toURI();
    final URI fileURI = classFile.toURI();

    final String path = folderURI.relativize(fileURI).getPath();

    /**
     * cut out file extension and convert to java class FQN
     *
     * <p>from: com/carrotgarden/test/TestComp.class
     *
     * <p>into: com.carrotgarden.test.TestComp
     */
    final int index = path.lastIndexOf(".");

    final String name = path.substring(0, index).replace("/", ".");

    return name;
  }
Esempio n. 23
0
 public void _files(FilesOption options) throws Exception {
   URI base = this.options.url();
   for (URI uri : nexus.files()) {
     System.out.printf("%s%n", base.relativize(uri));
   }
 }
Esempio n. 24
0
  /**
   * Returns the URL for the file.
   *
   * @return the associated url
   * @throws IOException if the URL cannot be generated
   */
  public URL makeUrl() throws Exception {

    // return the reference if it was already established
    if (this.referencedUrl != null) return this.referencedUrl;

    String loc = Val.chkStr(this.getLocation());
    URL locUrl = null;

    // determine the base location URIs
    URI rootUri = null;
    List<URI> baseUris = null;
    GxeFile parentFile = this;
    while (parentFile != null) {
      if (parentFile.isRoot) {
        baseUris = parentFile.getBaseLocations();
        break;
      }
      parentFile = parentFile.getParent();
    }
    boolean hasBaseUris = (baseUris != null) && (baseUris.size() > 0);
    if (hasBaseUris) rootUri = baseUris.get(0);

    if (locUrl == null) {
      locUrl = Thread.currentThread().getContextClassLoader().getResource(loc);
    }

    if ((locUrl == null) && !loc.startsWith("$base")) {
      if ((this.getParent() != null) && (this.getParent().getReferencedUrl() != null)) {
        try {
          URL parentUrl = this.getParent().getReferencedUrl();
          URI parentUri = parentUrl.toURI();
          URI thisUri = parentUri.resolve(loc);
          File thisFile = new File(thisUri);
          locUrl = thisUri.toURL();
          if (!thisFile.exists() && hasBaseUris && (rootUri != null)) {
            URI relUri = rootUri.relativize(thisUri);
            int n = baseUris.size();
            for (int i = 0; i < n; i++) {
              URI testUri = baseUris.get(i).resolve(relUri);
              // this won't work for http based URIs
              if ((new File(testUri)).exists()) {
                locUrl = testUri.toURL();
                break;
              }
            }
          }
        } catch (URISyntaxException e) {
          LOGGER.log(
              Level.CONFIG, "While attemting to load: " + loc + ", error: " + e.toString(), e);
        }
      }
    }

    if ((locUrl == null) && loc.startsWith("$base")) {
      String relLoc = Val.chkStr(loc.substring(5));
      if (relLoc.startsWith("/")) relLoc = Val.chkStr(relLoc.substring(1));
      if ((relLoc.length() > 0) && hasBaseUris) {
        try {
          URI relUri = new URI(relLoc);
          int n = baseUris.size();
          for (int i = 0; i < n; i++) {
            URI testUri = baseUris.get(i).resolve(relUri);
            // this won't work for http based URIs
            if ((new File(testUri)).exists()) {
              locUrl = testUri.toURL();
              break;
            }
          }
        } catch (URISyntaxException e) {
          LOGGER.log(
              Level.CONFIG, "While attemting to load: " + loc + ", error: " + e.toString(), e);
        }
      }
    }

    // throw an exception if the URL was not generated, otherwise save and return the reference
    if (locUrl == null) {
      throw new IOException("Unable to create resource URL for path: " + loc);
    } else {
      this.referencedUrl = locUrl;
    }
    return this.referencedUrl;
  }
 private static String relative(URI base, File src) {
   String relative = base.relativize(src.toURI()).getPath().replace('\\', '/');
   if (!relative.endsWith("/")) relative += "/";
   return relative;
 }
  /** Format the collection as an HTML display. */
  @SuppressWarnings({"unchecked"})
  public static void format(
      ContentCollection x,
      Reference ref,
      HttpServletRequest req,
      HttpServletResponse res,
      ResourceLoader rb,
      String accessPointTrue,
      String accessPointFalse) {
    // do not allow directory listings for /attachments and its subfolders
    if (ContentHostingService.isAttachmentResource(x.getId())) {
      try {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      } catch (java.io.IOException e) {
        return;
      }
    }

    PrintWriter out = null;

    // don't set the writer until we verify that
    // getallresources is going to work.
    boolean printedHeader = false;
    boolean printedDiv = false;

    try {
      res.setContentType("text/html; charset=UTF-8");

      out = res.getWriter();

      ResourceProperties pl = x.getProperties();
      String webappRoot = ServerConfigurationService.getServerUrl();
      String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
      String skinName = "default";
      String[] parts = StringUtils.split(x.getId(), Entity.SEPARATOR);

      // Is this a site folder (Resources or Dropbox)? If so, get the site skin

      if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE)
          || x.getId()
              .startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) {
        if (parts.length > 1) {
          String siteId = parts[1];
          try {
            Site site = SiteService.getSite(siteId);
            if (site.getSkin() != null) {
              skinName = site.getSkin();
            }
          } catch (IdUnusedException e) {
            // Cannot get site - ignore it
          }
        }
      }

      // Output the headers

      out.println(
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
      out.println("<html><head>");
      out.println(
          "<title>"
              + rb.getFormattedMessage(
                  "colformat.pagetitle",
                  new Object[] {
                    Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                  })
              + "</title>");
      out.println(
          "<link href=\""
              + webappRoot
              + skinRepo
              + "/"
              + skinName
              + "/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">");
      out.println(
          "<script src=\"" + webappRoot + "/library/js/jquery.js\" type=\"text/javascript\">");
      out.println("</script>");
      out.println("</head><body class=\"specialLink\">");

      out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>");
      out.println("<div class=\"directoryIndex\">");

      // for content listing it's best to use a real title
      out.println(
          "<h3>"
              + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
              + "</h3>");
      out.println(
          "<p id=\"toggle\"><a id=\"toggler\" href=\"#\">"
              + rb.getString("colformat.showhide")
              + "</a></p>");
      String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION);
      if (folderdesc != null && !folderdesc.equals(""))
        out.println("<div class=\"textPanel\">" + folderdesc + "</div>");

      out.println("<ul>");
      out.println("<li style=\"display:none\">");
      out.println("</li>");

      printedHeader = true;
      printedDiv = true;

      if (parts.length > 2) {
        // go up a level
        out.println(
            "<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\""
                + rb.getString("colformat.uplevel.alttext")
                + "\"/>"
                + rb.getString("colformat.uplevel")
                + "</a></li>");
      }

      // Sort the collection items

      List<ContentEntity> members = x.getMemberResources();

      boolean hasCustomSort = false;
      try {
        hasCustomSort =
            x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
      } catch (Exception e) {
        // use false that's already there
      }

      if (hasCustomSort)
        Collections.sort(
            members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true));
      else
        Collections.sort(
            members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true));

      // Iterate through content items

      URI baseUri = new URI(x.getUrl());

      for (ContentEntity content : members) {

        ResourceProperties properties = content.getProperties();
        boolean isCollection = content.isCollection();
        String xs = content.getId();
        String contentUrl = content.getUrl();

        // These both perform the same check in the implementation but we should observe the API.
        // This also checks to see if a resource is hidden or time limited.
        if (isCollection) {
          if (!ContentHostingService.allowGetCollection(xs)) {
            continue;
          }
        } else {
          if (!ContentHostingService.allowGetResource(xs)) {
            continue;
          }
        }

        if (isCollection) {
          xs = xs.substring(0, xs.length() - 1);
          xs = xs.substring(xs.lastIndexOf('/') + 1) + '/';
        } else {
          xs = xs.substring(xs.lastIndexOf('/') + 1);
        }

        try {
          // Relativize the URL (canonical item URL relative to canonical collection URL).
          // Inter alias this will preserve alternate access paths via aliases, e.g. /web/

          URI contentUri = new URI(contentUrl);
          URI relativeUri = baseUri.relativize(contentUri);
          contentUrl = relativeUri.toString();

          if (isCollection) {
            // Folder

            String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
            if ((desc == null) || desc.equals("")) desc = "";
            else desc = "<div class=\"textPanel\">" + desc + "</div>";
            out.println(
                "<li class=\"folder\"><a href=\""
                    + contentUrl
                    + "\">"
                    + Validator.escapeHtml(
                        properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                    + "</a>"
                    + desc
                    + "</li>");
          } else {
            // File

            /*
            String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
            Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
            String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();

            ContentResource contentResource = (ContentResource) content;

            long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1;
            String filetype = contentResource.getContentType();
             */

            String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
            if ((desc == null) || desc.equals("")) desc = "";
            else desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>";
            String resourceType = content.getResourceType().replace('.', '_');
            out.println(
                "<li class=\"file\"><a href=\""
                    + contentUrl
                    + "\" target=_blank class=\""
                    + resourceType
                    + "\">"
                    + Validator.escapeHtml(
                        properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                    + "</a>"
                    + desc
                    + "</li>");
          }
        } catch (Exception ignore) {
          // TODO - what types of failures are being caught here?

          out.println(
              "<li class=\"file\"><a href=\""
                  + contentUrl
                  + "\" target=_blank>"
                  + Validator.escapeHtml(xs)
                  + "</a></li>");
        }
      }

    } catch (Exception e) {
      M_log.warn("Problem formatting HTML for collection: " + x.getId(), e);
    }

    if (out != null && printedHeader) {
      out.println("</ul>");

      if (printedDiv) out.println("</div>");
      out.println("</body></html>");
    }
  }