Java Code Examples for java.util.EnumSet

The following are top voted examples for showing how to use java.util.EnumSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cyberduck   File: MantaMoveFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testMoveRename() throws BackgroundException {
    final Directory directory = new MantaDirectoryFeature(session);
    final Touch touch = new MantaTouchFeature(session);
    final Move move = new MantaMoveFeature(session);
    final Delete delete = new MantaDeleteFeature(session);
    final AttributesFinder attributesFinder = new MantaAttributesFinderFeature(session);
    final Path drive = new MantaDirectoryFeature(session).mkdir(randomDirectory(), "", new TransferStatus());
    Path targetDirectory = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    directory.mkdir(targetDirectory, null, null);
    assertNotNull(attributesFinder.find(targetDirectory));
    Path touchedFile = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    touch.touch(touchedFile, new TransferStatus().withMime("x-application/cyberduck"));
    assertNotNull(attributesFinder.find(touchedFile));
    Path rename = new Path(targetDirectory, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    assertTrue(move.isSupported(touchedFile, rename));
    assertEquals(rename, move.move(touchedFile, rename, new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback()));
    assertNotNull(attributesFinder.find(rename));
    assertFalse(new MantaFindFeature(session).find(touchedFile));
    assertTrue(new MantaFindFeature(session).find(rename));
    delete.delete(Collections.singletonList(targetDirectory), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 2
Project: cyberduck   File: FTPUTIMETimestampFeatureTest.java   View source code 6 votes vote down vote up
@Test(expected = BackgroundException.class)
public void testSetTimestamp() throws Exception {
    final Host host = new Host(new FTPTLSProtocol(), "test.cyberduck.ch", new Credentials(
            System.getProperties().getProperty("ftp.user"), System.getProperties().getProperty("ftp.password")
    ));
    final FTPSession session = new FTPSession(host);
    assertNotNull(session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback()));
    assertTrue(session.isConnected());
    assertNotNull(session.getClient());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final FTPWorkdirService workdir = new FTPWorkdirService(session);
    final Path home = workdir.find();
    final long modified = System.currentTimeMillis();
    final Path test = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    session.getFeature(Touch.class).touch(test, new TransferStatus());
    new FTPUTIMETimestampFeature(session).setTimestamp(test, modified);
    new FTPDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 3
Project: cyberduck   File: S3EncryptionFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testSetEncryptionAES256Placeholder() throws Exception {
    final S3Session session = new S3Session(
            new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
                    new Credentials(
                            System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
                    )));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume));
    final Path test = new S3DirectoryFeature(session, new S3WriteFeature(session, new S3DisabledMultipartService())).mkdir(
            new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)), null, new TransferStatus());
    final S3EncryptionFeature feature = new S3EncryptionFeature(session);
    feature.setEncryption(test, S3EncryptionFeature.SSE_AES256);
    final Encryption.Algorithm value = feature.getEncryption(test);
    assertEquals("AES256", value.algorithm);
    assertNull(value.key);
    new S3DefaultDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 4
Project: javaide   File: LocalSdk.java   View source code 6 votes vote down vote up
/**
 * Clear the tracked visited folders & the cached {@link LocalPkgInfo} for the
 * given filter types.
 *
 * @param filters A set of PkgType constants or {@link PkgType#PKG_ALL} to clear everything.
 */
public void clearLocalPkg(@NonNull EnumSet<PkgType> filters) {
    mLegacyBuildTools = null;

    synchronized (mLocalPackages) {
        for (PkgType filter : filters) {
            mVisitedDirs.removeAll(filter);
            mLocalPackages.removeAll(filter);
        }
    }

    // Clear the targets if the platforms or addons are being cleared
    if (filters.contains(PkgType.PKG_PLATFORM) ||  filters.contains(PkgType.PKG_ADDON)) {
      mReloadTargets = true;
    }
}
 
Example 5
Project: hadoop   File: NativeAzureFileSystem.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public FSDataOutputStream createNonRecursive(Path f, FsPermission permission,
    EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize,
    Progressable progress) throws IOException {

  // Check if file should be appended or overwritten. Assume that the file
  // is overwritten on if the CREATE and OVERWRITE create flags are set. Note
  // that any other combinations of create flags will result in an open new or
  // open with append.
  final EnumSet<CreateFlag> createflags =
      EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE);
  boolean overwrite = flags.containsAll(createflags);

  // Delegate the create non-recursive call.
  return this.createNonRecursive(f, permission, overwrite,
      bufferSize, replication, blockSize, progress);
}
 
