java.util.EnumSet Java Examples

The following examples show how to use java.util.EnumSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestNNAnalyticsBase.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidQueryChecker() throws Exception {
  HashMap<INodeSet, HashMap<String, HashMap<String, ArrayList<EnumSet<Filter>>>>>
      setSumTypeFilterConfig = getInvalidCombinations();
  String[] parameters = new String[4];
  for (INodeSet set : INodeSet.values()) {
    String setType = set.toString();
    parameters[0] = setType;
    HashMap<String, HashMap<String, ArrayList<EnumSet<Filter>>>> sumTypeFilters =
        setSumTypeFilterConfig.get(set);
    for (Map.Entry<String, HashMap<String, ArrayList<EnumSet<Filter>>>> sumTypeFilter :
        sumTypeFilters.entrySet()) {
      HashMap<String, ArrayList<EnumSet<Filter>>> typeFilters = sumTypeFilter.getValue();
      String sum = sumTypeFilter.getKey();
      parameters[1] = sum;
      for (Map.Entry<String, ArrayList<EnumSet<Filter>>> typeFilter : typeFilters.entrySet()) {
        String type = typeFilter.getKey();
        parameters[2] = type;
        String testingURL = buildQuery(parameters);
        testQuery(testingURL, false);
      }
    }
  }
}
 
Example #2
Source File: Bundle.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("ConvertToStringSwitch")
Bundle(String id, String cldrPath, String bundles, String currencies) {
    this.id = id;
    this.cldrPath = cldrPath;
    if ("localenames".equals(bundles)) {
        bundleTypes = EnumSet.of(Type.LOCALENAMES);
    } else if ("currencynames".equals(bundles)) {
        bundleTypes = EnumSet.of(Type.CURRENCYNAMES);
    } else {
        bundleTypes = Type.ALL_TYPES;
    }
    if (currencies == null) {
        currencies = "local";
    }
    this.currencies = currencies;
    addBundle();
}
 
Example #3
Source File: OzoneBlockTokenSecretManager.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an block token for specified user, blockId. Service field for
 * token is set to blockId.
 *
 * @param user
 * @param blockId
 * @param modes
 * @param maxLength
 * @return token
 */
public Token<OzoneBlockTokenIdentifier> generateToken(String user,
    String blockId, EnumSet<AccessModeProto> modes, long maxLength) {
  OzoneBlockTokenIdentifier tokenIdentifier = createIdentifier(user,
      blockId, modes, maxLength);
  if (LOG.isTraceEnabled()) {
    long expiryTime = tokenIdentifier.getExpiryDate();
    String tokenId = tokenIdentifier.toString();
    LOG.trace("Issued delegation token -> expiryTime:{}, tokenId:{}",
        expiryTime, tokenId);
  }
  // Pass blockId as service.
  return new Token<>(tokenIdentifier.getBytes(),
      createPassword(tokenIdentifier), tokenIdentifier.getKind(),
      new Text(blockId));
}
 
Example #4
Source File: SimpleConversionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void providerAssignedMessageId_UuidMode_10_010() throws Exception
{
    assumeTrue(EnumSet.of(Protocol.AMQP_1_0).contains(getPublisherProtocolVersion())
               && EnumSet.of(Protocol.AMQP_0_10).contains(getSubscriberProtocolVersion()));

    List<ClientMessage> clientResults = performProviderAssignedMessageIdTest(Collections.singletonMap(
            JMS_MESSAGE_IDPOLICY_MESSAGE_IDTYPE, "UUID"));

    ClientMessage publishedMessage = clientResults.get(0);
    ClientMessage subscriberMessage = clientResults.get(1);

    // On the wire the message-id is a message-id-uuid
    final String publishedJmsMessageID = publishedMessage.getJMSMessageID();
    assertThat(publishedJmsMessageID, startsWith("ID:AMQP_UUID:"));
    String barePublishedJmsMessageID = publishedJmsMessageID.substring("ID:AMQP_UUID:".length());
    String expectedSubscriberJmsMessageID = String.format("ID:%s", barePublishedJmsMessageID);
    assertThat(subscriberMessage.getJMSMessageID(), equalTo(expectedSubscriberJmsMessageID));
}
 
