Пример #1
0
 DefaultAsyncFile(
     final VertxInternal vertx,
     final String path,
     String perms,
     final boolean read,
     final boolean write,
     final boolean createNew,
     final boolean flush,
     final Context context)
     throws Exception {
   if (!read && !write) {
     throw new FileSystemException("Cannot open file for neither reading nor writing");
   }
   this.vertx = vertx;
   Path file = Paths.get(path);
   HashSet<OpenOption> options = new HashSet<>();
   if (read) options.add(StandardOpenOption.READ);
   if (write) options.add(StandardOpenOption.WRITE);
   if (createNew) options.add(StandardOpenOption.CREATE);
   if (flush) options.add(StandardOpenOption.DSYNC);
   if (perms != null) {
     FileAttribute<?> attrs =
         PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(perms));
     ch = AsynchronousFileChannel.open(file, options, vertx.getBackgroundPool(), attrs);
   } else {
     ch = AsynchronousFileChannel.open(file, options, vertx.getBackgroundPool());
   }
   this.context = context;
 }
Пример #2
0
 protected BlockingAction<Void> mkdirInternal(
     String path,
     final String perms,
     final boolean createParents,
     Handler<AsyncResult<Void>> handler) {
   final Path source = PathAdjuster.adjust(vertx, Paths.get(path));
   final FileAttribute<?> attrs =
       perms == null
           ? null
           : PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(perms));
   return new BlockingAction<Void>(handler) {
     public Void perform() {
       try {
         if (createParents) {
           if (attrs != null) {
             Files.createDirectories(source, attrs);
           } else {
             Files.createDirectories(source);
           }
         } else {
           if (attrs != null) {
             Files.createDirectory(source, attrs);
           } else {
             Files.createDirectory(source);
           }
         }
       } catch (IOException e) {
         throw new FileSystemException(e);
       }
       return null;
     }
   };
 }
 private static void createAFile(final String dirName, final String fileName) {
   final Path file = Paths.get(dirName, fileName);
   try {
     if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
       Files.createFile(
           file,
           PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---")));
     }
   } catch (IOException e) {
     LOG.error(e.getMessage(), e);
   }
 }
 private static void createDirectory(final String dirName) {
   System.out.println("=======================createDirectory===================================");
   final FileAttribute<Set<PosixFilePermission>> fileAttribute =
       PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"));
   try {
     final Path dir = Paths.get(dirName);
     if (!Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
       Files.createDirectory(dir, fileAttribute);
     }
   } catch (IOException e) {
     LOG.error(e.getMessage(), e);
   }
 }
Пример #5
0
  @Test
  public void testThatExternalAttributesFieldIsFunctional() throws IOException {

    // Prepare some sample modes to write into the zip file.
    final ImmutableList<String> samples =
        ImmutableList.of("rwxrwxrwx", "rw-r--r--", "--x--x--x", "---------");

    for (String stringMode : samples) {
      long mode = MorePosixFilePermissions.toMode(PosixFilePermissions.fromString(stringMode));

      // Write a tiny sample zip file, which sets the external attributes per the
      // permission sample above.
      try (CustomZipOutputStream out =
          ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING)) {
        CustomZipEntry entry = new CustomZipEntry("test");
        entry.setTime(System.currentTimeMillis());
        entry.setExternalAttributes(mode << 16);
        out.putNextEntry(entry);
        out.write(new byte[0]);
      }

      // Now re-read the zip file using apache's commons-compress, which supports parsing
      // the external attributes field.
      try (ZipFile in = new ZipFile(output.toFile())) {
        Enumeration<ZipArchiveEntry> entries = in.getEntries();
        ZipArchiveEntry entry = entries.nextElement();
        assertEquals(mode, entry.getExternalAttributes() >> 16);
        assertFalse(entries.hasMoreElements());
      }
    }
  }