Example 6
Project: cyberduck   File: OneDriveWriteFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testWrite() throws Exception {
    final OneDriveWriteFeature feature = new OneDriveWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    final byte[] buffer = new byte[32 * 1024];
    assertEquals(content.length, IOUtils.copyLarge(in, out, buffer));
    in.close();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 7
Project: incubator-netbeans   File: FilesystemInterceptorTest.java   View source code 6 votes vote down vote up
public void testRenameVersionedFolder_DO () throws Exception {
    // init
    File fromFolder = new File(repositoryLocation, "from");
    fromFolder.mkdirs();
    File file = new File(fromFolder, "file");
    file.createNewFile();
    add();
    commit();

    File toFolder = new File(repositoryLocation, "to");
    File toFile = new File(toFolder, file.getName());

    // rename
    h.setFilesToRefresh(new HashSet<File>(Arrays.asList(fromFolder, toFolder)));
    renameDO(fromFolder, toFolder);
    assertTrue(h.waitForFilesToRefresh());

    // test
    assertFalse(fromFolder.exists());
    assertTrue(toFolder.exists());
    assertEquals(EnumSet.of(Status.REMOVED_HEAD_INDEX, Status.REMOVED_HEAD_WORKING_TREE), getCache().getStatus(file).getStatus());
    FileInformation info = getCache().getStatus(toFile);
    assertEquals(EnumSet.of(Status.NEW_HEAD_INDEX, Status.NEW_HEAD_WORKING_TREE), info.getStatus());
    assertTrue(info.isRenamed());
    assertEquals(file, info.getOldFile());
}
 
Example 8
Project: GitHub   File: RealmProxyMediatorGenerator.java   View source code 6 votes vote down vote up
private void emitGetExpectedObjectSchemaInfoMap(JavaWriter writer) throws IOException {
    writer.emitAnnotation("Override");
    writer.beginMethod(
            "Map<Class<? extends RealmModel>, OsObjectSchemaInfo>",
            "getExpectedObjectSchemaInfoMap",
            EnumSet.of(Modifier.PUBLIC));

    writer.emitStatement(
            "Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap = " +
                    "new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>(%s)", qualifiedProxyClasses.size());
    for (int i = 0; i < qualifiedProxyClasses.size(); i++) {
        writer.emitStatement("infoMap.put(%s.class, %s.getExpectedObjectSchemaInfo())",
                qualifiedModelClasses.get(i), qualifiedProxyClasses.get(i));
    }
    writer.emitStatement("return infoMap");

    writer.endMethod();
    writer.emitEmptyLine();
}
 
Example 9
Project: cyberduck   File: LocalAttributesFinderFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testConvert() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    if(session.isPosixFilesystem()) {
        session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
        session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
        final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
        new LocalTouchFeature(session).touch(file, new TransferStatus());
        final java.nio.file.Path local = session.toPath(file);
        final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class);
        final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session);
        assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------"));
        assertEquals("rw-------", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx"));
        assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----"));
        assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol());
        assertEquals(posixAttributes.size(), finder.find(file).getSize());
        assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate());
        assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate());
        assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate());
        new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    }
}
 
Example 10
Project: incubator-netbeans   File: FileObjectArchiveTest.java   View source code 6 votes vote down vote up
public void testList() throws IOException {
    final FileObjectArchive archive = new FileObjectArchive(FileUtil.toFileObject(root));
    Iterable<JavaFileObject> res = archive.getFiles(
            "org/me",   //NOI18N
            null,
            EnumSet.of(JavaFileObject.Kind.CLASS),
            null,
            false);
    assertEquals(Arrays.asList("org.me.A", "org.me.B"), toInferedName(res));    //NOI18N
    res = archive.getFiles(
            "non-package/org/me",   //NOI18N
            null,
            EnumSet.of(JavaFileObject.Kind.CLASS),
            null,
            false);
    //Explicit list of non-package returns FileObejcts with prefix
    assertEquals(Arrays.asList("non-package.org.me.X", "non-package.org.me.Y"), toInferedName(res));    //NOI18N
}
 
Example 11
Project: cyberduck   File: S3DirectoryFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testMakeDirectoryEncrypted() throws Exception {
    final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
            System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
    ));
    final S3Session session = new S3Session(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final Path test = new CryptoDirectoryFeature<StorageObject>(session, new S3DirectoryFeature(session, new S3WriteFeature(session)), new S3WriteFeature(session), cryptomator).mkdir(new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), null, new TransferStatus());
    assertTrue(test.getType().contains(Path.Type.placeholder));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(test));
    new CryptoDeleteFeature(session, new S3DefaultDeleteFeature(session), cryptomator).delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 12