Example #5
Source File: SampleVerifier.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void actionPerformed (ActionEvent e)
{
    // Populate with shape names found in selected folders
    List<String> folders = folderSelector.list.getSelectedValuesList();

    if (folders.isEmpty()) {
        logger.warn("No folders selected in Folder Selector");
    } else {
        EnumSet<Shape> shapeSet = EnumSet.noneOf(Shape.class);

        for (String folder : folders) {
            File dir = getActualDir(folder);

            // Add all glyphs files from this directory
            for (File file : repository.getGlyphsIn(dir)) {
                shapeSet.add(Shape.valueOf(radixOf(file.getName())));
            }
        }

        populateWith(shapeSet);
    }
}
 
Example #6
Source File: TXManagerImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public final TXStateProxy resumeTX(final TXManagerImpl.TXContext context,
    final IsolationLevel isolationLevel,
    final EnumSet<TransactionFlag> txFlags, TXId txid) {
  checkClosed();
  TXId txId = context.getTXId();
  context.remoteBatching(false);
  if (txId != null) {
    throw new IllegalTransactionStateException(
        LocalizedStrings.TXManagerImpl_TRANSACTION_0_ALREADY_IN_PROGRESS
            .toLocalizedString(txId));
  }
  txId = txid;
  // Do we have a proxy here
  TXStateProxy txState = this.hostedTXStates.get(txId);
  if (txState != null) {
    return txState;
  }
  txState = this.hostedTXStates.create(txId,
      txStateProxyCreator, isolationLevel, txFlags, false);
  // context.setTXState(txState);
  return txState;
}
 
Example #7
Source File: T6431257.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
void testPackage(String packageName) throws IOException {
    JavaFileObject object
        = fm.getJavaFileForInput(PLATFORM_CLASS_PATH, "java.lang.Object", CLASS);
    Iterable<? extends JavaFileObject> files
        = fm.list(CLASS_OUTPUT, packageName, EnumSet.of(CLASS), false);
    boolean found = false;
    String binaryPackageName = packageName.replace('/', '.');
    for (JavaFileObject file : files) {
        System.out.println("Found " + file.getName() + " in " + packageName);
        String name = fm.inferBinaryName(CLASS_OUTPUT, file);
        found |= name.equals(binaryPackageName + ".package-info");
        JavaFileObject other = fm.getJavaFileForInput(CLASS_OUTPUT, name, CLASS);
        if (!fm.isSameFile(file, other))
            throw new AssertionError(file + " != " + other);
        if (fm.isSameFile(file, object))
            throw new AssertionError(file + " == " + object);
    }
    if (!found)
        throw new AssertionError("Did not find " + binaryPackageName + ".package-info");
}
 
Example #8
Source File: DAGAppMaster.java    From incubator-tez with Apache License 2.0 6 votes vote down vote up
private synchronized void checkAndHandleSessionTimeout() {
  if (EnumSet.of(DAGAppMasterState.RUNNING,
      DAGAppMasterState.RECOVERING).contains(this.state)
      || sessionStopped.get()) {
    // DAG running or session already completed, cannot timeout session
    return;
  }
  long currentTime = clock.getTime();
  if (currentTime < (lastDAGCompletionTime + sessionTimeoutInterval)) {
    return;
  }
  LOG.info("Session timed out"
      + ", lastDAGCompletionTime=" + lastDAGCompletionTime + " ms"
      + ", sessionTimeoutInterval=" + sessionTimeoutInterval + " ms");
  shutdownTezAM();
}
 
Example #9
Source File: GeoIPISPDissector.java    From logparser with Apache License 2.0 6 votes vote down vote up
@Override
public EnumSet<Casts> prepareForDissect(final String inputname, final String outputname) {
    EnumSet<Casts> result = super.prepareForDissect(inputname, outputname);
    if (!result.isEmpty()) {
        return result;
    }
    String name = extractFieldName(inputname, outputname);

    switch (name) {
        case "isp.name":
            wantIspName = true;
            return STRING_ONLY;

        case "isp.organization":
            wantIspOrganization = true;
            return STRING_ONLY;

        default:
            return NO_CASTS;
    }
}
 