Пример #6
0
  @Test
  public void testAddAndDelete() {
    try {
      Path path2 = Paths.get(ParentPath + "\\crea22te.txt222");
      // 只能在linux windows不能
      Set<PosixFilePermission> fromString = PosixFilePermissions.fromString("rw-rw-rw-");
      FileAttribute<Set<PosixFilePermission>> asFileAttribute =
          PosixFilePermissions.asFileAttribute(fromString);

      Path createFile = Files.createFile(path2, asFileAttribute);
      System.out.println(createFile);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #7
0
  protected BlockingAction<Void> chmodInternal(
      String path, String perms, String dirPerms, Handler<AsyncResult<Void>> handler) {
    final Path target = PathAdjuster.adjust(vertx, Paths.get(path));
    final Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(perms);
    final Set<PosixFilePermission> dirPermissions =
        dirPerms == null ? null : PosixFilePermissions.fromString(dirPerms);
    return new BlockingAction<Void>(handler) {
      public Void perform() {
        try {
          if (dirPermissions != null) {
            Files.walkFileTree(
                target,
                new SimpleFileVisitor<Path>() {
                  public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                      throws IOException {
                    // The directory entries typically have different permissions to the files, e.g.
                    // execute permission
                    // or can't cd into it
                    Files.setPosixFilePermissions(dir, dirPermissions);
                    return FileVisitResult.CONTINUE;
                  }

                  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                      throws IOException {
                    Files.setPosixFilePermissions(file, permissions);
                    return FileVisitResult.CONTINUE;
                  }
                });
          } else {
            Files.setPosixFilePermissions(target, permissions);
          }
        } catch (SecurityException e) {
          throw new FileSystemException("Accessed denied for chmod on " + target);
        } catch (IOException e) {
          throw new FileSystemException(e);
        }
        return null;
      }
    };
  }
Пример #8
0
 protected BlockingAction<Void> createFileInternal(
     String p, final String perms, Handler<AsyncResult<Void>> handler) {
   final String path = PathAdjuster.adjust(vertx, p);
   final FileAttribute<?> attrs =
       perms == null
           ? null
           : PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(perms));
   return new BlockingAction<Void>(handler) {
     public Void perform() {
       try {
         Path target = Paths.get(path);
         if (attrs != null) {
           Files.createFile(target, attrs);
         } else {
           Files.createFile(target);
         }
       } catch (IOException e) {
         throw new FileSystemException(e);
       }
       return null;
     }
   };
 }
  private void runChmodCheck(String routeSuffix, String expectedPermissions) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:chmod" + routeSuffix);
    mock.expectedMessageCount(1);
    String testFileName = "chmod" + routeSuffix + ".txt";
    String fullTestFileName = TEST_DIRECTORY + testFileName;
    String testFileContent = "Writing file with chmod " + routeSuffix + " option at " + new Date();
    mock.expectedFileExists(fullTestFileName, testFileContent);

    template.sendBodyAndHeader(
        "direct:write" + routeSuffix, testFileContent, Exchange.FILE_NAME, testFileName);

    File f = new File(fullTestFileName);
    Set<PosixFilePermission> permissions =
        Files.getPosixFilePermissions(f.toPath(), LinkOption.NOFOLLOW_LINKS);
    assertEquals(expectedPermissions, PosixFilePermissions.toString(permissions));
    assertEquals(expectedPermissions.replace("-", "").length(), permissions.size());

    assertMockEndpointsSatisfied();
  }
Пример #10
0
  /*
   * Make file non-readable by modifying its permissions.
   * If file supports "posix" attributes, then modify it.
   * Otherwise check for "acl" attributes.
   */
  private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
      Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
      UserPrincipal fileOwner = Files.getOwner(filePath);

      AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

      AclEntry entry =
          AclEntry.newBuilder()
              .setType(AclEntryType.DENY)
              .setPrincipal(fileOwner)
              .setPermissions(AclEntryPermission.READ_DATA)
              .build();

      List<AclEntry> acl = view.getAcl();
      acl.add(0, entry);
      view.setAcl(acl);
    }
  }
Пример #11
0
  public FileAttrs getAttrs() throws IOException {
    FileAttrs result;
    BasicFileAttributes attr;
    DosFileAttributes dosAttr;
    PosixFileAttributes posixAttr;

    result = new FileAttrs();
    attr = Files.readAttributes(this.path.toPath(), BasicFileAttributes.class);

    result.setCtime(attr.creationTime().toMillis());
    result.setMtime(attr.lastModifiedTime().toMillis());
    // result.append("symlink", attr.isSymbolicLink()); //Redundant
    result.setSize(attr.size());

    if (System.getProperty("os.name").startsWith("Windows")) {
      dosAttr = Files.readAttributes(this.path.toPath(), DosFileAttributes.class);

      result.setDosArchive(dosAttr.isArchive());
      result.setDosHidden(dosAttr.isHidden());
      result.setDosReadonly(dosAttr.isReadOnly());
      result.setDosSystem(dosAttr.isSystem());
    } else {
      posixAttr = Files.readAttributes(this.path.toPath(), PosixFileAttributes.class);

      result.setPosixSymlink(this.isSymlink());

      if (result.getPosixSymlink()) {
        result.setLinkTo(Files.readSymbolicLink(this.path.toPath()).toString());
      }

      result.setPosixOwner(posixAttr.owner().getName());
      result.setPosixGroup(posixAttr.group().getName());
      result.setPosixPermission(PosixFilePermissions.toString(posixAttr.permissions()));
    }

    return result;
  }