Project: cyberduck   File: SDSDirectoryFeature.java   View source code 6 votes vote down vote up
@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException {
    try {
        if(containerService.isContainer(folder)) {
            final CreateRoomRequest roomRequest = new CreateRoomRequest();
            final UserAccountWrapper user = session.userAccount();
            roomRequest.addAdminIdsItem(user.getId());
            roomRequest.setAdminGroupIds(null);
            roomRequest.setName(folder.getName());
            final Node r = new NodesApi(session.getClient()).createRoom(StringUtils.EMPTY, null, roomRequest);
            return new Path(folder.getParent(), folder.getName(), EnumSet.of(Path.Type.directory, Path.Type.volume),
                new PathAttributes(folder.attributes()));
        }
        else {
            final CreateFolderRequest folderRequest = new CreateFolderRequest();
            folderRequest.setParentId(Long.parseLong(new SDSNodeIdProvider(session).getFileid(folder.getParent(), new DisabledListProgressListener())));
            folderRequest.setName(folder.getName());
            final Node f = new NodesApi(session.getClient()).createFolder(StringUtils.EMPTY, folderRequest, null);
            return new Path(folder.getParent(), folder.getName(), folder.getType(),
                new PathAttributes(folder.attributes()));
        }
    }
    catch(ApiException e) {
        throw new SDSExceptionMappingService().map("Cannot create folder {0}", e, folder);
    }
}
 
Example 13
Project: cyberduck   File: S3AttributesFinderFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testReadTildeInKey() throws Exception {
    final S3Session session = new S3Session(
        new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(
                System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
            )));
    session.setSignatureVersion(S3Protocol.AuthenticationHeaderSignatureVersion.AWS2);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    container.attributes().setRegion("us-east-1");
    final Path file = new Path(container, String.format("%s~", UUID.randomUUID().toString()), EnumSet.of(Path.Type.file));
    new S3TouchFeature(session).touch(file, new TransferStatus());
    new S3AttributesFinderFeature(session).find(file);
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 14
Project: hadoop   File: TestFavoredNodesEndToEnd.java   View source code 6 votes vote down vote up
@Test(timeout = 180000)
public void testFavoredNodesEndToEndForAppend() throws Exception {
  // create 10 files with random preferred nodes
  for (int i = 0; i < NUM_FILES; i++) {
    Random rand = new Random(System.currentTimeMillis() + i);
    // pass a new created rand so as to get a uniform distribution each time
    // without too much collisions (look at the do-while loop in getDatanodes)
    InetSocketAddress datanode[] = getDatanodes(rand);
    Path p = new Path("/filename" + i);
    // create and close the file.
    dfs.create(p, FsPermission.getDefault(), true, 4096, (short) 3, 4096L,
        null, null).close();
    // re-open for append
    FSDataOutputStream out = dfs.append(p, EnumSet.of(CreateFlag.APPEND),
        4096, null, datanode);
    out.write(SOME_BYTES);
    out.close();
    BlockLocation[] locations = getBlockLocations(p);
    // verify the files got created in the right nodes
    for (BlockLocation loc : locations) {
      String[] hosts = loc.getNames();
      String[] hosts1 = getStringForInetSocketAddrs(datanode);
      assertTrue(compareNodes(hosts, hosts1));
    }
  }
}
 
Example 15
Project: octoBubbles   File: NodeViewScratchParser.java   View source code 6 votes vote down vote up
/**
 * It adds all the attributes need to be added to the existing compilation unit.
 */
private void addAttributesToCompilationUnit() {
    if(attributesToBeAdded.size() > 0) {
        ClassOrInterfaceDeclaration type = getFileType();

        attributesToBeAdded.stream().forEach(attribute -> {
            EnumSet<Modifier> modifiers = null;
            for (Modifier modifier : attribute.getAccessModifiers()) {
                modifiers = EnumSet.of(modifier);
            }

            VariableDeclarator vd = new VariableDeclarator(JavaParser.parseType(attribute.getDataType()), attribute.getName());
            FieldDeclaration fd = new FieldDeclaration();
            fd.setModifiers(modifiers);
            fd.addVariable(vd);

            type.addMember(fd);
            ((ClassStructure)existingAbstractStructure).addAttribute(attribute);
        });
    }
}
 