Example #10
Source File: ArgGroupParameterizedTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
@junitparams.Parameters(method = "commandMethodArgs")
public void testCommandMethod(String args,
                              InvokedSub invokedSub,
                              ArgGroupTest.SomeMixin expectedMixin,
                              ArgGroupTest.Composite expectedArgGroup,
                              int[] expectedPositionalInt,
                              String[] expectedStrings) {
    ArgGroupTest.CommandMethodsWithGroupsAndMixins bean = new ArgGroupTest.CommandMethodsWithGroupsAndMixins();
    new CommandLine(bean).execute(args.split(" "));
    assertTrue(bean.invoked.contains(invokedSub));
    EnumSet<InvokedSub> notInvoked = EnumSet.allOf(InvokedSub.class);
    notInvoked.remove(invokedSub);
    for (InvokedSub sub : notInvoked) {
        assertFalse(bean.invoked.contains(sub));
    }
    assertTrue(bean.invoked.contains(invokedSub));
    assertEquals(expectedMixin, bean.myMixin);
    assertEquals(expectedArgGroup, bean.myComposite);
    assertArrayEquals(expectedPositionalInt, bean.myPositionalInt);
    assertArrayEquals(expectedStrings, bean.myStrings);
}
 
Example #11
Source File: SDSSharesUrlProviderTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test(expected = InteroperabilityException.class)
public void testToUrlInvalidSMSRecipients() throws Exception {
    final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache);
    final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume, Path.Type.triplecrypt)), null, new TransferStatus());
    final Path test = new SDSTouchFeature(session, nodeid).touch(new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
    try {
        final DescriptiveUrl url = new SDSSharesUrlProvider(session, nodeid).toDownloadUrl(test,
            new CreateDownloadShareRequest()
                .expiration(new ObjectExpiration().enableExpiration(false))
                .notifyCreator(false)
                .sendMail(false)
                .mailRecipients(null)
                .sendSms(true)
                .smsRecipients("invalid")
                .password("p")
                .mailSubject(null)
                .mailBody(null)
                .maxDownloads(null), new DisabledPasswordCallback());
    }
    finally {
        new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
    }
}
 
Example #12
Source File: OcspUnauthorized.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    cf = CertificateFactory.getInstance("X.509");
    X509Certificate taCert = getX509Cert(TRUST_ANCHOR);
    X509Certificate eeCert = getX509Cert(EE_CERT);
    CertPath cp = cf.generateCertPath(Collections.singletonList(eeCert));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXRevocationChecker prc =
        (PKIXRevocationChecker)cpv.getRevocationChecker();
    prc.setOptions(EnumSet.of(Option.SOFT_FAIL, Option.NO_FALLBACK));
    byte[] response = base64Decoder.decode(OCSP_RESPONSE);

    prc.setOcspResponses(Collections.singletonMap(eeCert, response));

    TrustAnchor ta = new TrustAnchor(taCert, null);
    PKIXParameters params = new PKIXParameters(Collections.singleton(ta));

    params.addCertPathChecker(prc);

    try {
        cpv.validate(cp, params);
        throw new Exception("FAILED: expected CertPathValidatorException");
    } catch (CertPathValidatorException cpve) {
        cpve.printStackTrace();
    }
}
 
Example #13
Source File: FilesystemInterceptorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCopyAddedFile2UnversionedFolder_DO() throws Exception {
    // init
    File fromFile = new File(repositoryLocation, "file");
    fromFile.createNewFile();
    File toFolder = new File(repositoryLocation.getParentFile(), "toFolder");
    toFolder.mkdirs();

    File toFile = new File(toFolder, fromFile.getName());

    // add
    add(fromFile);

    // copy
    copyDO(fromFile, toFile);
    getCache().refreshAllRoots(Collections.singleton(fromFile));
    getCache().refreshAllRoots(Collections.singleton(toFile));

    // test
    assertTrue(fromFile.exists());
    assertTrue(toFile.exists());

    assertEquals(EnumSet.of(Status.NEW_HEAD_INDEX, Status.NEW_HEAD_WORKING_TREE), getCache().getStatus(fromFile).getStatus());
    assertEquals(EnumSet.of(Status.NOTVERSIONED_NOTMANAGED), getCache().getStatus(toFile).getStatus());
}
 
