@SuppressWarnings("unchecked") @Override public ServerConfiguration getServerConfiguration() throws Exception { FileReader fileReader; BufferedReader reader; String line; int iStartPos; ServerConfiguration config = null; String root = ""; int port = 0; Class<HttpApplication> httpApplicationClass = null; String paramater; String value; try { fileReader = new FileReader(serverConfig); reader = new BufferedReader(fileReader); while (reader.ready()) { line = reader.readLine().trim(); if (line.length() > 0) { iStartPos = line.indexOf(';'); paramater = line.substring(0, iStartPos); value = line.substring(iStartPos + 1); if (ServerConfiguration.RootParamaterName.equals(paramater.trim())) root = value.trim(); else if (ServerConfiguration.PortParamaterName.equals(paramater)) port = Integer.parseInt(value.trim()); else if (ServerConfiguration.HttpApplication_ClassParamaterName.equals(paramater)) { if (!root.isEmpty()) { URL urls[] = {}; String path = root + "app.jar"; JarFileLoader jarloader = new JarFileLoader(urls); jarloader.addFile(path); httpApplicationClass = (Class<HttpApplication>) jarloader.loadClass(value.trim()); } else throw new IllegalArgumentException(); } } } if (!root.isEmpty() && port != 0 && httpApplicationClass != null) { String serverRoot = ServerMain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); config = new ServerConfiguration(serverRoot, port); ServerConfiguration.WebApplication app = config.new WebApplication(root, httpApplicationClass); config.WebApplication = app; } } catch (Exception e) { e.printStackTrace(System.err); } return config; }
@Before public void setup() throws IOException, InterruptedException { PropertyConfigurator.configure(getClass().getResourceAsStream("log4j.properties")); ServerConfiguration config = ServerConfiguration.defaults(); // Use any available port config.setPortSocket(0); config.setPortWebsocket(0); main = new MainServer(config); main.getMods().loadExternal(Paths.get("../extra-resources/groovy")); server = main.start(); assertTrue("Server should start correctly.", server.getClients().size() > 0); socketPort = config.getPortSocket(); client1 = createTestClient(); client1.send(new LoginMessage("Tester1")); WelcomeMessage welcome = client1.await(WelcomeMessage.class); assertEquals(200, welcome.getStatus()); System.out.println(server.getClients()); assertEquals(server.getClients().size() + 1, welcome.getUserId()); userId = welcome.getUserId(); client1.await(ChatMessage.class); mods = client1.await(AvailableModsMessage.class); assertNotEquals("No mods found in " + new File("").getAbsolutePath(), 0, mods.getMods().length); }
/** * Starts the <code>HttpServer</code>. * * @throws IOException if an error occurs while attempting to start the server. */ public synchronized void start() throws IOException { if (state == State.RUNNING) { return; } else if (state == State.STOPPING) { throw new IllegalStateException( "The server is currently in pending" + " shutdown state. You have to either wait for shutdown to" + " complete or force it by calling shutdownNow()"); } state = State.RUNNING; shutdownFuture = null; configureAuxThreadPool(); delayedExecutor = new DelayedExecutor(auxExecutorService); delayedExecutor.start(); for (final NetworkListener listener : listeners.values()) { configureListener(listener); } if (serverConfig.isJmxEnabled()) { enableJMX(); } for (final NetworkListener listener : listeners.values()) { try { listener.start(); } catch (IOException ioe) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log( Level.FINEST, "Failed to start listener [{0}] : {1}", new Object[] {listener.toString(), ioe.toString()}); LOGGER.log(Level.FINEST, ioe.toString(), ioe); } throw ioe; } } setupHttpHandler(); if (serverConfig.isJmxEnabled()) { for (final JmxEventListener l : serverConfig.getJmxEventListeners()) { l.jmxEnabled(); } } if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "[{0}] Started.", getServerConfiguration().getName()); } }
/** * @param docRoot the document root, can be <code>null</code> when no static pages are needed * @param host the network port to which this listener will bind * @param range port range to attempt to bind to * @return a <code>HttpServer</code> configured to listen to requests on <code>host</code>:<code> * [port-range]</code>, using the specified <code>docRoot</code> as the server's document root */ public static HttpServer createSimpleServer( final String docRoot, final String host, final PortRange range) { final HttpServer server = new HttpServer(); final ServerConfiguration config = server.getServerConfiguration(); if (docRoot != null) { config.addHttpHandler(new StaticHttpHandler(docRoot), "/"); } final NetworkListener listener = new NetworkListener("grizzly", host, range); server.addListener(listener); return server; }
/** * This method will be invoked when a service's global configuration data has been changed. The * parameter <code>groupName</code> denote the name of the configuration grouping (e.g. default) * and <code>serviceComponent</code> denotes the service's sub-component that changed (e.g. <code> * /NamedPolicy</code>, <code>/Templates</code>). * * @param serviceName Name of the service. * @param version Version of the service. * @param groupName Name of the configuration grouping. * @param serviceComponent Name of the service components that changed. * @param type change type, i.e., ADDED, REMOVED or MODIFIED. */ public void globalConfigChanged( String serviceName, String version, String groupName, String serviceComponent, int type) { if (serviceName.equals(Constants.SVC_NAME_PLATFORM)) { if (serviceComponent.startsWith("/" + ConfigurationBase.CONFIG_SERVERS + "/")) { String serverName = serviceComponent.substring(PARENT_LEN); if (serverName.equals(ServerConfiguration.DEFAULT_SERVER_CONFIG) || serverName.equals(SystemProperties.getServerInstanceName())) { // always use the server instance name with initialising properties if (serverName.equals(ServerConfiguration.DEFAULT_SERVER_CONFIG)) { serverName = SystemProperties.getServerInstanceName(); } SSOToken adminToken = AccessController.doPrivileged(AdminTokenAction.getInstance()); try { Properties newProp = ServerConfiguration.getServerInstance(adminToken, serverName); SystemProperties.initializeProperties(newProp, true, true); notifies(Constants.SVC_NAME_PLATFORM); } catch (SSOException | IOException | SMSException ex) { // ignored } } } else { notifies(Constants.SVC_NAME_PLATFORM); } } else { /* need to do this else bcoz some of the property have been moved * to services */ notifies(serviceName); } }
public PACSStudyOperations(String username, String password) throws Exception { sxc = new PACSConfiguration(); serverConfiguration = sxc.getElementValues(); env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); env.setProperty(Context.URL_PKG_PREFIXES, "org.jnp.interfaces.NamingContextFactory"); env.setProperty(Context.PROVIDER_URL, "jnp://" + serverConfiguration.getHostName() + ":1099/"); pacsHandler = new PACSCallBackHandler(username, password); conf = new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { @SuppressWarnings({"unchecked", "rawtypes"}) AppConfigurationEntry entry = new AppConfigurationEntry( "org.jboss.security.ClientLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new java.util.HashMap()); return new AppConfigurationEntry[] {entry}; } }; }
/** Immediately shuts down the <code>HttpServer</code> instance. */ public synchronized void shutdownNow() { if (state == State.STOPPED) { return; } state = State.STOPPED; try { if (serverConfig.isJmxEnabled()) { for (final JmxEventListener l : serverConfig.getJmxEventListeners()) { l.jmxDisabled(); } } tearDownHttpHandler(); final String[] names = listeners.keySet().toArray(new String[listeners.size()]); for (final String name : names) { removeListener(name); } delayedExecutor.stop(); delayedExecutor.destroy(); delayedExecutor = null; stopAuxThreadPool(); if (serverConfig.isJmxEnabled()) { disableJMX(); } } catch (Exception e) { LOGGER.log(Level.WARNING, null, e); } finally { for (final NetworkListener listener : listeners.values()) { final FilterChain filterChain = listener.getTransport().getFilterChain(); filterChain.clear(); } if (shutdownFuture != null) { shutdownFuture.result(this); } } }
public static void dcmSND(String filename) throws Exception { // ServerXmlConfiguration sxc = new ServerXmlConfiguration(); Context context = new InitialContext(); String icmaaetitle = (String) context.lookup("java:global/ICMAAETITLE"); PACSConfiguration sxc = new PACSConfiguration(); ServerConfiguration sc = sxc.getElementValues(); DcmSnd dcmsnd = new DcmSnd(icmaaetitle); // Register the calling AE title dcmsnd.setCalledAET(sc.getAeTitle()); dcmsnd.setRemoteHost(sc.getHostName()); dcmsnd.setRemotePort(Integer.parseInt((sc.getPort()))); dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(false); dcmsnd.setSendFileRef(false); // Username password etc /* * if (cl.hasOption("username")) { String username = * cl.getOptionValue("username"); UserIdentity userId; UserIdentity * userId; if (cl.hasOption("passcode")) { String passcode = * cl.getOptionValue("passcode"); userId = new * UserIdentity.UsernamePasscode(username, passcode.toCharArray()); } * else { userId = new UserIdentity.Username(username); } * userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp")); * dcmsnd.setUserIdentity(userId); } */ dcmsnd.setStorageCommitment(false); dcmsnd.setPackPDV(true); dcmsnd.setTcpNoDelay(true); // Setup the file dcmsnd.addFile(new File(filename)); dcmsnd.configureTransferCapability(); try { // Start the sending process dcmsnd.start(); // Open connections dcmsnd.open(); dcmsnd.send(); dcmsnd.close(); } catch (Exception exx) { throw exx; } finally { dcmsnd.stop(); } }
protected void enableJMX() { if (jmxManager == null) { synchronized (serverConfig) { if (jmxManager == null) { jmxManager = GrizzlyJmxManager.instance(); } } } jmxManager.registerAtRoot(getManagementObject(false), serverConfig.getName()); }
@SuppressWarnings("unchecked") private void configureMonitoring(final NetworkListener listener) { final Transport transport = listener.getTransport(); final MonitoringConfig<TransportProbe> transportMonitoringCfg = transport.getMonitoringConfig(); final MonitoringConfig<ConnectionProbe> connectionMonitoringCfg = transport.getConnectionMonitoringConfig(); final MonitoringConfig<MemoryProbe> memoryMonitoringCfg = transport.getMemoryManager().getMonitoringConfig(); final MonitoringConfig<ThreadPoolProbe> threadPoolMonitoringCfg = transport.getThreadPoolMonitoringConfig(); transportMonitoringCfg.addProbes( serverConfig.getMonitoringConfig().getTransportConfig().getProbes()); connectionMonitoringCfg.addProbes( serverConfig.getMonitoringConfig().getConnectionConfig().getProbes()); memoryMonitoringCfg.addProbes(serverConfig.getMonitoringConfig().getMemoryConfig().getProbes()); threadPoolMonitoringCfg.addProbes( serverConfig.getMonitoringConfig().getThreadPoolConfig().getProbes()); }
private void setupHttpHandler() { serverConfig.addJmxEventListener(httpHandlerChain); synchronized (serverConfig.handlersSync) { for (final HttpHandler httpHandler : serverConfig.orderedHandlers) { final String[] mappings = serverConfig.handlers.get(httpHandler); httpHandlerChain.addHandler(httpHandler, mappings); } } httpHandlerChain.start(); }
@SuppressWarnings("unchecked") public static Object createIface(String clazzIfaceName, List<String> servers) throws ClassNotFoundException { String clazzClientName = clazzIfaceName.substring(0, clazzIfaceName.lastIndexOf('$')) + "$Client"; Class<?> clientClazz = Class.forName(clazzClientName); ServerConfiguration configuration = new ServerConfiguration(); for (String server : servers) { server = server.trim(); String[] metas = server.split(":"); if (metas.length != 2) { throw new IllegalArgumentException(server); } configuration.getServerNodes().add(new ServerNode(metas[0], Integer.parseInt(metas[1]))); } configuration.setTimeout(1000 * 5); @SuppressWarnings("rawtypes") DynamicClientProxy proxy = new DynamicClientProxy(); return proxy.createProxy(clientClazz, configuration); }
/** * Adds a default administrator account, if not running in LAN mode, and if there are no accounts * in the active accounts service. */ private void createAdminIfNoUsers() { Configuration conf = context.getService(Configuration.class); if (!conf.getBoolean(ServerConfiguration.LAN_MODE)) { AccountsService accountsService = context.getAccountsService(); if (accountsService.getAccountsSize() == 0) { Configuration defaults = ServerConfiguration.getDefaults(); String username = defaults.getString(ServerConfiguration.LAN_ADMIN_USERNAME); String password = defaults.getString(ServerConfiguration.LAN_ADMIN_PASSWORD); LOG.info( "As there are no accounts yet, we are creating an" + " admin account: username=\"{}\", password=\"{}\"", username, password); Account admin = createAdmin(username, password); accountsService.addAccount(admin); accountsService.saveAccountsIfNeeded(); } } }
/** * Create cluster configuration object * * @param serverConfig */ public ClusterConfiguration(final ServerConfiguration serverConfig) { this.serverConfig = serverConfig; this.zookeeperConnection = serverConfig.getZookeeperConnection(); }
/** @return whether running in INMemory Mode */ public Boolean isInMemoryMode() { return serverConfig.isInMemoryModeEnabled(); }
public int getMaxNumberOfReadButUndeliveredMessages() { return serverConfig.getMaxNumberOfReadButUndeliveredMessages(); }
@Override protected JSONObject doInBackground(final String... givenUrl) { final ServerConfiguration serverConfiguration = AppContext.getServerConfiguration(); if (serverConfiguration == null || (serverConfiguration != null && !serverConfiguration.isValid())) { logError(new IOException(), "No server configured"); return null; } URLConnection c = null; try { String partialURL = serverConfiguration.getAddress() + givenUrl[0]; if (activity instanceof SearchActivity) { partialURL += LIST_PAGINATION; if (isPagedCookie) { partialURL += getPagedCookie(); } else { partialURL += getPageOffset(); } } final String authString = serverConfiguration.getUsername() + ":" + serverConfiguration.getPassword(); if (!serverConfiguration.isSSL()) { // Basic authentication. try { publishProgress(20); final URL url = getHTTPUrl(partialURL); c = url.openConnection(); c.setUseCaches(false); c.setConnectTimeout(3000); c.setReadTimeout(3000); c.setDoOutput(false); c.setRequestProperty( "Authorization", "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP)); c.connect(); publishProgress(50); if (((HttpURLConnection) c).getResponseCode() != 200) { if (((HttpURLConnection) c).getResponseCode() == 401) { error = "Invalid credentials"; throw new IOException("Invalid credentials"); } else { final String msg = ((HttpURLConnection) c).getResponseMessage(); if (msg != null) { throw new ConnectException(msg); } throw new ConnectException(); } } } catch (final SocketTimeoutException e) { logError(e, "Unable to connect to server."); } catch (final SocketException e) { logError(e, "Invalid server configuration."); } catch (final Exception e) { logError(e, "An error occured."); } } else { // SSL Connection. setSSLConnection(); final URL url = getHTTPsUrl(partialURL); try { c = url.openConnection(); c.setRequestProperty( "Authorization", "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP)); } catch (final IOException e) { logError(e, "An error occured during SSL transaction."); } ((HttpsURLConnection) c).setHostnameVerifier(new SSLHostNameVerifier()); } return readStream(c.getInputStream()); } catch (final IOException e) { logError(e, "An error when reading request result."); } finally { Utils.closeConnection(c); } return null; }
public int getFlusherPoolSize() { return serverConfig.getFlusherPoolSize(); }
private void configureListener(final NetworkListener listener) { FilterChain chain = listener.getFilterChain(); if (chain == null) { final FilterChainBuilder builder = FilterChainBuilder.newInstance(); builder.add(new TransportFilter()); if (listener.isSecure()) { SSLEngineConfigurator sslConfig = listener.getSslEngineConfig(); if (sslConfig == null) { sslConfig = new SSLEngineConfigurator(SSLContextConfigurator.DEFAULT_CONFIG, false, false, false); listener.setSSLEngineConfig(sslConfig); } final SSLBaseFilter filter = new SSLBaseFilter(sslConfig); builder.add(filter); } final int maxHeaderSize = listener.getMaxHttpHeaderSize() == -1 ? org.glassfish.grizzly.http.HttpServerFilter.DEFAULT_MAX_HTTP_PACKET_HEADER_SIZE : listener.getMaxHttpHeaderSize(); // Passing null value for the delayed executor, because IdleTimeoutFilter should // handle idle connections for us final org.glassfish.grizzly.http.HttpServerFilter httpServerCodecFilter = new org.glassfish.grizzly.http.HttpServerFilter( listener.isChunkingEnabled(), maxHeaderSize, null, listener.getKeepAliveConfig(), null, listener.getMaxRequestHeaders(), listener.getMaxResponseHeaders()); final Set<ContentEncoding> contentEncodings = configureCompressionEncodings(listener); for (ContentEncoding contentEncoding : contentEncodings) { httpServerCodecFilter.addContentEncoding(contentEncoding); } httpServerCodecFilter .getMonitoringConfig() .addProbes(serverConfig.getMonitoringConfig().getHttpConfig().getProbes()); builder.add(httpServerCodecFilter); builder.add( new IdleTimeoutFilter( delayedExecutor, listener.getKeepAliveConfig().getIdleTimeoutInSeconds(), TimeUnit.SECONDS)); final Transport transport = listener.getTransport(); final FileCache fileCache = listener.getFileCache(); fileCache.initialize(delayedExecutor); final FileCacheFilter fileCacheFilter = new FileCacheFilter(fileCache); fileCache .getMonitoringConfig() .addProbes(serverConfig.getMonitoringConfig().getFileCacheConfig().getProbes()); builder.add(fileCacheFilter); final ServerFilterConfiguration config = new ServerFilterConfiguration(serverConfig); if (listener.isSendFileExplicitlyConfigured()) { config.setSendFileEnabled(listener.isSendFileEnabled()); fileCache.setFileSendEnabled(listener.isSendFileEnabled()); } if (listener.getBackendConfig() != null) { config.setBackendConfiguration(listener.getBackendConfig()); } if (listener.getDefaultErrorPageGenerator() != null) { config.setDefaultErrorPageGenerator(listener.getDefaultErrorPageGenerator()); } config.setTraceEnabled(config.isTraceEnabled() || listener.isTraceEnabled()); config.setMaxFormPostSize(listener.getMaxFormPostSize()); config.setMaxBufferedPostSize(listener.getMaxBufferedPostSize()); final HttpServerFilter httpServerFilter = new HttpServerFilter(config, delayedExecutor); httpServerFilter.setHttpHandler(httpHandlerChain); httpServerFilter .getMonitoringConfig() .addProbes(serverConfig.getMonitoringConfig().getWebServerConfig().getProbes()); builder.add(httpServerFilter); chain = builder.build(); final AddOn[] addons = listener.getAddOnSet().getArray(); if (addons != null) { for (AddOn addon : addons) { addon.setup(listener, chain); } } listener.setFilterChain(chain); final int transactionTimeout = listener.getTransactionTimeout(); if (transactionTimeout >= 0) { ThreadPoolConfig threadPoolConfig = transport.getWorkerThreadPoolConfig(); if (threadPoolConfig != null) { threadPoolConfig.setTransactionTimeout( delayedExecutor, transactionTimeout, TimeUnit.SECONDS); } } } configureMonitoring(listener); }
public int getMaxNumberOfUnackedMessages() { return serverConfig.getMaxNumberOfUnackedMessages(); }
/** @return whether clustering is enabled */ public Boolean isClusteringEnabled() { return serverConfig.getClusteringEnabled(); }
public int getAndesInternalParallelThreadPoolSize() { return serverConfig.getAndesInternalParallelThreadPoolSize(); }
public boolean getViewMessageCounts() { return serverConfig.getViewMessageCounts(); }
public int getInternalSequentialThreadPoolSize() { return serverConfig.getInternalSequentialThreadPoolSize(); }
public int getSubscriptionPoolSize() { return serverConfig.getSubscriptionPoolSize(); }
public int andesExecutorServicePoolSize() { return serverConfig.getAndesExecutorServicePoolSize(); }
public int getGlobalQueueCount() { return serverConfig.getGlobalQueueCount(); }
public int getMinMessageBatchSizeForSubscribers() { return serverConfig.getMinMessageBatchSizeForSubscribers(); }
public int getNumberOfMaximumDeliveryCount() { return serverConfig.getNumberOfMaximumDeliveryCount(); }
public boolean isOnceInOrderSupportEnabled() { return serverConfig.isOnceInOrderSupportEnabled(); }