Example usage for java.util EnumSet allOf

List of usage examples for java.util EnumSet allOf

Introduction

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

Prototype

public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) 

Source Link

Document

Creates an enum set containing all of the elements in the specified element type.

Usage

From source file:org.waveprotocol.box.server.rpc.ServerRpcProvider.java

public void startWebSocketServer(final Injector injector) {
    httpServer = new Server();

    List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
    if (connectors.isEmpty()) {
        LOG.severe("No valid http end point address provided!");
    }//w ww .  j av a 2s  .co  m
    for (Connector connector : connectors) {
        httpServer.addConnector(connector);
    }
    final WebAppContext context = new WebAppContext();

    context.setParentLoaderPriority(true);

    if (jettySessionManager != null) {
        // This disables JSessionIDs in URLs redirects
        // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
        // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
        jettySessionManager.setSessionIdPathParameterName(null);

        context.getSessionHandler().setSessionManager(jettySessionManager);
    }
    final ResourceCollection resources = new ResourceCollection(resourceBases);
    context.setBaseResource(resources);

    addWebSocketServlets();

    try {

        final ServletModule servletModule = getServletModule();

        ServletContextListener contextListener = new GuiceServletContextListener() {

            private final Injector childInjector = injector.createChildInjector(servletModule);

            @Override
            protected Injector getInjector() {
                return childInjector;
            }
        };

        context.addEventListener(contextListener);
        context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
        context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
        httpServer.setHandler(context);

        httpServer.start();
        restoreSessions();

    } catch (Exception e) { // yes, .start() throws "Exception"
        LOG.severe("Fatal error starting http server.", e);
        return;
    }
    LOG.fine("WebSocket server running.");
}

From source file:de.schildbach.pte.AbstractHafasMobileProvider.java

private Location jsonTripSearchIdentify(final Location location) throws IOException {
    if (location.hasName()) {
        final List<Location> locations = jsonLocMatch(JOINER.join(location.place, location.name))
                .getLocations();/*from w  ww  .  j  ava2 s .c o m*/
        if (!locations.isEmpty())
            return locations.get(0);
    }
    if (location.hasLocation()) {
        final List<Location> locations = jsonLocGeoPos(EnumSet.allOf(LocationType.class), location.lat,
                location.lon).locations;
        if (!locations.isEmpty())
            return locations.get(0);
    }
    return null;
}

From source file:org.apache.hadoop.tools.distcp2.mapred.TestCopyMapper.java

