Example usage for java.util EnumSet copyOf

List of usage examples for java.util EnumSet copyOf

Introduction

In this page you can find the example usage for java.util EnumSet copyOf.

Prototype

public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) 

Source Link

Document

Creates an enum set initialized from the specified collection.

Usage

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateBuilderHelper.java

public X509CertificateBuilderHelper withInheritedResourceTypes(EnumSet<IpResourceType> resourceTypes) {
    this.inheritedResourceTypes = EnumSet.copyOf(resourceTypes);
    return this;
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {/* w  w  w  .jav a  2 s .c  o m*/
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.pentaho.platform.plugin.services.importexport.exportManifest.ExportManifestEntity.java

/**
 * Helper method for importing. Returns a FileRepositoryAcl object for the the ExportManifestEntity. Will return null
 * if there is no EntityAcl present.//from  w  ww.ja  v a2  s . c  om
 *
 * @return RepositoryFile
 */
public RepositoryFileAcl getRepositoryFileAcl() throws ExportManifestFormatException {
    RepositoryFileAcl repositoryFileAcl;
    EntityAcl entityAcl = getEntityAcl();
    if (entityAcl == null) {
        return null;
    }

    ArrayList<RepositoryFileAce> repositoryFileAces = new ArrayList<RepositoryFileAce>();
    RepositoryFileSid rfs;
    for (EntityAcl.Aces ace : entityAcl.getAces()) {
        rfs = getSid(ace.getRecipient(), ace.getRecipientType());
        HashSet<RepositoryFilePermission> permissionSet = new HashSet<RepositoryFilePermission>();
        for (String permission : ace.getPermissions()) {
            permissionSet.add(getPermission(permission));
        }
        RepositoryFileAce repositoryFileAce = new RepositoryFileAce(rfs, EnumSet.copyOf(permissionSet));
        repositoryFileAces.add(repositoryFileAce);
    }

    repositoryFileAcl = new RepositoryFileAcl("", getSid(entityAcl.getOwner(), entityAcl.getOwnerType()),
            entityAcl.isEntriesInheriting(), repositoryFileAces);

    return repositoryFileAcl;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tcf.TcfWriter.java

/**
 * Merge annotations from CAS into an existing TCF file.
 *
 * @param aIs//  w ww  .java  2  s  .  c om
 *            the TCF file with an existing annotation layers
 * @param aJCas
 *            an annotated CAS object
 * @param aOs
 *            the output stream.
 * @throws WLFormatException
 *             if a TCF problem occurs.
 */
public void casToTcfWriter(InputStream aIs, JCas aJCas, OutputStream aOs) throws WLFormatException {
    // If these layers are present in the TCF file, we use them from there, otherwise
    // we generate them
    EnumSet<TextCorpusLayerTag> layersToRead = EnumSet.of(TextCorpusLayerTag.TOKENS,
            TextCorpusLayerTag.SENTENCES);

    // If we have annotations for these layers in the CAS, we rewrite those layers. 
    List<TextCorpusLayerTag> layersToReplace = new ArrayList<TextCorpusLayerTag>();
    if (exists(aJCas, POS.class) || !preserveIfEmpty) {
        layersToReplace.add(TextCorpusLayerTag.POSTAGS);
    }
    if (exists(aJCas, Lemma.class) || !preserveIfEmpty) {
        layersToReplace.add(TextCorpusLayerTag.LEMMAS);
    }
    if (exists(aJCas, NamedEntity.class) || !preserveIfEmpty) {
        layersToReplace.add(TextCorpusLayerTag.NAMED_ENTITIES);
    }
    if (exists(aJCas, Dependency.class) || !preserveIfEmpty) {
        layersToReplace.add(TextCorpusLayerTag.PARSING_DEPENDENCY);
    }
    if (exists(aJCas, CoreferenceChain.class) || !preserveIfEmpty) {
        layersToReplace.add(TextCorpusLayerTag.REFERENCES);
    }

    TextCorpusStreamedWithReplaceableLayers textCorpus = null;
    try {
        textCorpus = new TextCorpusStreamedWithReplaceableLayers(aIs, layersToRead,
                EnumSet.copyOf(layersToReplace), aOs);

        write(aJCas, textCorpus);
    } finally {
        if (textCorpus != null) {
            try {
                textCorpus.close();
            } catch (IOException e) {
                // Ignore exception while closing
            }
        }
    }
}

From source file:forge.game.replacement.ReplacementHandler.java

/**
 * /*  ww w  .  j  a  va2  s.c  om*/
 * Creates an instance of the proper replacement effect object based on a
 * parsed script.
 * 
 * @param mapParams
 *            The parsed script
 * @param host
 *            The card that hosts the replacement effect
 * @return The finished instance
 */
private static ReplacementEffect parseReplacement(final Map<String, String> mapParams, final Card host,
        final boolean intrinsic) {
    final ReplacementType rt = ReplacementType.smartValueOf(mapParams.get("Event"));
    ReplacementEffect ret = rt.createReplacement(mapParams, host, intrinsic);

    String activeZones = mapParams.get("ActiveZones");
    if (null != activeZones) {
        ret.setActiveZone(EnumSet.copyOf(ZoneType.listValueOf(activeZones)));
    }

    return ret;
}

From source file:fr.ritaly.dungeonmaster.champion.Party.java

/**
 * Tries adding the given champion to the party and if the operation
 * succeeded returns the location where the champion was added.
 *
 * @param champion//from  w  ww .  j a va 2s .c o m
 *            the champion to add to the party. Can't be null.
 * @return a location representing where the champion was successfully
 *         added.
 */
public Location addChampion(Champion champion) {
    Validate.notNull(champion, "The given champion is null");
    Validate.isTrue(!champions.containsValue(champion), "The given champion has already joined the party");
    if (isFull()) {
        throw new IllegalStateException("The party is already full");
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("%s is joigning the party ...", champion.getName()));
    }

    final boolean wasEmpty = isEmpty(true);

    // Which locations are already occupied ?
    final EnumSet<Location> occupied;

    if (champions.isEmpty()) {
        occupied = EnumSet.noneOf(Location.class);
    } else {
        occupied = EnumSet.copyOf(champions.keySet());
    }

    // Free locations ?
    final EnumSet<Location> free = EnumSet.complementOf(occupied);

    if (log.isDebugEnabled()) {
        log.debug("Free locations = " + free);
    }

    // Get the first free location
    final Location location = free.iterator().next();

    champions.put(location, champion);

    // Listen to the events fired by the champion
    champion.addChangeListener(this);

    if (log.isDebugEnabled()) {
        log.debug(String.format("%s.Location: %s", champion.getName(), location));
    }

    // Assign a color to this champion
    final Color color = pickColor();

    if (log.isDebugEnabled()) {
        log.debug(String.format("%s.Color: %s", champion.getName(), color));
    }

    champion.setColor(color);
    champion.setParty(this);

    if (wasEmpty) {
        // This champion become the new leader
        setLeader(champion);
    }

    fireChangeEvent();

    if (log.isInfoEnabled()) {
        log.info(String.format("%s joined the party", champion.getName()));
    }

    return location;
}

From source file:org.trnltk.morphology.lexicon.ImmutableRootGenerator.java

private HashSet<ImmutableRoot> handleSpecialRoots(final Lexeme originalLexeme) {
    String changedRootStr = rootChanges.get(Pair.of(originalLexeme.getLemma(), originalLexeme.getPrimaryPos()));
    if (StringUtils.isBlank(changedRootStr))
        changedRootStr = rootChanges.get(Pair.of(originalLexeme.getLemma(), (PrimaryPos) null));

    Validate.notNull(changedRootStr, "Unhandled root change : " + originalLexeme);

    final Set<LexemeAttribute> attributes = originalLexeme.getAttributes();
    final EnumSet<LexemeAttribute> newAttributes = EnumSet.copyOf(attributes);
    newAttributes.remove(LexemeAttribute.Special);
    final Lexeme modifiedLexeme = new ImmutableLexeme(originalLexeme.getLemma(), originalLexeme.getLemmaRoot(),
            originalLexeme.getPrimaryPos(), originalLexeme.getSecondaryPos(),
            Sets.immutableEnumSet(newAttributes));

    final String unchangedRootStr = originalLexeme.getLemmaRoot();

    final ImmutableRoot rootUnchanged = new ImmutableRoot(unchangedRootStr, modifiedLexeme,
            Sets.immutableEnumSet(phoneticsAnalyzer.calculatePhoneticAttributes(unchangedRootStr,
                    modifiedLexeme.getAttributes())),
            null);//from  w  w w . j av a  2s. c  o  m

    final ImmutableRoot rootChanged = new ImmutableRoot(changedRootStr, modifiedLexeme, Sets.immutableEnumSet(
            phoneticsAnalyzer.calculatePhoneticAttributes(changedRootStr, modifiedLexeme.getAttributes())),
            null);

    return Sets.newHashSet(rootUnchanged, rootChanged);

}

From source file:gov.nih.nci.firebird.selenium2.tests.protocol.registration.ReviseReturnedRegistrationFormsTest.java

private void checkFormsAreRevised(FormTypeEnum... forms) {
    dataSet.reload();//from   ww  w. j  av a 2s .c o m
    registration = dataSet.getInvestigatorRegistration();
    EnumSet<FormTypeEnum> revisedFormTypes;
    if (forms.length == 0) {
        revisedFormTypes = EnumSet.noneOf(FormTypeEnum.class);
    } else {
        revisedFormTypes = EnumSet.copyOf(Arrays.asList(forms));
    }
    checkFormsRevised(revisedFormTypes);
    EnumSet<FormTypeEnum> notRevisedFormTypes = EnumSet.complementOf(revisedFormTypes);
    checkFormsNotRevised(notRevisedFormTypes);
}

From source file:org.brekka.pegasus.core.services.impl.TemplateServiceImpl.java

@Override
public Set<TemplateEngine> getAvailableEngines() {
    Set<TemplateEngine> engines = EnumSet.copyOf(this.adapters.keySet());
    return engines;
}

From source file:ws.wamp.jawampa.WampClient.java

/**
 * Registers a procedure at the router which will afterwards be available
 * for remote procedure calls from other clients.<br>
 * The actual registration will only happen after the user subscribes on
 * the returned Observable. This guarantees that no RPC requests get lost.
 * Incoming RPC requests will be pushed to the Subscriber via it's
 * onNext method. The Subscriber can send responses through the methods on
 * the {@link Request}.<br>//from  w  w w .j  a  v  a  2  s.  co m
 * If the client no longer wants to provide the method it can call
 * unsubscribe() on the Subscription to unregister the procedure.<br>
 * If the connection closes onCompleted will be called.<br>
 * In case of errors during subscription onError will be called.
 * @param topic The name of the procedure which this client wants to
 * provide.<br>
 * Must be valid WAMP URI.
 * @param flags procedure flags
 * @return An observable that can be used to provide a procedure.
 */
public Observable<Request> registerProcedure(final String topic, final RegisterFlags... flags) {
    return this.registerProcedure(topic, EnumSet.copyOf(Arrays.asList(flags)));
}