Example #14
Source File: S3MetadataFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSetMetadataFileLeaveOtherFeatures() throws Exception {
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume));
    final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    new S3TouchFeature(session).touch(test, new TransferStatus());
    final String v = UUID.randomUUID().toString();
    final S3StorageClassFeature storage = new S3StorageClassFeature(session);
    storage.setClass(test, S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY);
    assertEquals(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, storage.getClass(test));

    final S3EncryptionFeature encryption = new S3EncryptionFeature(session);
    encryption.setEncryption(test, S3EncryptionFeature.SSE_AES256);
    assertEquals("AES256", encryption.getEncryption(test).algorithm);

    final S3MetadataFeature feature = new S3MetadataFeature(session, new S3AccessControlListFeature(session));
    feature.setMetadata(test, Collections.singletonMap("Test", v));
    final Map<String, String> metadata = feature.getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertTrue(metadata.containsKey("test"));
    assertEquals(v, metadata.get("test"));

    assertEquals(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, storage.getClass(test));
    assertEquals("AES256", encryption.getEncryption(test).algorithm);

    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #15
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected void dropConstraints(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile, Charset.defaultCharset())) {
       		if (isDroppingConstraints(sql))
       			sqls.add(sql);
       	}
       	execute(sqls, false);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example #16
Source File: IntroduceHintTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIntroduceFieldFix114360() throws Exception {
    performFixTest("package test; public enum Test {\n" +
                   "    A;\n" +
                   "    public void method() {\n" +
                   "        String s = |\"const\"|;\n" +
                   "    }\n" +
                   "}\n",
                   "package test; public enum Test { A; private String aconst; Test() { aconst = \"const\"; } public void method() { String s = aconst; } } ",
                   new DialogDisplayerImpl2(null, IntroduceFieldPanel.INIT_CONSTRUCTORS, false, EnumSet
            .<Modifier>of(Modifier.PRIVATE), false, true),
                   5, 2);
}
 
Example #17
Source File: JBossDeploymentStructureParser11.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void parseModuleAlias(final XMLStreamReader reader, final ModuleStructureSpec moduleSpec) throws XMLStreamException {
    final int count = reader.getAttributeCount();
    String name = null;
    String slot = null;
    final Set<Attribute> required = EnumSet.of(Attribute.NAME);
    for (int i = 0; i < count; i++) {
        final Attribute attribute = Attribute.of(reader.getAttributeName(i));
        required.remove(attribute);
        switch (attribute) {
            case NAME:
                name = reader.getAttributeValue(i);
                break;
            case SLOT:
                slot = reader.getAttributeValue(i);
                break;
            default:
                throw unexpectedContent(reader);
        }
    }
    if (!required.isEmpty()) {
        throw missingAttributes(reader.getLocation(), required);
    }
    while (reader.hasNext()) {
        switch (reader.nextTag()) {
            case END_ELEMENT: {
                moduleSpec.addAlias(ModuleIdentifier.create(name, slot));
                return;
            }
            default: {
                throw unexpectedContent(reader);
            }
        }
    }
    throw endOfDocument(reader.getLocation());
}
 
Example #18
Source File: TestFinder.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static <T> void findTests(final String framework, final Path dir, final List<T> tests, final Set<String> orphanFiles, final Path[] excludePaths, final Set<String> excludedTests, final TestFactory<T> factory) throws Exception {
    final String pattern = System.getProperty(TEST_JS_INCLUDES);
    final String extension = pattern == null ? "js" : pattern;
    final Exception[] exceptions = new Exception[1];
    final List<String> excludedActualTests = new ArrayList<>();

    if (!dir.toFile().isDirectory()) {
        factory.log("WARNING: " + dir + " not found or not a directory");
    }

    Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String fileName = file.getName(file.getNameCount() - 1).toString();
            if (fileName.endsWith(extension)) {
                final String namex = file.toString().replace('\\', '/');
                if (!inExcludePath(file, excludePaths) && !excludedTests.contains(file.getFileName().toString())) {
                    try {
                        handleOneTest(framework, file, tests, orphanFiles, factory);
                    } catch (final Exception ex) {
                        exceptions[0] = ex;
                        return FileVisitResult.TERMINATE;
                    }
                } else {
                    excludedActualTests.add(namex);
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });
    Collections.sort(excludedActualTests);

    for (final String excluded : excludedActualTests) {
        factory.log("Excluding " + excluded);
    }

    if (exceptions[0] != null) {
        throw exceptions[0];
    }
}
 