@Test
public void testSkipCopyNoPerms() {
    try {//from   w  w  w  .  jav  a2  s.co m
        deleteState();
        createSourceData();

        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final StubContext stubContext = tmpUser.doAs(new PrivilegedAction<StubContext>() {
            @Override
            public StubContext run() {
                try {
                    return new StubContext(getConfiguration(), null, 0);
                } catch (Exception e) {
                    LOG.error("Exception encountered ", e);
                    throw new RuntimeException(e);
                }
            }
        });

        final Mapper<Text, FileStatus, Text, Text>.Context context = stubContext.getContext();
        EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class);

        context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS,
                DistCpUtils.packAttributes(preserveStatus));

        touchFile(SOURCE_PATH + "/src/file");
        touchFile(TARGET_PATH + "/src/file");
        cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file"),
                new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ));
        cluster.getFileSystem().setPermission(new Path(TARGET_PATH + "/src/file"),
                new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ));

        final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() {
            @Override
            public FileSystem run() {
                try {
                    return FileSystem.get(configuration);
                } catch (IOException e) {
                    LOG.error("Exception encountered ", e);
                    Assert.fail("Test failed: " + e.getMessage());
                    throw new RuntimeException("Test ought to fail here");
                }
            }
        });

        tmpUser.doAs(new PrivilegedAction<Integer>() {
            @Override
            public Integer run() {
                try {
                    copyMapper.setup(context);
                    copyMapper.map(new Text("/src/file"),
                            tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file")), context);
                    Assert.assertEquals(stubContext.getWriter().values().size(), 1);
                    Assert.assertTrue(stubContext.getWriter().values().get(0).toString().startsWith("SKIP"));
                    Assert.assertTrue(stubContext.getWriter().values().get(0).toString()
                            .contains(SOURCE_PATH + "/src/file"));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}

From source file:com.inmobi.conduit.distcp.tools.mapred.TestCopyMapper.java

@Test
public void testPreserve() {
    try {//from  w w w  .ja va 2s.  c o  m
        deleteState();
        createSourceData();

        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, FileStatus, NullWritable, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, FileStatus, NullWritable, Text>.Context>() {
                    @Override
                    public Mapper<Text, FileStatus, NullWritable, Text>.Context run() {
                        try {
                            StatusReporter reporter = new StubStatusReporter();
                            InMemoryWriter writer = new InMemoryWriter();
                            return getMapperContext(copyMapper, reporter, writer);
                        } catch (Exception e) {
                            LOG.error("Exception encountered ", e);
                            throw new RuntimeException(e);
                        }
                    }
                });

        EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class);

        context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS,
                DistCpUtils.packAttributes(preserveStatus));

        touchFile(SOURCE_PATH + "/src/file.gz");
        mkdirs(TARGET_PATH);
        cluster.getFileSystem().setPermission(new Path(TARGET_PATH), new FsPermission((short) 511));

        final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() {
            @Override
            public FileSystem run() {
                try {
                    return FileSystem.get(configuration);
                } catch (IOException e) {
                    LOG.error("Exception encountered ", e);
                    Assert.fail("Test failed: " + e.getMessage());
                    throw new RuntimeException("Test ought to fail here");
                }
            }
        });

        tmpUser.doAs(new PrivilegedAction<Integer>() {
            @Override
            public Integer run() {
                try {
                    copyMapper.setup(context);
                    copyMapper.map(new Text("/src/file.gz"),
                            tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file.gz")), context);
                    Assert.fail("Expected copy to fail");
                } catch (AccessControlException e) {
                    Assert.assertTrue("Got exception: " + e.getMessage(), true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java

/**
 * Returns all nodes in the cluster. If the states param is given, returns
 * all nodes that are in the comma-separated list of states.
 *///w ww . j a  va 2 s.  com
@GET
@Path("/nodes")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public NodesInfo getNodes(@QueryParam("states") String states) {
    init();
    ResourceScheduler sched = this.rm.getResourceScheduler();
    if (sched == null) {
        throw new NotFoundException("Null ResourceScheduler instance");
    }

    EnumSet<NodeState> acceptedStates;
    if (states == null) {
        acceptedStates = EnumSet.allOf(NodeState.class);
    } else {
        acceptedStates = EnumSet.noneOf(NodeState.class);
        for (String stateStr : states.split(",")) {
            acceptedStates.add(NodeState.valueOf(StringUtils.toUpperCase(stateStr)));
        }
    }

    Collection<RMNode> rmNodes = RMServerUtils.queryRMNodes(this.rm.getRMContext(), acceptedStates);
    NodesInfo nodesInfo = new NodesInfo();
    for (RMNode rmNode : rmNodes) {
        NodeInfo nodeInfo = new NodeInfo(rmNode, sched);
        if (EnumSet.of(NodeState.LOST, NodeState.DECOMMISSIONED, NodeState.REBOOTED)
                .contains(rmNode.getState())) {
            nodeInfo.setNodeHTTPAddress(EMPTY);
        }
        nodesInfo.add(nodeInfo);
    }

    return nodesInfo;
}

From source file:org.apache.ambari.server.controller.internal.AlertDefinitionResourceProvider.java

/**
 * Merges the map of properties into the specified entity. If the entity is
 * being created, an {@link IllegalArgumentException} is thrown when a
 * required property is absent. When updating, missing properties are assume
 * to not have changed.//from   ww w. jav  a2 s.  c om
 *
 * @param entity
 *          the entity to merge the properties into (not {@code null}).
 * @param requestMap
 *          the map of properties (not {@code null}).
 * @throws AmbariException
 */
private void populateEntity(AlertDefinitionEntity entity, Map<String, Object> requestMap)
        throws AmbariException {

    // some fields are required on creation; on update we keep what's there
    boolean bCreate = true;
    if (null != entity.getDefinitionId()) {
        bCreate = false;
    }

    String clusterName = (String) requestMap.get(ALERT_DEF_CLUSTER_NAME);
    String definitionName = (String) requestMap.get(ALERT_DEF_NAME);
    String serviceName = (String) requestMap.get(ALERT_DEF_SERVICE_NAME);
    String componentName = (String) requestMap.get(ALERT_DEF_COMPONENT_NAME);
    String type = (String) requestMap.get(ALERT_DEF_SOURCE_TYPE);
    String label = (String) requestMap.get(ALERT_DEF_LABEL);
    String description = (String) requestMap.get(ALERT_DEF_DESCRIPTION);
    String desiredScope = (String) requestMap.get(ALERT_DEF_SCOPE);

    Integer interval = null;
    if (requestMap.containsKey(ALERT_DEF_INTERVAL)) {
        interval = Integer.valueOf((String) requestMap.get(ALERT_DEF_INTERVAL));
    }

    Boolean enabled = null;
    if (requestMap.containsKey(ALERT_DEF_ENABLED)) {
        enabled = Boolean.parseBoolean((String) requestMap.get(ALERT_DEF_ENABLED));
    } else if (bCreate) {
        enabled = Boolean.TRUE;
    }

    Boolean ignoreHost = null;
    if (requestMap.containsKey(ALERT_DEF_IGNORE_HOST)) {
        ignoreHost = Boolean.parseBoolean((String) requestMap.get(ALERT_DEF_IGNORE_HOST));
    } else if (bCreate) {
        ignoreHost = Boolean.FALSE;
    }

    Scope scope = null;
    if (null != desiredScope && desiredScope.length() > 0) {
        scope = Scope.valueOf(desiredScope);
    }

    SourceType sourceType = null;
    if (null != type && type.length() > 0) {
        sourceType = SourceType.valueOf(type);
    }

    // if not specified when creating an alert definition, the scope is
    // assumed to be ANY
    if (null == scope && bCreate) {
        scope = Scope.ANY;
    }

    if (StringUtils.isEmpty(clusterName)) {
        throw new IllegalArgumentException("Invalid argument, cluster name is required");
    }

    if (bCreate && !requestMap.containsKey(ALERT_DEF_INTERVAL)) {
        throw new IllegalArgumentException("Check interval must be specified");
    }

    if (bCreate && StringUtils.isEmpty(definitionName)) {
        throw new IllegalArgumentException("Definition name must be specified");
    }

    if (bCreate && StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException("Service name must be specified");
    }

    // on creation, source type is required
    if (bCreate && null == sourceType) {
        throw new IllegalArgumentException(
                String.format("Source type must be specified and one of %s", EnumSet.allOf(SourceType.class)));
    }

    // !!! The AlertDefinition "Source" field is a nested JSON object;
    // build a JSON representation from the flat properties and then
    // serialize that JSON object as a string
    Map<String, JsonObject> jsonObjectMapping = new HashMap<String, JsonObject>();

    // for every property in the request, if it's a source property, then
    // add it to the JSON model
    for (Entry<String, Object> entry : requestMap.entrySet()) {
        String propertyKey = entry.getKey();

        // only handle "source" subproperties
        if (!propertyKey.startsWith(ALERT_DEF_SOURCE)) {
            continue;
        }

        // gets a JSON object to add the property to; this will create the
        // property and all of its parent properties recursively if necessary
        JsonObject jsonObject = getJsonObjectMapping(ALERT_DEF_SOURCE, jsonObjectMapping, propertyKey);

        String propertyName = PropertyHelper.getPropertyName(propertyKey);
        Object entryValue = entry.getValue();

        if (entryValue instanceof Collection<?>) {
            JsonElement jsonElement = gson.toJsonTree(entryValue);
            jsonObject.add(propertyName, jsonElement);
        } else {
            if (entryValue instanceof Number) {
                jsonObject.addProperty(propertyName, (Number) entryValue);
            } else {
                jsonObject.addProperty(propertyName, entryValue.toString());
            }
        }
    }

    // "source" must be filled in when creating
    JsonObject source = jsonObjectMapping.get(ALERT_DEF_SOURCE);
    if (bCreate && (null == source || 0 == source.entrySet().size())) {
        throw new IllegalArgumentException("Source must be specified");
    }

    Cluster cluster = getManagementController().getClusters().getCluster(clusterName);

    // at this point, we have either validated all required properties or
    // we are using the exiting entity properties where not defined, so we
    // can do simply null checks
    entity.setClusterId(Long.valueOf(cluster.getClusterId()));

    if (null != componentName) {
        entity.setComponentName(componentName);
    }

    if (null != definitionName) {
        entity.setDefinitionName(definitionName);
    }

    if (null != label) {
        entity.setLabel(label);
    }

    if (null != description) {
        entity.setDescription(description);
    }

    if (null != enabled) {
        entity.setEnabled(enabled.booleanValue());
    }

    if (null != ignoreHost) {
        entity.setHostIgnored(ignoreHost.booleanValue());
    }

    if (null != interval) {
        entity.setScheduleInterval(interval);
    }

    if (null != serviceName) {
        entity.setServiceName(serviceName);
    }

    if (null != sourceType) {
        entity.setSourceType(sourceType);
    }

    if (null != source) {
        entity.setSource(source.toString());
    }

    if (null != scope) {
        entity.setScope(scope);
    }

    entity.setHash(UUID.randomUUID().toString());
}

From source file:org.silverpeas.core.notification.user.delayed.DelayedNotificationManagerIT.java

private Set<NotifChannel> getAimedChannelsAll() {
    return EnumSet.allOf(NotifChannel.class);
}

From source file:com.sap.bi.da.extension.jsonextension.JSONExtension.java

@Override
public Set<DAEWorkflow> getEnabledWorkflows(IDAEAcquisitionState acquisitionState) {
    // If the extension is incompatible with the current environment, it may disable itself using this function
    // return EnumSet.allOf(DAEWorkflow.class) to enable the extension
    // return EnumSet.noneOf(DAEWorkflow.class) to disable the extension
    // Partial enabling is not currently supported
    return EnumSet.allOf(DAEWorkflow.class);
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.BorgBlockReader.java

@Override
public void readAll() {
    ArrayList<ColumnStructure> colstruct = new ArrayList<ColumnStructure>();
    colstruct.add(ColumnStructure.VC);//from   w w  w .ja va2s.  co  m
    colstruct.add(ColumnStructure.TS);
    colstruct.add(ColumnStructure.FL);
    for (RncAp r : EnumSet.allOf(RncAp.class)) {
        for (AppProc a : EnumSet.allOf(AppProc.class)) {
            ArrayList<ArrayList<String>> mapmap = new ArrayList<ArrayList<String>>();
            try {
                URL borg = new URL(BORG + r.getFile(a));
                URLConnection conn = borg.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                CSVParser parser = new CSVParser(in, strategy);
                //if header
                String[] header = parser.getLine();
                //and body
                String[] line = null;

                while ((line = parser.getLine()) != null) {

                    Calendar cal = Calendar.getInstance();
                    cal.setTime(BORG_DF.parse(line[0]));
                    String datestr = ALUDBUtilities.ALUDB_DF.format(cal.getTime());
                    //System.out.println(r.toString()+"/"+a.toString()+"//"+line[0]+"///"+datestr);
                    for (int i = 2; i < line.length; i++) {
                        ArrayList<String> map = new ArrayList<String>();
                        map.add(0, idConvert(r.toString(), a.toString(), header[i]));
                        map.add(1, datestr);
                        map.add(2, line[i]);
                        mapmap.add(map);
                    }

                }
                in.close();
            } catch (MalformedURLException mrue) {
                System.err.println("Borg Path incorrect " + mrue);
            } catch (IOException ioe) {
                System.err.println("Cannot read Borg file " + ioe);
            } catch (ParseException pe) {
                System.err.println("Cannot parse Date field " + pe);
            }

            ALUDBUtilities.insert(databasetype, TABLE, colstruct, mapmap);

        }
    }

}

From source file:org.photovault.imginfo.PhotoInfo.java

/**
 Returns an existing thumbnail for this photo but do not try to construct a 
 new one if there is no thumbnail already created.
 @return Thumbnail for this photo or null if none is found.
 *//*from  w ww .  j a  v  a  2s  . co m*/
@Transient
public Thumbnail getExistingThumbnail() {
    if (thumbnail == null) {
        log.debug("Finding thumbnail from database");
        ImageDescriptorBase img = getPreferredImage(EnumSet.allOf(ImageOperations.class),
                EnumSet.allOf(ImageOperations.class), 0, 0, 200, 200);
        if (img != null) {
            log.debug("Found thumbnail from database");
            // TODO: This must take also locator.
            thumbnail = Thumbnail.createThumbnail(this, img.getFile().findAvailableCopy());
            oldThumbnail = null;
        }
    }
    return thumbnail;
}