Пример #12
0
  public void setAttrs(FileAttrs attrs) throws IOException {
    UserPrincipal posixOwner;
    GroupPrincipal posixGroup;
    Set<PosixFilePermission> posixPerms;
    UserPrincipalLookupService lookup;

    if (System.getProperty("os.name").startsWith("Windows")) {
      Files.setAttribute(this.path.toPath(), "dos:archive", attrs.getDosArchive());
      Files.setAttribute(this.path.toPath(), "dos:hidden", attrs.getDosHidden());
      Files.setAttribute(this.path.toPath(), "dos:readonly", attrs.getDosReadonly());
      Files.setAttribute(this.path.toPath(), "dos:system", attrs.getDosSystem());
    } else {
      lookup = this.path.toPath().getFileSystem().getUserPrincipalLookupService();

      posixOwner = lookup.lookupPrincipalByName(attrs.getPosixOwner());
      posixGroup = lookup.lookupPrincipalByGroupName(attrs.getPosixGroup());
      posixPerms = PosixFilePermissions.fromString(attrs.getPosixPermission());

      Files.setOwner(this.path.toPath(), posixOwner);
      Files.getFileAttributeView(this.path.toPath(), PosixFileAttributeView.class)
          .setGroup(posixGroup);
      Files.setPosixFilePermissions(this.path.toPath(), posixPerms);
    }
  }