Example #19
Source File: FlagOpTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void testFlagsSetSequence(Supplier<StatefulTestOp<Integer>> cf) {
    EnumSet<StreamOpFlag> known = EnumSet.of(StreamOpFlag.ORDERED, StreamOpFlag.SIZED);
    EnumSet<StreamOpFlag> preserve = EnumSet.of(StreamOpFlag.DISTINCT, StreamOpFlag.SORTED);

    List<IntermediateTestOp<Integer, Integer>> ops = new ArrayList<>();
    for (StreamOpFlag f : EnumSet.of(StreamOpFlag.DISTINCT, StreamOpFlag.SORTED)) {
        ops.add(cf.get());
        ops.add(new TestFlagExpectedOp<>(f.set(),
                                         known.clone(),
                                         preserve.clone(),
                                         EnumSet.noneOf(StreamOpFlag.class)));
        known.add(f);
        preserve.remove(f);
    }
    ops.add(cf.get());
    ops.add(new TestFlagExpectedOp<>(0,
                                     known.clone(),
                                     preserve.clone(),
                                     EnumSet.noneOf(StreamOpFlag.class)));

    TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
    @SuppressWarnings("rawtypes")
    IntermediateTestOp[] opsArray = ops.toArray(new IntermediateTestOp[ops.size()]);

    withData(data).ops(opsArray).
            without(StreamTestScenario.CLEAR_SIZED_SCENARIOS).
            exercise();
}
 
Example #20
Source File: EnumSetTest.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/** Test failure mode from issue 3605. Previously resulted in a NoSuchElementException. */
public void testDuplicatesToArray() {
  EnumSet<Numbers> set = EnumSet.of(Numbers.Two, Numbers.One, Numbers.Two, Numbers.One);
  Numbers[] array = set.toArray(new Numbers[set.size()]);
  assertNotNull(array);
  assertEquals(2, array.length);
  if (array[0] != Numbers.One && array[1] != Numbers.One) {
    fail("Numbers.One not found");
  }
  if (array[0] != Numbers.Two && array[1] != Numbers.Two) {
    fail("Numbers.Two not found");
  }
}
 
Example #21
Source File: SchemeGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
public static Element serializeBuildAction(Document doc, XCScheme.BuildAction buildAction) {
  Element buildActionElem = doc.createElement("BuildAction");
  serializePrePostActions(doc, buildAction, buildActionElem);

  buildActionElem.setAttribute(
      "parallelizeBuildables", buildAction.getParallelizeBuild() ? "YES" : "NO");
  buildActionElem.setAttribute(
      "buildImplicitDependencies", buildAction.getParallelizeBuild() ? "YES" : "NO");

  Element buildActionEntriesElem = doc.createElement("BuildActionEntries");
  buildActionElem.appendChild(buildActionEntriesElem);

  for (XCScheme.BuildActionEntry entry : buildAction.getBuildActionEntries()) {
    Element entryElem = doc.createElement("BuildActionEntry");
    buildActionEntriesElem.appendChild(entryElem);

    EnumSet<XCScheme.BuildActionEntry.BuildFor> buildFor = entry.getBuildFor();
    boolean buildForRunning = buildFor.contains(XCScheme.BuildActionEntry.BuildFor.RUNNING);
    entryElem.setAttribute("buildForRunning", buildForRunning ? "YES" : "NO");
    boolean buildForTesting = buildFor.contains(XCScheme.BuildActionEntry.BuildFor.TESTING);
    entryElem.setAttribute("buildForTesting", buildForTesting ? "YES" : "NO");
    boolean buildForProfiling = buildFor.contains(XCScheme.BuildActionEntry.BuildFor.PROFILING);
    entryElem.setAttribute("buildForProfiling", buildForProfiling ? "YES" : "NO");
    boolean buildForArchiving = buildFor.contains(XCScheme.BuildActionEntry.BuildFor.ARCHIVING);
    entryElem.setAttribute("buildForArchiving", buildForArchiving ? "YES" : "NO");
    boolean buildForAnalyzing = buildFor.contains(XCScheme.BuildActionEntry.BuildFor.ANALYZING);
    entryElem.setAttribute("buildForAnalyzing", buildForAnalyzing ? "YES" : "NO");

    Element refElem = serializeBuildableReference(doc, entry.getBuildableReference());
    entryElem.appendChild(refElem);
  }

  return buildActionElem;
}
 
Example #22
Source File: EnumSetWritable.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public boolean add(E e) {
  if (value == null) {
    value = EnumSet.of(e);
    set(value, null);
  }
  return value.add(e);
}
 
Example #23
Source File: RequestLogTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private Server initJetty() throws Exception {
	Server server = new Server(0);
	ServletContextHandler handler = new ServletContextHandler(server, null);
	handler.addFilter(RequestLoggingFilter.class, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST,
			DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.ASYNC));
	handler.addServlet(TestServlet.class, "/test");
	server.start();
	return server;
}
 