Example 16
Project: xenon-utils   File: SwaggerDescriptorService.java   View source code 6 votes vote down vote up
@Override
public void handleGet(Operation get) {
    Operation op = Operation.createGet(this, "/");
    op.setCompletion((o, e) -> {
        SwaggerAssembler
                .create(this)
                .setExcludedPrefixes(this.excludedPrefixes)
                .setStripPackagePrefixes(this.stripPackagePrefixes)
                .setSupportLevel(this.supportLevel)
                .setInfo(this.info)
                .setPostprocessor(this.swaggerPostprocessor)
                .setExcludeUtilities(this.excludeUtilities)
                .setQueryResult(o.getBody(ServiceDocumentQueryResult.class))
                .build(get);
    });

    getHost().queryServiceUris(
            // all services
            EnumSet.noneOf(ServiceOption.class),
            true,
            op,
            // exclude factory items
            EnumSet.of(ServiceOption.FACTORY_ITEM));
}
 
Example 17
Project: hadoop   File: FSDirectory.java   View source code 6 votes vote down vote up
/**
 * Set the FileEncryptionInfo for an INode.
 */
void setFileEncryptionInfo(String src, FileEncryptionInfo info)
    throws IOException {
  // Make the PB for the xattr
  final HdfsProtos.PerFileEncryptionInfoProto proto =
      PBHelper.convertPerFileEncInfo(info);
  final byte[] protoBytes = proto.toByteArray();
  final XAttr fileEncryptionAttr =
      XAttrHelper.buildXAttr(CRYPTO_XATTR_FILE_ENCRYPTION_INFO, protoBytes);
  final List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1);
  xAttrs.add(fileEncryptionAttr);

  writeLock();
  try {
    FSDirXAttrOp.unprotectedSetXAttrs(this, src, xAttrs,
                                      EnumSet.of(XAttrSetFlag.CREATE));
  } finally {
    writeUnlock();
  }
}
 
