List of usage examples for java.util EnumSet allOf
public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)
From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.LeveldbTimelineStore.java
/** * Read entity from a db iterator. If no information is found in the * specified fields for this entity, return null. *///from w ww . ja va 2s.com private static TimelineEntity getEntity(String entityId, String entityType, Long startTime, EnumSet<Field> fields, DBIterator iterator, byte[] prefix, int prefixlen) throws IOException { if (fields == null) { fields = EnumSet.allOf(Field.class); } TimelineEntity entity = new TimelineEntity(); boolean events = false; boolean lastEvent = false; if (fields.contains(Field.EVENTS)) { events = true; } else if (fields.contains(Field.LAST_EVENT_ONLY)) { lastEvent = true; } else { entity.setEvents(null); } boolean relatedEntities = false; if (fields.contains(Field.RELATED_ENTITIES)) { relatedEntities = true; } else { entity.setRelatedEntities(null); } boolean primaryFilters = false; if (fields.contains(Field.PRIMARY_FILTERS)) { primaryFilters = true; } else { entity.setPrimaryFilters(null); } boolean otherInfo = false; if (fields.contains(Field.OTHER_INFO)) { otherInfo = true; } else { entity.setOtherInfo(null); } // iterate through the entity's entry, parsing information if it is part // of a requested field for (; iterator.hasNext(); iterator.next()) { byte[] key = iterator.peekNext().getKey(); if (!prefixMatches(prefix, prefixlen, key)) { break; } if (key.length == prefixlen) { continue; } if (key[prefixlen] == PRIMARY_FILTERS_COLUMN[0]) { if (primaryFilters) { addPrimaryFilter(entity, key, prefixlen + PRIMARY_FILTERS_COLUMN.length); } } else if (key[prefixlen] == OTHER_INFO_COLUMN[0]) { if (otherInfo) { entity.addOtherInfo(parseRemainingKey(key, prefixlen + OTHER_INFO_COLUMN.length), GenericObjectMapper.read(iterator.peekNext().getValue())); } } else if (key[prefixlen] == RELATED_ENTITIES_COLUMN[0]) { if (relatedEntities) { addRelatedEntity(entity, key, prefixlen + RELATED_ENTITIES_COLUMN.length); } } else if (key[prefixlen] == EVENTS_COLUMN[0]) { if (events || (lastEvent && entity.getEvents().size() == 0)) { TimelineEvent event = getEntityEvent(null, key, prefixlen + EVENTS_COLUMN.length, iterator.peekNext().getValue()); if (event != null) { entity.addEvent(event); } } } else { if (key[prefixlen] != INVISIBLE_REVERSE_RELATED_ENTITIES_COLUMN[0]) { LOG.warn(String.format("Found unexpected column for entity %s of " + "type %s (0x%02x)", entityId, entityType, key[prefixlen])); } } } entity.setEntityId(entityId); entity.setEntityType(entityType); entity.setStartTime(startTime); return entity; }
From source file:net.ripe.rpki.commons.validation.X509ResourceCertificateBottomUpValidatorTest.java
private X509ResourceCertificateBuilder createChildBuilder() { X509ResourceCertificateBuilder builder = new X509ResourceCertificateBuilder(); builder.withSubjectDN(FIRST_CHILD_CERTIFICATE_NAME); builder.withIssuerDN(ROOT_CERTIFICATE_NAME); builder.withSerial(FIRST_CHILD_SERIAL_NUMBER); builder.withPublicKey(FIRST_CHILD_KEY_PAIR.getPublic()); builder.withAuthorityKeyIdentifier(true); builder.withSigningKeyPair(ROOT_KEY_PAIR); builder.withCa(true);/*from www.j av a 2s .c o m*/ builder.withKeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign); builder.withAuthorityKeyIdentifier(true); builder.withSubjectKeyIdentifier(true); builder.withInheritedResourceTypes(EnumSet.allOf(IpResourceType.class)); builder.withValidityPeriod(VALIDITY_PERIOD); builder.withCrlDistributionPoints(new URI[] { URI.create("rsync://localhost/ta.crl") }); return builder; }
From source file:org.apache.ambari.server.controller.internal.AlertTargetResourceProvider.java
/** * Updates existing {@link AlertTargetEntity}s with the specified properties. * * @param requestMaps/*from w ww. j ava 2 s . c o m*/ * a set of property maps, one map for each entity. * @throws AmbariException * if the entity could not be found. */ @SuppressWarnings("unchecked") private void updateAlertTargets(long alertTargetId, Map<String, Object> requestMap) throws AmbariException { AlertTargetEntity entity = s_dao.findTargetById(alertTargetId); if (null == entity) { String message = MessageFormat.format("The alert target with ID {0} could not be found", alertTargetId); throw new AmbariException(message); } String name = (String) requestMap.get(ALERT_TARGET_NAME); String description = (String) requestMap.get(ALERT_TARGET_DESCRIPTION); String notificationType = (String) requestMap.get(ALERT_TARGET_NOTIFICATION_TYPE); Collection<String> alertStates = (Collection<String>) requestMap.get(ALERT_TARGET_STATES); Collection<Long> groupIds = (Collection<Long>) requestMap.get(ALERT_TARGET_GROUPS); if (!StringUtils.isBlank(name)) { entity.setTargetName(name); } if (null != description) { entity.setDescription(description); } if (!StringUtils.isBlank(notificationType)) { entity.setNotificationType(notificationType); } String properties = s_gson.toJson(extractProperties(requestMap)); if (!StringUtils.isEmpty(properties)) { entity.setProperties(properties); } // a null alert state implies that the key was not set and no update // should occur for this field, while an empty list implies all alert // states should be set if (null != alertStates) { final Set<AlertState> alertStateSet; if (alertStates.isEmpty()) { alertStateSet = EnumSet.allOf(AlertState.class); } else { alertStateSet = new HashSet<AlertState>(alertStates.size()); for (String state : alertStates) { alertStateSet.add(AlertState.valueOf(state)); } } entity.setAlertStates(alertStateSet); } // if groups were supplied, replace existing if (null != groupIds) { Set<AlertGroupEntity> groups = new HashSet<AlertGroupEntity>(); List<Long> ids = new ArrayList<Long>(groupIds); if (ids.size() > 0) { groups.addAll(s_dao.findGroupsById(ids)); } entity.setAlertGroups(groups); } s_dao.merge(entity); }
From source file:io.mpos.ui.tester.CheckoutActivity.java
void initMockPaymentController() { MposUi mposUi = MposUi.initialize(this, ProviderMode.MOCK, "mock", "mock"); AccessoryParameters mockAccessoryParameters = new AccessoryParameters.Builder(AccessoryFamily.MOCK).mocked() .build();/* ww w . ja va2 s . co m*/ mposUi.getConfiguration().setTerminalParameters(mockAccessoryParameters); MposUi.getInitializedInstance().getConfiguration().setPrinterParameters(mockAccessoryParameters); mposUi.getConfiguration().setSummaryFeatures(EnumSet.allOf(MposUiConfiguration.SummaryFeature.class)); }
From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java
/** * Reads properties as a Theme object/*from w ww .jav a2 s . c o m*/ */ private Theme fromProperties(final Properties properties) { final Theme theme = new Theme(); theme.setTitle(StringUtils.trimToNull(properties.getProperty("title"))); theme.setAuthor(StringUtils.trimToNull(properties.getProperty("author"))); theme.setVersion(StringUtils.trimToNull(properties.getProperty("version"))); theme.setDescription(StringUtils.trimToNull(properties.getProperty("description"))); final String styles = StringUtils.trimToNull(properties.getProperty("styles")); if (styles == null) { // None found - Assume all styles theme.setStyles(EnumSet.allOf(Style.class)); } else { final String[] array = StringUtils.split(styles, ','); theme.setStyles(CoercionHelper.coerceCollection(Theme.Style.class, array)); } return theme; }
From source file:com.addthis.hydra.task.output.tree.TreeMapper.java
private void _init(TaskRunConfig runConfig) throws Exception { config = runConfig;/*from ww w .j ava2s .c om*/ mapstats = new TreeMapperStats(log); resolve(); if (nodeCache != null) TreeCommonParameters.setDefaultCleanQueueSize(nodeCache); if (trashInterval != null) TreeCommonParameters.setDefaultTrashInterval(trashInterval); if (trashTimeLimit != null) TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit); if (storage != null) { if (storage.maxCacheSize != null) TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize); if (storage.maxCacheMem != null) TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem); if (storage.maxPageSize != null) TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize); if (storage.maxPageMem != null) TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem); if (storage.memSample != null) TreeCommonParameters.setDefaultMemSample(storage.memSample); } if (Strings.isEmpty(localhost)) { localhost = InetAddress.getLocalHost().getHostAddress(); } log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http=" + enableHttp + " jmx=" + enableJmx + " live=" + live); log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId); Path treePath = Paths.get(runConfig.dir, "data"); tree = new ConcurrentTree(Files.initDirectory(treePath.toFile())); bench = new Bench(EnumSet.allOf(BENCH.class), 1000); if (enableHttp) { jetty = new Server(port > 0 ? port++ : 0); jetty.start(); int httpPort = jetty.getConnectors()[0].getLocalPort(); log.info("[init.http] http://" + localhost + ":" + httpPort + "/"); Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false); } if (enableJmx) { int queryPort = 0; jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort); ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname); ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(port > 0 ? new InetSocketAddress(port++) : null); int jmxport = ss.getLocalPort(); ss.close(); if (jmxport == -1) { log.warn("[init.jmx] failed to get a port"); } else { try { jmxremote = new MBeanRemotingSupport(jmxport); jmxremote.start(); log.info("[init.jmx] port=" + jmxport); } catch (Exception e) { log.warn("[init.jmx] err=" + e); } } } if (config.jobId != null && live && livePort > -1) { QueryEngine liveQueryEngine = new QueryEngine(tree); connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine); } startTime = System.currentTimeMillis(); if (pre != null) { log.warn("pre-chain: " + pre); processBundle(new KVBundle(), pre); } }
From source file:org.whispersystems.textsecuregcm.WhisperServerService.java
@Override public void run(WhisperServerConfiguration config, Environment environment) throws Exception { SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics()); environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); environment.getObjectMapper().setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); environment.getObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); DBIFactory dbiFactory = new DBIFactory(); DBI database = dbiFactory.build(environment, config.getDataSourceFactory(), "accountdb"); DBI messagedb = dbiFactory.build(environment, config.getMessageStoreConfiguration(), "messagedb"); Accounts accounts = database.onDemand(Accounts.class); PendingAccounts pendingAccounts = database.onDemand(PendingAccounts.class); PendingDevices pendingDevices = database.onDemand(PendingDevices.class); Keys keys = database.onDemand(Keys.class); Messages messages = messagedb.onDemand(Messages.class); RedisClientFactory cacheClientFactory = new RedisClientFactory(config.getCacheConfiguration().getUrl()); JedisPool cacheClient = cacheClientFactory.getRedisClientPool(); JedisPool directoryClient = new RedisClientFactory(config.getDirectoryConfiguration().getUrl()) .getRedisClientPool();//w ww . jav a2 s . co m Client httpClient = initializeHttpClient(environment, config); DirectoryManager directory = new DirectoryManager(directoryClient); PendingAccountsManager pendingAccountsManager = new PendingAccountsManager(pendingAccounts, cacheClient); PendingDevicesManager pendingDevicesManager = new PendingDevicesManager(pendingDevices, cacheClient); AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheClient); FederatedClientManager federatedClientManager = new FederatedClientManager(environment, config.getJerseyClientConfiguration(), config.getFederationConfiguration()); MessagesManager messagesManager = new MessagesManager(messages); DeadLetterHandler deadLetterHandler = new DeadLetterHandler(messagesManager); DispatchManager dispatchManager = new DispatchManager(cacheClientFactory, Optional.<DispatchChannel>of(deadLetterHandler)); PubSubManager pubSubManager = new PubSubManager(cacheClient, dispatchManager); PushServiceClient pushServiceClient = new PushServiceClient(httpClient, config.getPushConfiguration()); WebsocketSender websocketSender = new WebsocketSender(messagesManager, pubSubManager); AccountAuthenticator deviceAuthenticator = new AccountAuthenticator(accountsManager); FederatedPeerAuthenticator federatedPeerAuthenticator = new FederatedPeerAuthenticator( config.getFederationConfiguration()); RateLimiters rateLimiters = new RateLimiters(config.getLimitsConfiguration(), cacheClient); ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushServiceClient, pubSubManager); TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration()); SmsSender smsSender = new SmsSender(twilioSmsSender); UrlSigner urlSigner = new UrlSigner(config.getS3Configuration()); PushSender pushSender = new PushSender(apnFallbackManager, pushServiceClient, websocketSender, config.getPushConfiguration().getQueueSize()); ReceiptSender receiptSender = new ReceiptSender(accountsManager, pushSender, federatedClientManager); FeedbackHandler feedbackHandler = new FeedbackHandler(pushServiceClient, accountsManager); TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration()); Optional<byte[]> authorizationKey = config.getRedphoneConfiguration().getAuthorizationKey(); environment.lifecycle().manage(apnFallbackManager); environment.lifecycle().manage(pubSubManager); environment.lifecycle().manage(feedbackHandler); environment.lifecycle().manage(pushSender); AttachmentController attachmentController = new AttachmentController(rateLimiters, federatedClientManager, urlSigner); KeysControllerV1 keysControllerV1 = new KeysControllerV1(rateLimiters, keys, accountsManager, federatedClientManager); KeysControllerV2 keysControllerV2 = new KeysControllerV2(rateLimiters, keys, accountsManager, federatedClientManager); MessageController messageController = new MessageController(rateLimiters, pushSender, receiptSender, accountsManager, messagesManager, federatedClientManager); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Account>().setAuthenticator(deviceAuthenticator) .setPrincipal(Account.class).buildAuthFilter(), new BasicCredentialAuthFilter.Builder<FederatedPeer>().setAuthenticator(federatedPeerAuthenticator) .setPrincipal(FederatedPeer.class).buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder()); environment.jersey() .register(new AccountController(pendingAccountsManager, accountsManager, rateLimiters, smsSender, messagesManager, new TimeProvider(), authorizationKey, turnTokenGenerator, config.getTestDevices())); environment.jersey().register( new DeviceController(pendingDevicesManager, accountsManager, messagesManager, rateLimiters)); environment.jersey().register(new DirectoryController(rateLimiters, directory)); environment.jersey().register(new FederationControllerV1(accountsManager, attachmentController, messageController, keysControllerV1)); environment.jersey().register(new FederationControllerV2(accountsManager, attachmentController, messageController, keysControllerV2)); environment.jersey().register(new ReceiptController(receiptSender)); environment.jersey().register(new ProvisioningController(rateLimiters, pushSender)); environment.jersey().register(attachmentController); environment.jersey().register(keysControllerV1); environment.jersey().register(keysControllerV2); environment.jersey().register(messageController); if (config.getWebsocketConfiguration().isEnabled()) { WebSocketEnvironment webSocketEnvironment = new WebSocketEnvironment(environment, config, 90000); webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(deviceAuthenticator)); webSocketEnvironment.setConnectListener(new AuthenticatedConnectListener(accountsManager, pushSender, receiptSender, messagesManager, pubSubManager)); webSocketEnvironment.jersey().register(new KeepAliveController(pubSubManager)); webSocketEnvironment.jersey().register(messageController); WebSocketEnvironment provisioningEnvironment = new WebSocketEnvironment(environment, config); provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(pubSubManager)); provisioningEnvironment.jersey().register(new KeepAliveController(pubSubManager)); WebSocketResourceProviderFactory webSocketServlet = new WebSocketResourceProviderFactory( webSocketEnvironment); WebSocketResourceProviderFactory provisioningServlet = new WebSocketResourceProviderFactory( provisioningEnvironment); ServletRegistration.Dynamic websocket = environment.servlets().addServlet("WebSocket", webSocketServlet); ServletRegistration.Dynamic provisioning = environment.servlets().addServlet("Provisioning", provisioningServlet); websocket.addMapping("/v1/websocket/"); websocket.setAsyncSupported(true); provisioning.addMapping("/v1/websocket/provisioning/"); provisioning.setAsyncSupported(true); webSocketServlet.start(); provisioningServlet.start(); FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); filter.setInitParameter("allowedOrigins", "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,X-Signal-Agent"); filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter("preflightMaxAge", "5184000"); filter.setInitParameter("allowCredentials", "true"); } environment.healthChecks().register("directory", new RedisHealthCheck(directoryClient)); environment.healthChecks().register("cache", new RedisHealthCheck(cacheClient)); environment.jersey().register(new IOExceptionMapper()); environment.jersey().register(new RateLimitExceededExceptionMapper()); environment.jersey().register(new InvalidWebsocketAddressExceptionMapper()); environment.jersey().register(new DeviceLimitExceededExceptionMapper()); environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge()); environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge()); environment.metrics().register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge()); environment.metrics().register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge()); environment.metrics().register(name(FileDescriptorGauge.class, "fd_count"), new FileDescriptorGauge()); }
From source file:com.cisco.oss.foundation.http.server.jetty.JettyHttpServerFactory.java
/** * @param serviceName - the http logical service name * @param servlets - a mapping between servlet path and servlet instance. This mapping uses the google collections {@link com.google.common.collect.ListMultimap}. * <br>Example of usage: * {@code ArrayListMultimap<String,Servlet> servletMap = ArrayListMultimap.create()} * @param filters - a mapping between filter path and filter instance. This mapping uses the google collections {@link com.google.common.collect.ListMultimap}. * <br>Example of usage: * {@code ArrayListMultimap<String,Filter> filterMap = ArrayListMultimap.create()} * @param eventListeners event listeners to be applied on this server * @param keyStorePath - a path to the keystore file * @param keyStorePassword - the keystore password * @param trustStorePath - the trust store file path * @param trustStorePassword - the trust store password *//*w w w . ja v a 2 s . c o m*/ @Override public void startHttpServer(String serviceName, ListMultimap<String, Servlet> servlets, ListMultimap<String, Filter> filters, List<EventListener> eventListeners, Map<String, String> initParams, String keyStorePath, String keyStorePassword, String trustStorePath, String trustStorePassword) { if (servers.get(serviceName) != null) { throw new UnsupportedOperationException( "you must first stop stop server: " + serviceName + " before you want to start it again!"); } Configuration configuration = ConfigurationFactory.getConfiguration(); boolean sessionManagerEnabled = configuration.getBoolean(serviceName + ".http.sessionManagerEnabled", false); ContextHandlerCollection handler = new ContextHandlerCollection(); JettyHttpThreadPool jettyHttpThreadPool = new JettyHttpThreadPool(serviceName); Map<String, Map<String, String>> servletMapping = ConfigUtil .parseComplexArrayStructure(serviceName + ".http.servletsMapping"); Map<String, ServletContextHandler> contextMap = new HashMap<>(); int servletNum = -1; for (Map.Entry<String, Servlet> entry : servlets.entries()) { servletNum++; ServletContextHandler context = new ServletContextHandler(); if (sessionManagerEnabled) { context = new ServletContextHandler(ServletContextHandler.SESSIONS); } String uri = entry.getKey(); if (servletMapping != null && !servletMapping.isEmpty()) { contextMap.put(uri, context); } context.setContextPath(configuration.getString(serviceName + ".http.servletContextPath", "/")); if (eventListeners != null && !eventListeners.isEmpty()) { if (servletMapping != null && !servletMapping.isEmpty() && eventListeners.size() == servlets.size()) { context.setEventListeners(new EventListener[] { eventListeners.get(servletNum) }); } else { context.setEventListeners(eventListeners.toArray(new EventListener[0])); } for (EventListener eventListener : JettyHttpServerFactory.eventListeners) { context.addEventListener(eventListener); } } context.addServlet(new ServletHolder(entry.getValue()), uri); for (Map.Entry<String, String> initParam : initParams.entrySet()) { context.setInitParameter(initParam.getKey(), initParam.getValue()); } HttpServerUtil.addFiltersToServletContextHandler(serviceName, jettyHttpThreadPool, context); for (Map.Entry<String, Filter> filterEntry : filters.entries()) { context.addFilter(new FilterHolder(filterEntry.getValue()), filterEntry.getKey(), EnumSet.allOf(DispatcherType.class)); } handler.addHandler(context); } Server server = new Server(); server.setSendServerVersion(false); try { List<Connector> connectors = new ArrayList<>(3); List<String> startupLogs = new ArrayList<>(3); // set connectors String host = configuration.getString(serviceName + ".http.host", "0.0.0.0"); int port = configuration.getInt(serviceName + ".http.port", 8080); int connectionIdleTime = configuration.getInt(serviceName + ".http.connectionIdleTime", 180000); boolean isBlockingChannelConnector = configuration .getBoolean(serviceName + ".http.isBlockingChannelConnector", false); int numberOfAcceptors = configuration.getInt(serviceName + ".http.numberOfAcceptors", Runtime.getRuntime().availableProcessors()); int acceptQueueSize = configuration.getInt(serviceName + ".http.acceptQueueSize", 0); boolean serviceDirectoryEnabled = configuration .getBoolean(serviceName + ".http.serviceDirectory.isEnabled", false); if (servletMapping != null && !servletMapping.isEmpty()) { for (Map<String, String> servletToConnctor : servletMapping.values()) { String logicalName = servletToConnctor.get("logicalName"); String uriMapping = servletToConnctor.get("uriMapping"); String hostForConnector = servletToConnctor.get("host"); int portForConnector = Integer.parseInt(servletToConnctor.get("port")); ServletContextHandler servletContextHandler = contextMap.get(uriMapping); servletContextHandler.setVirtualHosts(new String[] { "@" + logicalName }); boolean isSSL = Boolean.valueOf(servletToConnctor.get("isSSL")); getConnectors(startupLogs, connectors, isSSL, logicalName, serviceName, keyStorePath, keyStorePassword, trustStorePath, trustStorePassword, configuration, hostForConnector, portForConnector, connectionIdleTime, isBlockingChannelConnector, numberOfAcceptors, acceptQueueSize); servletContextHandler.setConnectorNames(new String[] { logicalName }); } } else { boolean useHttpsOnly = configuration.getBoolean(serviceName + ".https.useHttpsOnly", false); getConnectors(startupLogs, connectors, useHttpsOnly, null, serviceName, keyStorePath, keyStorePassword, trustStorePath, trustStorePassword, configuration, host, port, connectionIdleTime, isBlockingChannelConnector, numberOfAcceptors, acceptQueueSize); } server.setConnectors(connectors.toArray(new Connector[0])); // set thread pool server.setThreadPool(jettyHttpThreadPool.threadPool); // set servlets/context handlers server.setHandler(handler); server.start(); ProvidedServiceInstance instance = null; if (serviceDirectoryEnabled) { instance = registerWithSDServer(serviceName, host, port); } servers.put(serviceName, Pair.of(server, instance)); for (String startupLog : startupLogs) { LOGGER.info(startupLog); } // server.join(); } catch (Exception e) { LOGGER.error("Problem starting the http {} server. Error is {}.", new Object[] { serviceName, e, e }); throw new ServerFailedToStartException(e); } }
From source file:org.apache.hadoop.yarn.server.timeline.LeveldbTimelineStore.java
@Override public TimelineEntity getEntity(String entityId, String entityType, EnumSet<Field> fields) throws IOException { Long revStartTime = getStartTimeLong(entityId, entityType); if (revStartTime == null) { return null; }//from w w w. j a v a 2s . com byte[] prefix = KeyBuilder.newInstance().add(ENTITY_ENTRY_PREFIX).add(entityType) .add(writeReverseOrderedLong(revStartTime)).add(entityId).getBytesForLookup(); LeveldbIterator iterator = null; try { iterator = new LeveldbIterator(db); iterator.seek(prefix); if (fields == null) { fields = EnumSet.allOf(Field.class); } return getEntity(entityId, entityType, revStartTime, fields, iterator, prefix, prefix.length); } catch (DBException e) { throw new IOException(e); } finally { IOUtils.cleanup(LOG, iterator); } }
From source file:org.apache.hadoop.tools.mapred.TestCopyMapper.java
@Test(timeout = 40000) public void testPreserve() { try {//from www .ja va 2 s . c o m deleteState(); createSourceData(); try { UsersGroups.addUser("guest"); } catch (UserAlreadyExistsException e) { } UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest"); final CopyMapper copyMapper = new CopyMapper(); final Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = tmpUser .doAs(new PrivilegedAction<Mapper<Text, CopyListingFileStatus, Text, Text>.Context>() { @Override public Mapper<Text, CopyListingFileStatus, Text, Text>.Context run() { try { StubContext stubContext = new StubContext(getConfiguration(), null, 0); return stubContext.getContext(); } catch (Exception e) { LOG.error("Exception encountered ", e); throw new RuntimeException(e); } } }); EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class); preserveStatus.remove(DistCpOptions.FileAttribute.ACL); preserveStatus.remove(DistCpOptions.FileAttribute.XATTR); context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS, DistCpUtils.packAttributes(preserveStatus)); touchFile(SOURCE_PATH + "/src/file"); 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"), new CopyListingFileStatus(tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file"))), 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()); } }