Пример #13
0
  protected void doExecute() throws Exception {
    startupRepositories = nonNullList(startupRepositories);
    bootRepositories = nonNullList(bootRepositories);
    installedRepositories = nonNullList(installedRepositories);
    startupBundles = nonNullList(startupBundles);
    bootBundles = nonNullList(bootBundles);
    installedBundles = nonNullList(installedBundles);
    blacklistedBundles = nonNullList(blacklistedBundles);
    startupFeatures = nonNullList(startupFeatures);
    bootFeatures = nonNullList(bootFeatures);
    installedFeatures = nonNullList(installedFeatures);
    blacklistedFeatures = nonNullList(blacklistedFeatures);
    startupProfiles = nonNullList(startupProfiles);
    bootProfiles = nonNullList(bootProfiles);
    installedProfiles = nonNullList(installedProfiles);
    blacklistedProfiles = nonNullList(blacklistedProfiles);

    if (!startupProfiles.isEmpty() || !bootProfiles.isEmpty() || !installedProfiles.isEmpty()) {
      if (profilesUri == null) {
        throw new IllegalArgumentException("profilesDirectory must be specified");
      }
    }

    if (featureRepositories != null && !featureRepositories.isEmpty()) {
      getLog()
          .warn(
              "Use of featureRepositories is deprecated, use startupRepositories, bootRepositories or installedRepositories instead");
      startupRepositories.addAll(featureRepositories);
      bootRepositories.addAll(featureRepositories);
      installedRepositories.addAll(featureRepositories);
    }

    StringBuilder remote = new StringBuilder();
    for (Object obj : project.getRemoteProjectRepositories()) {
      if (remote.length() > 0) {
        remote.append(",");
      }
      remote.append(invoke(obj, "getUrl"));
      remote.append("@id=").append(invoke(obj, "getId"));
      if (!((Boolean) invoke(getPolicy(obj, false), "isEnabled"))) {
        remote.append("@noreleases");
      }
      if ((Boolean) invoke(getPolicy(obj, true), "isEnabled")) {
        remote.append("@snapshots");
      }
    }
    getLog().info("Using repositories: " + remote.toString());

    Builder builder = Builder.newInstance();
    builder.offline(mavenSession.isOffline());
    builder.localRepository(localRepo.getBasedir());
    builder.mavenRepositories(remote.toString());
    builder.javase(javase);

    // Set up blacklisted items
    builder.blacklistBundles(blacklistedBundles);
    builder.blacklistFeatures(blacklistedFeatures);
    builder.blacklistProfiles(blacklistedProfiles);
    builder.blacklistPolicy(blacklistPolicy);

    if (propertyFileEdits != null) {
      File file = new File(propertyFileEdits);
      if (file.exists()) {
        KarafPropertyEdits edits;
        try (InputStream editsStream = new FileInputStream(propertyFileEdits)) {
          KarafPropertyInstructionsModelStaxReader kipmsr =
              new KarafPropertyInstructionsModelStaxReader();
          edits = kipmsr.read(editsStream, true);
        }
        builder.propertyEdits(edits);
      }
    }

    Map<String, String> urls = new HashMap<>();
    List<Artifact> artifacts = new ArrayList<>(project.getAttachedArtifacts());
    artifacts.add(project.getArtifact());
    for (Artifact artifact : artifacts) {
      if (artifact.getFile() != null && artifact.getFile().exists()) {
        String mvnUrl =
            "mvn:"
                + artifact.getGroupId()
                + "/"
                + artifact.getArtifactId()
                + "/"
                + artifact.getVersion();
        String type = artifact.getType();
        if ("bundle".equals(type)) {
          type = "jar";
        }
        if (!"jar".equals(type) || artifact.getClassifier() != null) {
          mvnUrl += "/" + type;
          if (artifact.getClassifier() != null) {
            mvnUrl += "/" + artifact.getClassifier();
          }
        }
        urls.put(mvnUrl, artifact.getFile().toURI().toString());
      }
    }
    if (translatedUrls != null) {
      urls.putAll(translatedUrls);
    }
    builder.translatedUrls(urls);

    // creating system directory
    getLog().info("Creating work directory");
    builder.homeDirectory(workDirectory.toPath());
    IoUtils.deleteRecursive(workDirectory);
    workDirectory.mkdirs();

    List<String> startupKars = new ArrayList<>();
    List<String> bootKars = new ArrayList<>();
    List<String> installedKars = new ArrayList<>();

    // Loading kars and features repositories
    getLog().info("Loading kar and features repositories dependencies");
    for (Artifact artifact : project.getDependencyArtifacts()) {
      Builder.Stage stage;
      switch (artifact.getScope()) {
        case "compile":
          stage = Builder.Stage.Startup;
          break;
        case "runtime":
          stage = Builder.Stage.Boot;
          break;
        case "provided":
          stage = Builder.Stage.Installed;
          break;
        default:
          continue;
      }
      if ("kar".equals(artifact.getType())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupKars.add(uri);
            break;
          case Boot:
            bootKars.add(uri);
            break;
          case Installed:
            installedKars.add(uri);
            break;
        }
      } else if ("features".equals(artifact.getClassifier())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupRepositories.add(uri);
            break;
          case Boot:
            bootRepositories.add(uri);
            break;
          case Installed:
            installedRepositories.add(uri);
            break;
        }
      } else if ("jar".equals(artifact.getType()) || "bundle".equals(artifact.getType())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupBundles.add(uri);
            break;
          case Boot:
            bootBundles.add(uri);
            break;
          case Installed:
            installedBundles.add(uri);
            break;
        }
      }
    }

    builder
        .karafVersion(karafVersion)
        .useReferenceUrls(useReferenceUrls)
        .defaultAddAll(installAllFeaturesByDefault)
        .ignoreDependencyFlag(ignoreDependencyFlag);
    if (profilesUri != null) {
      builder.profilesUris(profilesUri);
    }
    if (libraries != null) {
      builder.libraries(libraries.toArray(new String[libraries.size()]));
    }
    // Startup
    builder
        .defaultStage(Builder.Stage.Startup)
        .kars(toArray(startupKars))
        .repositories(
            startupFeatures.isEmpty() && startupProfiles.isEmpty() && installAllFeaturesByDefault,
            toArray(startupRepositories))
        .features(toArray(startupFeatures))
        .bundles(toArray(startupBundles))
        .profiles(toArray(startupProfiles));
    // Boot
    builder
        .defaultStage(Builder.Stage.Boot)
        .kars(toArray(bootKars))
        .repositories(
            bootFeatures.isEmpty() && bootProfiles.isEmpty() && installAllFeaturesByDefault,
            toArray(bootRepositories))
        .features(toArray(bootFeatures))
        .bundles(toArray(bootBundles))
        .profiles(toArray(bootProfiles));
    // Installed
    builder
        .defaultStage(Builder.Stage.Installed)
        .kars(toArray(installedKars))
        .repositories(
            installedFeatures.isEmpty()
                && installedProfiles.isEmpty()
                && installAllFeaturesByDefault,
            toArray(installedRepositories))
        .features(toArray(installedFeatures))
        .bundles(toArray(installedBundles))
        .profiles(toArray(installedProfiles));

    // Generate the assembly
    builder.generateAssembly();

    // Include project classes content
    if (includeBuildOutputDirectory)
      IoUtils.copyDirectory(new File(project.getBuild().getOutputDirectory()), workDirectory);

    // Overwrite assembly dir contents
    if (sourceDirectory.exists()) IoUtils.copyDirectory(sourceDirectory, workDirectory);

    // Chmod the bin/* scripts
    File[] files = new File(workDirectory, "bin").listFiles();
    if (files != null) {
      for (File file : files) {
        if (!file.getName().endsWith(".bat")) {
          try {
            Files.setPosixFilePermissions(
                file.toPath(), PosixFilePermissions.fromString("rwxr-xr-x"));
          } catch (Throwable ignore) {
            // we tried our best, perhaps the OS does not support posix file perms.
          }
        }
      }
    }
  }