Example 18
Project: cyberduck   File: SDSDelegatingCopyFeatureTest.java   View source code 6 votes vote down vote up
@Test
public void testCopyFileToDifferentDataRoom() throws Exception {
    final Host host = new Host(new SDSProtocol(), "duck.ssp-europe.eu", new Credentials(
        System.getProperties().getProperty("sds.user"), System.getProperties().getProperty("sds.key")
    ));
    final SDSSession session = new SDSSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path room1 = new SDSDirectoryFeature(session).mkdir(new Path(
        new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final Path room2 = new SDSDirectoryFeature(session).mkdir(new Path(
        new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final Path source = new SDSTouchFeature(session).touch(new Path(room1, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
    final Path target = new SDSTouchFeature(session).touch(new Path(room2, source.getName(), EnumSet.of(Path.Type.file)), new TransferStatus());
    final SDSCopyFeature feature = new SDSCopyFeature(session);
    assertTrue(feature.isSupported(source, target));
    new SDSDelegatingCopyFeature(session, feature).copy(source, target, new TransferStatus(), new DisabledConnectionCallback());
    assertTrue(new SDSFindFeature(session).find(source));
    assertTrue(new SDSFindFeature(session).find(target));
    new SDSDeleteFeature(session).delete(Arrays.asList(room1, room2), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 19
Project: cyberduck   File: SFTPCryptomatorInteroperabilityTest.java   View source code 6 votes vote down vote up
/**
 * Create long file/folder with Cryptomator, read with Cyberduck
 */
@Test
public void testCryptomatorInteroperability_longNames_Tests() throws Exception {
    // create folder
    final java.nio.file.Path targetFolder = cryptoFileSystem.getPath("/", new AlphanumericRandomStringService().random());
    Files.createDirectory(targetFolder);
    // create file and write some random content
    java.nio.file.Path targetFile = targetFolder.resolve(new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(20);
    Files.write(targetFile, content);

    // read with Cyberduck and compare
    final Host host = new Host(new SFTPProtocol(), "localhost", PORT_NUMBER, new Credentials("empty", "empty"));
    final SFTPSession session = new SFTPSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new SFTPHomeDirectoryService(session).find();
    final Path vault = new Path(home, "vault", EnumSet.of(Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()).load(session, new DisabledPasswordCallback() {
        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException {
            return new VaultCredentials(passphrase);
        }
    });
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    Path p = new Path(new Path(vault, targetFolder.getFileName().toString(), EnumSet.of(Path.Type.directory)), targetFile.getFileName().toString(), EnumSet.of(Path.Type.file));
    final InputStream read = new CryptoReadFeature(session, new SFTPReadFeature(session), cryptomator).read(p, new TransferStatus(), new DisabledConnectionCallback());
    final byte[] readContent = new byte[content.length];
    IOUtils.readFully(read, readContent);
    assertArrayEquals(content, readContent);
    session.close();
}
 
Example 20
Project: incubator-netbeans   File: FilesystemInterceptorTest.java   View source code 6 votes vote down vote up
public void testRenameA2CB2A_FO() throws Exception {
    // init
    File fileA = new File(repositoryLocation, "A");
    write(fileA, "aaa");
    File fileB = new File(repositoryLocation, "B");
    write(fileB, "bbb");
    add();
    commit();

    File fileC = new File(repositoryLocation, "C");

    // move
    h.setFilesToRefresh(new HashSet<File>(Arrays.asList(fileA, fileB, fileC)));
    renameFO(fileA, fileC);
    renameFO(fileB, fileA);
    assertTrue(h.waitForFilesToRefresh());

    // test
    assertTrue(fileA.exists());
    assertTrue(fileC.exists());
    assertFalse(fileB.exists());

    assertEquals(EnumSet.of(Status.MODIFIED_HEAD_INDEX, Status.MODIFIED_HEAD_WORKING_TREE), getCache().getStatus(fileA).getStatus());
    assertEquals(EnumSet.of(Status.REMOVED_HEAD_INDEX, Status.REMOVED_HEAD_WORKING_TREE), getCache().getStatus(fileB).getStatus());
    assertEquals(EnumSet.of(Status.NEW_HEAD_INDEX, Status.NEW_HEAD_WORKING_TREE), getCache().getStatus(fileC).getStatus());
}
 
Example 21
Project: jdk8u-jdk   File: ScanManager.java   View source code 6 votes vote down vote up
/**
 * Checks that the current state is one of the allowed states,
 * and if so, switch its value to the new desired state.
 * This operation also enqueue the appropriate state changed
 * notification.
 **/
private ScanState switchState(ScanState desired,EnumSet<ScanState> allowed) {
    final ScanState old;
    final long timestamp;
    final long sequence;
    synchronized(this) {
        old = state;
        if (!allowed.contains(state))
           throw new IllegalStateException(state.toString());
        state = desired;
        timestamp = System.currentTimeMillis();
        sequence  = getNextSeqNumber();
    }
    LOG.fine("switched state: "+old+" -> "+desired);
    if (old != desired)
        queueStateChangedNotification(sequence,timestamp,old,desired);
    return old;
}
 
Example 22
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 6 votes vote down vote up
public void testConstantFix208072a() throws Exception {
    Preferences prefs = CodeStylePreferences.get((FileObject) null, JavacParser.MIME_TYPE).getPreferences();
    prefs.put("classMemberInsertionPoint", "LAST_IN_CATEGORY");
    performFixTest("package test;\n" +
                   "import java.util.logging.Level;\n" +
                   "import java.util.logging.Logger;\n" +
                   "public class Test {\n" +
                   "     private static final int II = |1 + 2 * 3|;\n" +
                   "}\n",
                   ("package test;\n" +
                    "import java.util.logging.Level;\n" +
                    "import java.util.logging.Logger;\n" +
                    "public class Test {\n" +
                   "     private static final int ZZ = 1 + 2 * 3;\n" +
                   "     private static final int II = ZZ;\n" +
                    "}\n").replaceAll("[ \t\n]+", " "),
                   new DialogDisplayerImpl("ZZ", true, true, true, EnumSet.of(Modifier.PRIVATE)),
                   1, 0);
}
 
Example 23
Project: cyberduck   File: S3DirectoryFeatureTest.java   View source code 6 votes vote down vote up
@Test(expected = InteroperabilityException.class)
public void testCreateBucketInvalidName() throws Exception {
    final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
        System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
    ));
    final S3Session session = new S3Session(host);
    session.setSignatureVersion(S3Protocol.AuthenticationHeaderSignatureVersion.AWS4HMACSHA256);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final S3DirectoryFeature feature = new S3DirectoryFeature(session, new S3WriteFeature(session));
    final Path test = new Path(new S3HomeFinderService(session).find(), "untitled folder", EnumSet.of(Path.Type.directory, Path.Type.volume));
    assertFalse(feature.isSupported(test.getParent(), test.getName()));
    final S3LocationFeature.S3Region region = new S3LocationFeature.S3Region("eu-west-2");
    test.attributes().setRegion(region.getIdentifier());
    feature.mkdir(test, region.getIdentifier(), new TransferStatus());
    assertTrue(new S3FindFeature(session).find(test));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 24
Project: iot-edge-greengrass   File: Configuration.java   View source code 5 votes vote down vote up
private Configuration(JsonProvider jsonProvider, MappingProvider mappingProvider, EnumSet<Option> options, Collection<EvaluationListener> evaluationListeners) {
    notNull(jsonProvider, "jsonProvider can not be null");
    notNull(mappingProvider, "mappingProvider can not be null");
    notNull(options, "setOptions can not be null");
    notNull(evaluationListeners, "evaluationListeners can not be null");
    this.jsonProvider = jsonProvider;
    this.mappingProvider = mappingProvider;
    this.options = Collections.unmodifiableSet(options);
    this.evaluationListeners = Collections.unmodifiableCollection(evaluationListeners);
}
 
Example 25
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 5 votes vote down vote up
public void testIntroduceMethod112552a() throws Exception {
    performFixTest("package test; public class Test {public static void t() {boolean first = true; while (true) {if (first) {first = false;} else {break;}}}}",
                   130 - 25, 144 - 25,
                   "package test; public class Test {public static void t() {boolean first = true; while (true) {if (first) {first = name();} else {break;}}} private static boolean name() { boolean first; first = false; return first; } }",
                   new DialogDisplayerImpl3("name", EnumSet
            .of(Modifier.PRIVATE), true));
}
 
Example 26
Project: cyberduck   File: ResumeFilterTest.java   View source code 5 votes vote down vote up
@Test
public void testPrepare0() throws Exception {
    final ResumeFilter f = new ResumeFilter(new DisabledUploadSymlinkResolver(), new NullSession(new Host(new TestProtocol())),
            new UploadFilterOptions().withTemporary(true));
    final Path t = new Path("t", EnumSet.of(Path.Type.file));
    t.attributes().setSize(0L);
    final TransferStatus status = f.prepare(t, new NullLocal("t"), new TransferStatus().exists(true), new DisabledProgressListener());
    assertFalse(status.isAppend());
    assertNotNull(status.getRename().remote);
    assertEquals(0L, status.getOffset());
}
 
Example 27
Project: incubator-netbeans   File: PositionEstimator.java   View source code 5 votes vote down vote up
static JavaTokenId moveFwdToOneOfTokens(TokenSequence<JavaTokenId> tokenSequence, 
        final int pos,
        EnumSet<JavaTokenId> ids)
{
    tokenSequence.move(pos);
    tokenSequence.moveNext(); // Assumes the pos is located within input bounds
    while (!ids.contains(tokenSequence.token().id())) {
        if (!tokenSequence.moveNext())
            return null;
    }
    return tokenSequence.token().id();
}
 
Example 28
Project: Jupiter   File: BlockRedstoneWire.java   View source code 5 votes vote down vote up
public int getWeakPower(BlockFace side) {
    if (!this.canProvidePower) {
        return 0;
    } else {
        int power = this.meta;

        if (power == 0) {
            return 0;
        } else if (side == BlockFace.UP) {
            return power;
        } else {
            EnumSet<BlockFace> enumset = EnumSet.noneOf(BlockFace.class);

            for (BlockFace face : Plane.HORIZONTAL) {
                if (this.isPowerSourceAt(face)) {
                    enumset.add(face);
                }
            }

            if (side.getAxis().isHorizontal() && enumset.isEmpty()) {
                return power;
            } else if (enumset.contains(side) && !enumset.contains(side.rotateYCCW()) && !enumset.contains(side.rotateY())) {
                return power;
            } else {
                return 0;
            }
        }
    }
}
 
Example 29
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 5 votes vote down vote up
public void testIntroduceMethodTypeParam183435b() throws Exception {
    performFixTest("package test;\n" +
                   "public class Test {\n" +
                   "    public static <T extends Number> void test(T t) {\n" +
                   "        String allianceString = new String(\"[]\");\n" +
                   "        String s = t.toString();" +
                   "        |allianceString += s;|" +
                   "    }\n" +
                   "}",
                   "package test; public class Test { public static <T extends Number> void test(T t) { String allianceString = new String(\"[]\"); String s = t.toString(); name(allianceString, s); } private static void name(String allianceString, String s) { allianceString += s; } }",
                   new DialogDisplayerImpl3("name", EnumSet
            .of(Modifier.PRIVATE), true));
}
 
Example 30
Project: cyberduck   File: MoveWorkerTest.java   View source code 5 votes vote down vote up
@Test
public void testMoveDirectoryOutsideVault() throws Exception {
    final Path home = new OneDriveHomeFinderFeature(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path encryptedFolder = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path encryptedFile = new Path(encryptedFolder, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    new CryptoDirectoryFeature<>(session, new OneDriveDirectoryFeature(session), new OneDriveWriteFeature(session), cryptomator).mkdir(encryptedFolder, null, new TransferStatus());
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(encryptedFolder));
    new CryptoTouchFeature<>(session, new DefaultTouchFeature<Void>(new DefaultUploadFeature<>(new OneDriveWriteFeature(session))), new OneDriveWriteFeature(session), cryptomator).touch(encryptedFile, new TransferStatus());
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(encryptedFile));
    // move directory outside vault
    final Path directoryRenamed = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final MoveWorker worker = new MoveWorker(Collections.singletonMap(encryptedFolder, directoryRenamed), PathCache.empty(), new TestPasswordStore(), new DisabledLoginCallback(), new DisabledHostKeyCallback(), new DisabledProgressListener(), new DisabledTranscriptListener());
    worker.run(session);
    assertFalse(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(encryptedFolder));
    assertFalse(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(encryptedFile));
    assertTrue(new DefaultFindFeature(session).find(directoryRenamed));
    final Path fileRenamed = new Path(directoryRenamed, encryptedFile.getName(), EnumSet.of(Path.Type.file));
    assertTrue(new DefaultFindFeature(session).find(fileRenamed));
    new CryptoDeleteFeature(session, new OneDriveDeleteFeature(session), cryptomator).delete(Collections.singletonList(vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    new OneDriveDeleteFeature(session).delete(Arrays.asList(fileRenamed, directoryRenamed), new DisabledLoginCallback(), new Delete.DisabledCallback());
    registry.clear();
}
 
Example 31
Project: cyberduck   File: DefaultPathPredicate.java   View source code 5 votes vote down vote up
protected String type() {
    final EnumSet<Path.Type> types = EnumSet.copyOf(file.getType());
    types.remove(Path.Type.placeholder);
    types.remove(Path.Type.volume);
    types.remove(Path.Type.encrypted);
    types.remove(Path.Type.decrypted);
    types.remove(Path.Type.vault);
    types.remove(Path.Type.upload);
    return String.valueOf(types);
}
 
Example 32
Project: cyberduck   File: CryptoDirectoryProvider.java   View source code 5 votes vote down vote up
/**
 * Get encrypted filename for given clear text filename with id of parent encrypted directory.
 *
 * @param session     Connection
 * @param directoryId Directory id
 * @param filename    Clear text filename
 * @param type        File type
 * @return Encrypted filename
 */
public String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<AbstractPath.Type> type) throws BackgroundException {
    final String prefix = type.contains(Path.Type.directory) ? CryptoVault.DIR_PREFIX : "";
    final String ciphertextName = String.format("%s%s", prefix,
            cryptomator.getCryptor().fileNameCryptor().encryptFilename(filename, directoryId.getBytes(StandardCharsets.UTF_8)));
    if(log.isDebugEnabled()) {
        log.debug(String.format("Encrypted filename %s to %s", filename, ciphertextName));
    }
    return cryptomator.getFilenameProvider().deflate(session, ciphertextName);
}
 
Example 33
Project: incubator-netbeans   File: FilesystemInterceptorTest.java   View source code 5 votes vote down vote up
public void testCopyVersionedFolder2UnversionedFolder_DO() throws Exception {
    // init
    File fromFolder = new File(repositoryLocation, "folder");
    fromFolder.mkdir();
    File fromFile = new File(fromFolder, "file");
    fromFile.createNewFile();

    File unversionedFolder = new File(repositoryLocation.getParentFile(), getName() + "_unversioned");
    unversionedFolder.mkdirs();
    File toFolder = new File(unversionedFolder, fromFolder.getName());
    File toFile = new File(toFolder, fromFile.getName());

    // add
    add(fromFolder);
    commit(fromFolder);

    // copy
    copyDO(fromFolder, toFolder);
    getCache().refreshAllRoots(new HashSet<File>(Arrays.asList(fromFile, toFile)));

    // test
    assertTrue(fromFolder.exists());
    assertTrue(toFolder.exists());
    assertTrue(toFile.exists());

    assertEquals(EnumSet.of(Status.UPTODATE), getCache().getStatus(fromFile).getStatus());
    assertEquals(EnumSet.of(Status.NOTVERSIONED_NOTMANAGED), getCache().getStatus(toFile).getStatus());
}
 
Example 34
Project: openjdk-jdk10   File: ExplodedImage.java   View source code 5 votes vote down vote up
void testDirectoryStreamClosed(String loc) throws IOException {
    System.err.println("testDirectoryStreamClosed(" + loc + ")");
    Path javaHome = prepareJavaHome();
    Path targetPath = javaHome.resolve(loc.replace("*", "/java.base").replace("/", sep));
    Path testClass = targetPath.resolve(("java/lang/" + TEST_FILE).replace("/", sep));
    Files.createDirectories(testClass.getParent());
    Files.createFile(testClass);
    System.setProperty("java.home", javaHome.toString());

    for (int i = 0; i < REPEATS; i++) {
        try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
            Iterable<JavaFileObject> javaLangContent =
                    fm.list(StandardLocation.PLATFORM_CLASS_PATH,
                            "java.lang",
                            EnumSet.allOf(JavaFileObject.Kind.class),
                            false);
            boolean found = false;

            for (JavaFileObject fo : javaLangContent) {
                if (!fo.getName().endsWith(TEST_FILE)) {
                    throw new IllegalStateException("Wrong file: " + fo);
                }
                found = true;
            }

            if (!found)
                throw new IllegalStateException("Could not find the expected file!");
        }
    }

    System.err.println("finished.");
}
 
Example 35
Project: cyberduck   File: LocalWriteFeatureTest.java   View source code 5 votes vote down vote up
@Test
public void testAppend() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path workdir = new LocalHomeFinderFeature(session).find();
    final Path test = new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    assertFalse(new LocalWriteFeature(session).append(test, 0L, PathCache.empty()).append);
    new LocalTouchFeature(session).touch(test, new TransferStatus());
    assertTrue(new LocalWriteFeature(session).append(test, 0L, PathCache.empty()).append);
    new LocalDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 36
Project: cyberduck   File: CustomOriginCloudFrontDistributionConfigurationTest.java   View source code 5 votes vote down vote up
@Test(expected = NotfoundException.class)
public void testReadNoConfiguredDistributionForOrigin() throws Exception {
    final Host origin = new Host(new TestProtocol(), "myhost.localdomain");
    origin.getCdnCredentials().setUsername(System.getProperties().getProperty("s3.key"));
    origin.getCdnCredentials().setPassword(System.getProperties().getProperty("s3.secret"));
    final CustomOriginCloudFrontDistributionConfiguration configuration
            = new CustomOriginCloudFrontDistributionConfiguration(origin, new DefaultX509TrustManager() {
        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String cipher) throws CertificateException {
            //
        }
    }, new DefaultX509KeyManager());
    final Path container = new Path("unknown.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
    configuration.read(container, Distribution.CUSTOM, new DisabledLoginCallback());
}
 
Example 37
Project: openjdk-jdk10   File: TraceLinearScanLifetimeAnalysisPhase.java   View source code 5 votes vote down vote up
@Override
public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
    if (isVariableOrRegister(operand)) {
        addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister);
        addRegisterHint(op, operand, mode, flags, false);
    }
}
 
Example 38
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 5 votes vote down vote up
public void testIntroduceMethodFromExpression2() throws Exception {
    performFixTest("package test;\n" +
                   "public class Test {\n" +
                   "    public static void test() {\n" +
                   "        java.util.List<? extends String> l = null;\n" +
                   "        System.err.println(|l.get(0)|);\n" +
                   "    }\n" +
                   "}",
                   "package test; import java.util.List; public class Test { public static void test() { java.util.List<? extends String> l = null; System.err.println(name(l)); } private static String name(List<? extends String> l) { return l.get(0); } }",
                   new DialogDisplayerImpl3("name", EnumSet
            .of(Modifier.PRIVATE), true),
                   4, 2);
}
 
Example 39
Project: incubator-netbeans   File: FieldGroupTest.java   View source code 5 votes vote down vote up
public void testNoFieldGroup() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package javaapplication1;\n" +
        "\n" +
        "class MyOuterClass {\n" +
        "}\n"
        );
    String golden = 
        "package javaapplication1;\n" +
        "\n" +
        "class MyOuterClass {\n" +
        "\n" +
        "    private Exception a;\n" + 
        "    private String b;\n" + 
        "    private Object c;\n" + 
        "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PRIVATE));
            Elements e = workingCopy.getElements();
            
            ClassTree nue = make.insertClassMember(clazz, 0, make.Variable(mods, "c", make.QualIdent(e.getTypeElement("java.lang.Object")), null));
            nue = make.insertClassMember(nue, 0, make.Variable(mods, "b", make.QualIdent(e.getTypeElement("java.lang.String")), null));
            nue = make.insertClassMember(nue, 0, make.Variable(mods, "a", make.QualIdent(e.getTypeElement("java.lang.Exception")), null));
            workingCopy.rewrite(clazz, nue);
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example 40
Project: hadoop   File: TestRetryCacheWithHA.java   View source code 5 votes vote down vote up
@Override
void invoke() throws Exception {
  client.modifyCacheDirective(
      new CacheDirectiveInfo.Builder().
          setId(id).
          setReplication(newReplication).
          build(), EnumSet.of(CacheFlag.FORCE));
}