Example #24
Source File: EnumSetParam.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
protected EnumSet<E> parse(String str) throws Exception {
  final EnumSet<E> set = EnumSet.noneOf(klass);
  if (!str.isEmpty()) {
    for (String sub : str.split(",")) {
      set.add(Enum.valueOf(klass, StringUtils.toUpperCase(sub.trim())));
    }
  }
  return set;
}
 
Example #25
Source File: NumericShaper.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private NumericShaper(Range defaultContext, Set<Range> ranges) {
    shapingRange = defaultContext;
    rangeSet = EnumSet.copyOf(ranges); // throws NPE if ranges is null.

    // Give precedance to EASTERN_ARABIC if both ARABIC and
    // EASTERN_ARABIC are specified.
    if (rangeSet.contains(Range.EASTERN_ARABIC)
        && rangeSet.contains(Range.ARABIC)) {
        rangeSet.remove(Range.ARABIC);
    }

    // As well as the above case, give precedance to TAI_THAM_THAM if both
    // TAI_THAM_HORA and TAI_THAM_THAM are specified.
    if (rangeSet.contains(Range.TAI_THAM_THAM)
        && rangeSet.contains(Range.TAI_THAM_HORA)) {
        rangeSet.remove(Range.TAI_THAM_HORA);
    }

    rangeArray = rangeSet.toArray(new Range[rangeSet.size()]);
    if (rangeArray.length > BSEARCH_THRESHOLD) {
        // sort rangeArray for binary search
        Arrays.sort(rangeArray,
                    new Comparator<Range>() {
                        public int compare(Range s1, Range s2) {
                            return s1.base > s2.base ? 1 : s1.base == s2.base ? 0 : -1;
                        }
                    });
    }
}
 
Example #26
Source File: NumericShaper.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private NumericShaper(Range defaultContext, Set<Range> ranges) {
    shapingRange = defaultContext;
    rangeSet = EnumSet.copyOf(ranges); // throws NPE if ranges is null.

    // Give precedance to EASTERN_ARABIC if both ARABIC and
    // EASTERN_ARABIC are specified.
    if (rangeSet.contains(Range.EASTERN_ARABIC)
        && rangeSet.contains(Range.ARABIC)) {
        rangeSet.remove(Range.ARABIC);
    }

    // As well as the above case, give precedance to TAI_THAM_THAM if both
    // TAI_THAM_HORA and TAI_THAM_THAM are specified.
    if (rangeSet.contains(Range.TAI_THAM_THAM)
        && rangeSet.contains(Range.TAI_THAM_HORA)) {
        rangeSet.remove(Range.TAI_THAM_HORA);
    }

    rangeArray = rangeSet.toArray(new Range[rangeSet.size()]);
    if (rangeArray.length > BSEARCH_THRESHOLD) {
        // sort rangeArray for binary search
        Arrays.sort(rangeArray,
                    new Comparator<Range>() {
                        public int compare(Range s1, Range s2) {
                            return s1.base > s2.base ? 1 : s1.base == s2.base ? 0 : -1;
                        }
                    });
    }
}
 
Example #27
Source File: FontPanel.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static Object getValue(int ordinal) {
    if (valArray == null) {
        valArray = (FMValues[])EnumSet.allOf(FMValues.class).toArray(new FMValues[0]);
    }
    for (int i=0;i<valArray.length;i++) {
        if (valArray[i].ordinal() == ordinal) {
            return valArray[i];
        }
    }
    return valArray[0];
}
 
Example #28
Source File: GetClusterNodesRequestPBImpl.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void setNodeStates(final EnumSet<NodeState> states) {
  initNodeStates();
  this.states.clear();
  if (states == null) {
    return;
  }
  this.states.addAll(states);
}
 
Example #29
Source File: PathTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDictionaryFileSymbolicLink() {
    Path path = new Path("/path", EnumSet.of(Path.Type.file, Path.Type.symboliclink));
    assertEquals(path, new PathDictionary().deserialize(path.serialize(SerializerFactory.get())));
    assertEquals(EnumSet.of(Path.Type.file, Path.Type.symboliclink),
            new PathDictionary().deserialize(path.serialize(SerializerFactory.get())).getType());
}
 
Example #30
Source File: OneUniverse.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static <E extends Enum<E>> Enum<E>[] getUniverse(EnumSet<E> set) {
    try {
        return (Enum<E>[]) universeField.get(set);
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);
    }
}