List of usage examples for java.util EnumSet noneOf
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)
From source file:org.apache.felix.karaf.deployer.features.FeatureDeploymentListener.java
public void bundleChanged(BundleEvent bundleEvent) { try {/*from w w w . j av a2s . com*/ Bundle bundle = bundleEvent.getBundle(); if (bundleEvent.getType() == BundleEvent.RESOLVED) { Enumeration featuresUrlEnumeration = bundle.findEntries("/META-INF/" + FEATURE_PATH + "/", "*.xml", false); while (featuresUrlEnumeration != null && featuresUrlEnumeration.hasMoreElements()) { URL url = (URL) featuresUrlEnumeration.nextElement(); featuresService.addRepository(url.toURI()); for (Repository repo : featuresService.listRepositories()) { if (repo.getURI().equals(url.toURI())) { Set<Feature> features = new HashSet<Feature>(Arrays.asList(repo.getFeatures())); try { featuresService.installFeatures(features, EnumSet.noneOf(FeaturesService.Option.class)); } catch (Exception e) { LOGGER.error("Unable to install features", e); } } } } } else if (bundleEvent.getType() == BundleEvent.UNINSTALLED) { Enumeration featuresUrlEnumeration = bundle.findEntries("/META-INF/" + FEATURE_PATH + "/", "*.xml", false); while (featuresUrlEnumeration != null && featuresUrlEnumeration.hasMoreElements()) { URL url = (URL) featuresUrlEnumeration.nextElement(); for (Repository repo : featuresService.listRepositories()) { if (repo.getURI().equals(url.toURI())) { for (Feature f : repo.getFeatures()) { try { featuresService.uninstallFeature(f.getName(), f.getVersion()); } catch (Exception e) { LOGGER.error("Unable to uninstall feature: " + f.getName(), e); } } } } featuresService.removeRepository(url.toURI()); } } } catch (Exception e) { LOGGER.error("Unable to install / uninstall feature", e); } }
From source file:org.apache.hadoop.hdfs.server.datanode.TestFsDatasetCacheRevocation.java
/** * Test that when a client has a replica mmapped, we will not un-mlock that * replica for a reasonable amount of time, even if an uncache request * occurs./*from w w w .ja v a 2s. com*/ */ @Test(timeout = 120000) public void testPinning() throws Exception { assumeTrue(NativeCodeLoader.isNativeCodeLoaded() && !Path.WINDOWS); Configuration conf = getDefaultConf(); // Set a really long revocation timeout, so that we won't reach it during // this test. conf.setLong(DFSConfigKeys.DFS_DATANODE_CACHE_REVOCATION_TIMEOUT_MS, 1800000L); // Poll very often conf.setLong(DFSConfigKeys.DFS_DATANODE_CACHE_REVOCATION_POLLING_MS, 2L); MiniDFSCluster cluster = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); // Create and cache a file. final String TEST_FILE = "/test_file"; DFSTestUtil.createFile(dfs, new Path(TEST_FILE), BLOCK_SIZE, (short) 1, 0xcafe); dfs.addCachePool(new CachePoolInfo("pool")); long cacheDirectiveId = dfs.addCacheDirective(new CacheDirectiveInfo.Builder().setPool("pool") .setPath(new Path(TEST_FILE)).setReplication((short) 1).build()); FsDatasetSpi<?> fsd = cluster.getDataNodes().get(0).getFSDataset(); DFSTestUtil.verifyExpectedCacheUsage(BLOCK_SIZE, 1, fsd); // Mmap the file. FSDataInputStream in = dfs.open(new Path(TEST_FILE)); ByteBuffer buf = in.read(null, BLOCK_SIZE, EnumSet.noneOf(ReadOption.class)); // Attempt to uncache file. The file should still be cached. dfs.removeCacheDirective(cacheDirectiveId); Thread.sleep(500); DFSTestUtil.verifyExpectedCacheUsage(BLOCK_SIZE, 1, fsd); // Un-mmap the file. The file should be uncached after this. in.releaseBuffer(buf); DFSTestUtil.verifyExpectedCacheUsage(0, 0, fsd); // Cleanup in.close(); cluster.shutdown(); }
From source file:org.compass.core.converter.mapping.osem.CollectionMappingConverter.java
protected Object createColObject(Getter getter, AbstractCollectionMapping.CollectionType collectionType, int size, AbstractCollectionMapping mapping, MarshallingContext context) { if (((CollectionMapping) mapping).isLazy()) { if (collectionType == AbstractCollectionMapping.CollectionType.LIST) { return new LazyReferenceList(context.getSession(), size); } else if (collectionType == AbstractCollectionMapping.CollectionType.SET || collectionType == AbstractCollectionMapping.CollectionType.SORTED_SET || collectionType == AbstractCollectionMapping.CollectionType.LINKED_HASH_SET) { return new LazyReferenceSet(context.getSession(), size, collectionType); } else {/*from w w w .j av a2 s . c om*/ throw new IllegalStateException( "Lazy not supported for this type of collection [" + collectionType + "]"); } } else { if (collectionType == AbstractCollectionMapping.CollectionType.LIST) { return new ArrayList(size); } else if (collectionType == AbstractCollectionMapping.CollectionType.ENUM_SET) { return EnumSet.noneOf(AccessorUtils.getCollectionParameter(getter)); } else if (collectionType == AbstractCollectionMapping.CollectionType.SET) { return new HashSet(size); } else if (collectionType == AbstractCollectionMapping.CollectionType.SORTED_SET) { return new TreeSet(); } else if (collectionType == AbstractCollectionMapping.CollectionType.LINKED_HASH_SET) { return new LinkedHashSet(size); } else { throw new IllegalStateException("Should not happen, internal compass error"); } } }
From source file:com.github.rolecraftdev.guild.Guild.java
/** * Create a new {@link Guild}, automatically generating a semi-random * {@link UUID}; and the leader and default {@link GuildRank}s. When the * given {@link GuildManager} is {@code null}, all fields will be assigned * {@code null}./*from ww w. j a v a2 s . c o m*/ * * @param guildManager the {@link GuildManager} this {@link Guild} will be * registered to * @since 0.0.5 */ public Guild(final GuildManager guildManager) { if (guildManager == null) { this.guildManager = null; plugin = null; members = null; ranks = null; guildId = null; channel = null; return; } plugin = guildManager.getPlugin(); this.guildManager = guildManager; guildId = UUID.randomUUID(); members = new HashSet<UUID>(); ranks = new HashSet<GuildRank>(); ranks.add(new GuildRank(plugin.getMessage(Messages.GUILD_LEADER_RANK), EnumSet.allOf(GuildAction.class), new HashSet<UUID>())); ranks.add(new GuildRank(plugin.getMessage(Messages.GUILD_DEFAULT_RANK), EnumSet.noneOf(GuildAction.class), new HashSet<UUID>())); channel = new DefaultChannel(new DefaultChannelConfig().setOption(ChannelOption.PREFIX, "[GC] ")); }
From source file:com.inmobi.conduit.distcp.tools.util.DistCpUtils.java
/** * Un packs preservation attribute string containing the first character of * each preservation attribute back to a set of attributes to preserve * @param attributes - Attribute string/*from w w w . j a v a 2 s . c om*/ * @return - Attribute set */ public static EnumSet<FileAttribute> unpackAttributes(String attributes) { EnumSet<FileAttribute> retValue = EnumSet.noneOf(FileAttribute.class); if (attributes != null) { for (int index = 0; index < attributes.length(); index++) { retValue.add(FileAttribute.getAttribute(attributes.charAt(index))); } } return retValue; }
From source file:fr.ritaly.dungeonmaster.ai.CreatureManager.java
private EnumSet<Direction> getFreeDirections() { if (creatures != null) { final boolean ne = !creatures.containsKey(Sector.NORTH_EAST); final boolean nw = !creatures.containsKey(Sector.NORTH_WEST); final boolean se = !creatures.containsKey(Sector.SOUTH_EAST); final boolean sw = !creatures.containsKey(Sector.SOUTH_WEST); int count = 0; if (ne) { count++;//from w ww . j a v a2 s .c o m } if (nw) { count++; } if (se) { count++; } if (sw) { count++; } switch (count) { case 0: case 1: // No free direction return EnumSet.noneOf(Direction.class); case 2: // At most one direction free if (ne && nw) { return EnumSet.of(Direction.NORTH); } else if (se && sw) { return EnumSet.of(Direction.SOUTH); } else if (nw && sw) { return EnumSet.of(Direction.WEST); } else if (ne && se) { return EnumSet.of(Direction.EAST); } else { // No direction free (the sectors are staggered) return EnumSet.noneOf(Direction.class); } case 3: // One for sure, maybe 2 final List<Direction> directions = new ArrayList<Direction>(2); if (ne && nw) { directions.add(Direction.NORTH); } if (se && sw) { directions.add(Direction.SOUTH); } if (nw && sw) { directions.add(Direction.WEST); } if (ne && se) { directions.add(Direction.EAST); } if (directions.size() == 1) { return EnumSet.of(directions.iterator().next()); } else { Collections.shuffle(directions); return EnumSet.of(directions.iterator().next()); } case 4: // 2 are free // Choose a random pair of directions if (RandomUtils.nextBoolean()) { return EnumSet.of(Direction.EAST, Direction.WEST); } else { return EnumSet.of(Direction.NORTH, Direction.SOUTH); } default: throw new RuntimeException("Unexpected count <" + count + ">"); } } // Choose a random pair of directions if (RandomUtils.nextBoolean()) { return EnumSet.of(Direction.EAST, Direction.WEST); } else { return EnumSet.of(Direction.NORTH, Direction.SOUTH); } }
From source file:ws.wamp.jawampa.client.HandshakingState.java
void onMessage(WampMessage msg) { // We were not yet welcomed if (msg instanceof WelcomeMessage) { // Receive a welcome. Now the session is established! ObjectNode welcomeDetails = ((WelcomeMessage) msg).details; long sessionId = ((WelcomeMessage) msg).sessionId; // Extract the roles of the remote side JsonNode roleNode = welcomeDetails.get("roles"); if (roleNode == null || !roleNode.isObject()) { handleProtocolError();//w w w . j av a 2s .co m return; } EnumSet<WampRoles> routerRoles = EnumSet.noneOf(WampRoles.class); Iterator<String> roleKeys = roleNode.fieldNames(); while (roleKeys.hasNext()) { WampRoles role = WampRoles.fromString(roleKeys.next()); if (role != null) routerRoles.add(role); } SessionEstablishedState newState = new SessionEstablishedState(stateController, connectionController, sessionId, welcomeDetails, routerRoles); stateController.setState(newState); } else if (msg instanceof ChallengeMessage) { if (!challengeMsgAllowed) { // Allow Challenge message only a single time handleProtocolError(); return; } challengeMsgAllowed = false; ChallengeMessage challenge = (ChallengeMessage) msg; String authMethodString = challenge.authMethod; List<ClientSideAuthentication> authMethods = stateController.clientConfig().authMethods(); for (ClientSideAuthentication authMethod : authMethods) { if (authMethod.getAuthMethod().equals(authMethodString)) { AuthenticateMessage reply = authMethod.handleChallenge(challenge, stateController.clientConfig().objectMapper()); if (reply == null) { handleProtocolError(); } else { connectionController.sendMessage(reply, IWampConnectionPromise.Empty); } return; } } handleProtocolError(); } else if (msg instanceof AbortMessage) { // The remote doesn't want us to connect :( AbortMessage abort = (AbortMessage) msg; handleSessionError(new ApplicationError(abort.reason), null); } }
From source file:com.sg.rest.SpringSecurityTest.java
@Test public void testSecureResourceWithAuthToken() throws IOException, Exception { String authToken = webSecurityService.generateToken(ACCOUNT_ID, Instant.now(), TokenExpirationStandardDurations.WEB_SESSION_TOKEN_EXPIRATION_DURATION); Set<Role> roles = EnumSet.noneOf(Role.class); roles.add(Role.USER);/*from w ww. j av a 2 s .co m*/ roles.add(Role.ADMIN); when(handler.handle(new GetAccountRolesOperation(ACCOUNT_ID))) .thenReturn(new GetAccountRolesResponse(roles)); mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST).header(HttpCustomHeaders.AUTH_TOKEN_HEADER.getHeader(), authToken)).andExpect(status().isOk()).andExpect(content().bytes(new byte[0])); }
From source file:io.swagger.jaxrs.SynapseReader.java
private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, Set<String> parentConsumes, Set<String> parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) { Api api = (Api) cls.getAnnotation(Api.class); boolean isServiceAnnotated = (cls.getAnnotation(Service.class) != null); boolean isMarkedService = SynapseEndpointServiceMarker.class.isAssignableFrom(cls) && !cls.isInterface(); Map<String, Tag> tags = new HashMap<>(); List<SecurityRequirement> securities = new ArrayList<>(); final List<String> consumes = new ArrayList<>(); final List<String> produces = new ArrayList<>(); final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class); /*/*from www . ja v a2 s .c o m*/ * Only read @Api configuration if: * * @Api annotated AND * @Path annotated AND * @Api (hidden) false * isSubresource false * * OR * * @Api annotated AND * isSubresource true * @Api (hidden) false * */ final boolean readable = ((api != null && (isServiceAnnotated || isMarkedService) && !api.hidden() && !isSubresource) || (api != null && !api.hidden() && isSubresource) || (api != null && !api.hidden() && getConfig().isScanAllResources())); if (readable) { // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present Set<String> tagStrings = extractTags(api); tagStrings.stream().forEach((tagString) -> { Tag tag = new Tag().name(tagString); tags.put(tagString, tag); }); tags.keySet().stream().forEach((tagName) -> { getSwagger().tag(tags.get(tagName)); }); if (api != null && !api.produces().isEmpty()) { produces.add(api.produces()); // } else if (cls.getAnnotation(Produces.class) != null) { // produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value()); } if (api != null && !api.consumes().isEmpty()) { consumes.add(api.consumes()); // } else if (cls.getAnnotation(Consumes.class) != null) { // consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value()); } if (api != null) { globalSchemes.addAll(parseSchemes(api.protocols())); } Authorization[] authorizations = api != null ? api.authorizations() : new Authorization[] {}; for (Authorization auth : authorizations) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } } if (isSubresource) { if (parentTags != null) { tags.putAll(parentTags); } } if (readable || (api == null && getConfig().isScanAllResources())) { // merge consumes, produces // look for method-level annotated properties // handle sub-resources by looking at return type final List<Parameter> globalParameters = new ArrayList<>(); // look for constructor-level annotated properties globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, getSwagger())); // look for field-level annotated properties globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, getSwagger())); // parse the method final Service serviceAnnotation = ReflectionUtils.getAnnotation(cls, Service.class); for (Method method : cls.getMethods()) { if (ReflectionUtils.isOverriddenMethod(method, cls)) { //is this a method overriden by one in a subclass? continue; } final RequestMapping requestMappingAnnotation = isServiceAnnotated ? ReflectionUtils.getAnnotation(method, RequestMapping.class) : null; final List<String> operationPaths = isServiceAnnotated ? getPaths(serviceAnnotation, method, parentPath) : isMarkedService ? getPaths(method) : null; Map<String, String> regexMap = new HashMap<>(); if (operationPaths == null) { continue; } operationPaths.stream().map(op -> PathUtils.parsePath(op, regexMap)) .filter(op -> op != null && !MethodProcessor.isIgnored(op, getConfig())).forEach(op -> { final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); List<String> httpMethods = extractOperationMethods(apiOperation, method, SwaggerExtensions.chain()); if (httpMethods != null && !httpMethods.isEmpty()) { httpMethods.forEach(hm -> { Operation operation = null; if (apiOperation != null || getConfig().isScanAllResources() || (hm != null) || requestMappingAnnotation != null || isMarkedService) { operation = MethodProcessor.parseMethod(cls, method, globalParameters, getSwagger()); } if (operation != null) { if (parentParameters != null && !parentParameters.isEmpty()) { //add parent parameters to this Operation for (Parameter param : parentParameters) { operation.parameter(param); } } prepareOperation(operation, apiOperation, regexMap, globalSchemes); Set<String> apiConsumes = new HashSet<>(consumes); if (parentConsumes != null) { apiConsumes.addAll(parentConsumes); if (operation.getConsumes() != null) { apiConsumes.addAll(operation.getConsumes()); } } Set<String> apiProduces = new HashSet<>(produces); if (parentProduces != null) { apiProduces.addAll(parentProduces); if (operation.getProduces() != null) { apiProduces.addAll(operation.getProduces()); } } final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs( method); if (subResource != null && !scannedResources.contains(subResource)) { scannedResources.add(subResource); read(subResource, op, hm, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources); // remove the sub resource so that it can visit it later in another path // but we have a room for optimization in the future to reuse the scanned result // by caching the scanned resources in the reader instance to avoid actual scanning // the the resources again scannedResources.remove(subResource); } if (apiOperation != null) { boolean hasExplicitTag = false; for (String tag : apiOperation.tags()) { if (!"".equals(tag)) { operation.tag(tag); getSwagger().tag(new Tag().name(tag)); } } operation.getVendorExtensions().putAll( BaseReaderUtils.parseExtensions(apiOperation.extensions())); } if (operation.getConsumes() == null) { for (String mediaType : apiConsumes) { operation.consumes(mediaType); } } if (operation.getProduces() == null) { for (String mediaType : apiProduces) { operation.produces(mediaType); } } if (operation.getTags() == null) { for (String tagString : tags.keySet()) { operation.tag(tagString); } } // Only add global @Api securities if operation doesn't already have more specific securities if (operation.getSecurity() == null) { for (SecurityRequirement security : securities) { operation.security(security); } } Path path = getSwagger().getPath(op); if (path == null) { path = new Path(); getSwagger().path(op, path); } path.set(hm, operation); readImplicitParameters(method, operation); } }); } }); } } return getSwagger(); }
From source file:org.rhq.test.arquillian.impl.DataCleanupExecutor.java
private <T extends Enum<T>> EnumSet<T> toEnumSet(Class<T> c, T... values) { EnumSet<T> ret = EnumSet.noneOf(c); for (T e : values) { ret.add(e);// w w w. j a v a 2 s .c om } return ret; }