public Container buildContainer(String containerClass) { notNull( containerClass, "Container type " + Arrays.deepToString(Server.values()) + " or container class"); Class<Container> clazz = null; for (Server container : Server.values()) { if (container.name().equalsIgnoreCase(containerClass)) { clazz = loadServerClass(container.serverClass()); break; } } if (clazz == null) clazz = loadServerClass(containerClass); try { return clazz .getConstructor(ContainerConfiguration.class) .newInstance(ContainerConfiguration.from(this)); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) throw (RuntimeException) e.getTargetException(); else throw new RuntimeException(e.getTargetException().getMessage(), e.getTargetException()); } catch (Exception e) { throw new IllegalArgumentException( "Cannot instanciate class [" + clazz + "]. Ensure there is a public constructor having a parameter of type " + ContainerConfiguration.class.getName(), e); } }
public void setContent(byte[] cntnt) throws Exception { StringBuffer sb = new StringBuffer(isHTTP11 ? "HTTP/1.1" : "HTTP/1.0"); sb.append(OK_HDR); sb.append("Content-Type: "); sb.append(contentType); if (!isHTTP11 || !keepAlive || isMessages) { sb.append("\r\nConnection: close\r\nProxy-Connection: close"); } else { sb.append("\r\nConnection: Keep-Alive\r\nProxy-Connection: Keep-Alive"); sb.append("\r\nContent-Length: "); sb.append(cntnt.length); } sb.append("\r\n\r\n"); sb.trimToSize(); CharBuffer cb = CharBuffer.wrap(sb.toString()); ByteBuffer tempBuffer; try { tempBuffer = Charset.forName("iso-8859-1").newEncoder().encode(cb); } catch (CharacterCodingException cce) { Server.debug(this, "prepareForSending: ", cce, Server.MSG_ERROR, Server.LVL_MINOR); try { tempBuffer = ByteBuffer.wrap(cb.toString().getBytes(Server.srv.DEFAULT_CHARSET)); } catch (Exception e) { Server.debug(this, "prepareForSending: ", e, Server.MSG_ERROR, Server.LVL_MAJOR); throw e; } } this.buf = ByteBuffer.allocate(tempBuffer.capacity() + cntnt.length); this.buf.put(tempBuffer.array()); this.buf.put(cntnt); this.buf.flip(); }
private String getSocketIn() { try { String s = ""; while (true) { int count = socket_in.read(buffer); if (count < 0) { for (Iterator<Server> it = servers.iterator(); it.hasNext(); ) { Server server = it.next(); if (server.host.equals(host)) { server.deleteThis(); break; } } deleteThis(); Bundle bundle = new Bundle(); bundle.putInt(Constants.CLIENTS_STATUS, Constants.CLIENTS_STATUS_UPDATE_STATUS); Message msg = new Message(); msg.setData(bundle); MainActivity.this.clientMessageHandler.sendMessage(msg); return null; } s += new String(buffer, 0, count); if (s.endsWith("\n")) { s = s.substring(0, s.length() - 1); break; } } return s; } catch (Exception e) { return null; } }
@Override @Transactional public Application start(Application application) throws ServiceException { try { User user = authentificationUtils.getAuthentificatedUser(); logger.debug("start : Methods parameters : " + application); List<Module> modules = application.getModules(); for (Module module : modules) { try { module = moduleService.startModule(module); } catch (ServiceException e) { logger.error("failed to start " + application.toString(), e); } } List<Server> servers = application.getServers(); for (Server server : servers) { logger.info("old server ip : " + server.getContainerIP()); server = serverService.startServer(server); } if (application.getAliases() != null && !application.getAliases().isEmpty()) { updateAliases(application); } logger.info("ApplicationService : Application successfully started "); } catch (PersistenceException e) { throw new ServiceException(e.getLocalizedMessage(), e); } return application; }
@Override public void run() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if ((networkInfo == null) || (!networkInfo.isConnected()) || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI)) { bundle.putInt( Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_WIFI_NOT_CONNECTED); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); return; } WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = (ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff); try { serverSocket = new ServerSocket(Constants.SERVER_PORT); bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_LISTENING); bundle.putString(Constants.IP_ADDRESS, ip); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); } catch (Exception e) { bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_INIT_FAILED); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); return; } Socket clientSocket; while (true) { try { clientSocket = serverSocket.accept(); String hostAddress = clientSocket.getInetAddress().getHostAddress(); boolean inClients = false; for (Client client : clients) if (client.host.equals(hostAddress)) { inClients = true; break; } if (!inClients) { Client newClient = new Client(hostAddress); clients.add(newClient); newClient.connect(); } Server server = new Server(clientSocket, hostAddress); servers.add(server); server.start(); } catch (Exception e) { } } }
@Test(timeout = 90000) public void testRPCInterruptedSimple() throws IOException { final Configuration conf = new Configuration(); Server server = new RPC.Builder(conf) .setProtocol(TestProtocol.class) .setInstance(new TestImpl()) .setBindAddress(ADDRESS) .setPort(0) .setNumHandlers(5) .setVerbose(true) .setSecretManager(null) .build(); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); // Connect to the server proxy.ping(); // Interrupt self, try another call Thread.currentThread().interrupt(); try { proxy.ping(); fail("Interruption did not cause IPC to fail"); } catch (IOException ioe) { if (!ioe.toString().contains("InterruptedException")) { throw ioe; } // clear interrupt status for future tests Thread.interrupted(); } }
/** Update the server. */ private void updateServer() { System.out.println("Updating the server."); // PLACEHOLDER server.SendData("HELO"); System.out.println(server.getData()); }
private void refreshTimeoutOnEvade(User user, Server server) { ServerTimeout timeout = SafeNav.of(serverStorage.get(server.getId())) .next(TempServerConfig::getServerTimeouts) .next(ServerTimeoutStorage::getTimeouts) .next(timeouts -> timeouts.get(user.getId())) .get(); if (timeout == null) { LOGGER.warn( "Attempted to refresh a timeout on a user who was not timed out! {} ({})", user.getUsername(), user.getId()); return; } LOGGER.info( "User {} ({}) attempted to evade a timeout on {} ({})!", user.getUsername(), user.getId(), server.getName(), server.getId()); Channel channel = apiClient.getChannelById(server.getId(), server); apiClient.sendMessage( loc.localize( "listener.mod.timeout.on_evasion", user.getId(), formatDuration(Duration.between(Instant.now(), timeout.getEndTime())), formatInstant(timeout.getEndTime())), channel); applyTimeoutRole(user, server, channel); }
// ainda nao acabou public Server chooseServer() { int maximun = -1; Vector<Server> bestServers = new Vector<Server>(); // escolher os servidores com maior capacidade for (int i = 0; i < p.getServers().size(); i++) { if (p.getServers().get(i).getCapacity() >= maximun) { if (p.getServers().get(i).getCapacity() > maximun) { bestServers = new Vector<Server>(); maximun = p.getServers().get(i).getCapacity(); } bestServers.add(p.getServers().get(i)); } } if (maximun == -1) { return null; } // escolher os servidores com menor tamanho Server bestServer = bestServers.get(0); for (int i = 1; i < bestServers.size(); i++) { if (bestServers.get(i).getSlots() < bestServer.getSlots()) { bestServer = bestServers.get(i); } } return null; }
public void testSerial( int handlerCount, boolean handlerSleep, int clientCount, int callerCount, int callCount) throws Exception { Server server = new TestServer(handlerCount, handlerSleep); InetSocketAddress addr = NetUtils.getConnectAddress(server); server.start(); Client[] clients = new Client[clientCount]; for (int i = 0; i < clientCount; i++) { clients[i] = new Client(LongWritable.class, conf); } SerialCaller[] callers = new SerialCaller[callerCount]; for (int i = 0; i < callerCount; i++) { callers[i] = new SerialCaller(clients[i % clientCount], addr, callCount); callers[i].start(); } for (int i = 0; i < callerCount; i++) { callers[i].join(); assertFalse(callers[i].failed); } for (int i = 0; i < clientCount; i++) { clients[i].stop(); } server.stop(); }
/** * Method declaration * * @return */ private Session init() { try { mSocket.setTcpNoDelay(true); mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream())); mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream())); user = mInput.readUTF(); String password = mInput.readUTF(); Session c; try { mServer.trace(mThread + ":trying to connect user " + user); return mServer.mDatabase.connect(user, password); } catch (SQLException e) { write(new Result(e.getMessage(), e.getErrorCode()).getBytes()); } } catch (Exception e) { mServer.trace(mThread + ":couldn't connect " + user); } close(); return null; }
public void run() { try { Telnet.writeLine(cs, "<fggreen> >>> Welcome to AdaMUD <<< <reset>"); Telnet.flushInput(cs); while ((player = s.getPlayerDB().login(cs, s)) == null) ; player.look(); while (true) { System.out.println("Waiting for message"); String message = Telnet.readLine(cs).trim(); if (message == null) { // Disconnected break; } if (message.equals("bye")) { Telnet.writeLine(cs, "Goodbye!"); break; } parseCommand(message); } cs.close(); } catch (IOException e) { System.out.println("Client error: " + e); } finally { s.getPlayerDB().remove(player); s.remove(cs); } }
public void run() { ServerSocket mainSocket = null; try { mainSocket = new ServerSocket(wyldConfig.getPort()); } catch (IOException e) { Misc.println(Messages.PORT_IN_USE.getDesc()); } Misc.println( "[Socket] Listening on port " + wyldConfig.getPort() + " for incoming connections."); while (true) { Socket connectionSocket = null; try { connectionSocket = mainSocket.accept(); } catch (IOException e) { Misc.servere(e.toString()); } try { Server thread = new Server(connectionSocket, i, irc); thread.start(); irc.clients.add(thread); } catch (java.lang.NullPointerException e) { e.printStackTrace(); } i++; } }
public void Dispose() { for (Server server : servers) { server.Dispose(); } super.Dispose(); }
private int getScore() { List<Integer> guaranteedCapacity = new ArrayList<Integer>(); for (int i = 0; i < this.nbPools; i++) { List<Integer> capacityPerRow = new ArrayList<Integer>(); for (int j = 0; j < this.nbRows; j++) { capacityPerRow.add(0); } for (Server s : this.servers) { if (s.getPool() == i) { capacityPerRow.set(s.getRow(), capacityPerRow.get(s.getRow()) + s.getCapacity()); } } int max = 0, sum = 0; for (Integer n : capacityPerRow) { max = (max > n) ? max : n; sum += n; } guaranteedCapacity.add(sum - max); } int min = Integer.MAX_VALUE; for (Integer n : guaranteedCapacity) { min = (min < n) ? min : n; } return min; }
public boolean cast(Player player, String[] command) { if (removeReagents(player, reagents)) { // reagents removed - cast spell // get targeted block HitBlox hit = new HitBlox(player); Block target = hit.getTargetBlock(); // remove blocks around target block Server s = etc.getServer(); for (int x = target.getX() - BLAST_RADIUS; x <= target.getX() + BLAST_RADIUS; x++) { for (int y = target.getY() - BLAST_RADIUS; y <= target.getY() + BLAST_RADIUS; y++) { for (int z = target.getZ() - BLAST_RADIUS; z <= target.getZ() + BLAST_RADIUS; z++) { s.setBlockAt(0, x, y, z); } } } // send alerts player.sendMessage(TEXT_COLOR + STR_CAST); sendMessageToPlayersInRange(player, STR_CAST_OTHERS); return true; } else { // reagents missing player.sendMessage(TEXT_COLOR + STR_NO_REAGENTS); return false; } }
public static void main(String[] args) { Server c = new Server(); int status = c.main("Server", args); System.gc(); System.exit(status); }
@Test public void memoryTest() throws InterruptedException { final StatefulKnowledgeSession ksession = createKnowledgeSession(); Event myevent = new Event(); ksession.setGlobal("event", myevent); final Server node1 = new Server(1500, "server1"); new Thread( new Runnable() { public void run() { ksession.fireUntilHalt(); } }) .start(); serverHandle = ksession.insert(node1); int memory = 1500; for (int i = 0; i < 5; i++) { Thread.sleep(6000); memory = memory - 200; node1.setMemory(memory); ksession.update(serverHandle, node1); } ksession.halt(); System.out.println(myevent.getEvents()); }
private void stopTimeout(MessageContext context, String args) { if (args.isEmpty()) { apiClient.sendMessage( loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel()); return; } String uid = args; if (uid.length() > 4) { if (uid.startsWith("<@")) { uid = uid.substring(2, uid.length() - 1); } Server server = context.getServer(); User user = apiClient.getUserById(uid, server); if (user == NO_USER) { user = new User("UNKNOWN", uid, "", null); } LOGGER.info( "{} ({}) is attempting to cancel timeout for {} ({}) in {} ({})", context.getAuthor().getUsername(), context.getAuthor().getId(), user.getUsername(), user.getId(), server.getName(), server.getId()); cancelTimeout(user, server, context.getChannel()); } else { apiClient.sendMessage( loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel()); } }
@Test public void testProxyAddress() throws IOException { Server server = new RPC.Builder(conf) .setProtocol(TestProtocol.class) .setInstance(new TestImpl()) .setBindAddress(ADDRESS) .setPort(0) .build(); TestProtocol proxy = null; try { server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); // create a client proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); assertEquals(addr, RPC.getServerAddress(proxy)); } finally { server.stop(); if (proxy != null) { RPC.stopProxy(proxy); } } }
@Test(timeout = 90000) public void testRPCInterruptedSimple() throws Exception { final Configuration conf = new Configuration(); Server server = RPC.getServer(TestProtocol.class, new TestImpl(), ADDRESS, 0, 5, true, conf, null); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); // Connect to the server proxy.ping(); // Interrupt self, try another call Thread.currentThread().interrupt(); try { proxy.ping(); fail("Interruption did not cause IPC to fail"); } catch (IOException ioe) { if (!ioe.toString().contains("InterruptedException")) { throw ioe; } // clear interrupt status for future tests Thread.interrupted(); } finally { server.stop(); } }
@Override @Transactional public void addNewAlias(Application application, String alias) throws ServiceException, CheckException { logger.info("ALIAS VALUE IN addNewAlias : " + alias); if (checkAliasIfExists(alias)) { throw new CheckException( "This alias is already used by another application on this CloudUnit instance"); } alias = alias.toLowerCase(); if (alias.startsWith("https://") || alias.startsWith("http://") || alias.startsWith("ftp://")) { alias = alias.substring(alias.lastIndexOf("//") + 2, alias.length()); } if (!StringUtils.isAlphanumeric(alias)) { throw new CheckException( "This alias must be alphanumeric. Please remove all other characters"); } try { Server server = application.getServers().get(0); application.getAliases().add(alias); hipacheRedisUtils.writeNewAlias(alias, application, server.getServerAction().getServerPort()); applicationDAO.save(application); } catch (DataAccessException e) { throw new ServiceException(e.getLocalizedMessage(), e); } }
@Test public void testConnectionPing() throws Exception { Configuration conf = new Configuration(); int pingInterval = 50; conf.setBoolean(CommonConfigurationKeys.IPC_CLIENT_PING_KEY, true); conf.setInt(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY, pingInterval); final Server server = new RPC.Builder(conf) .setProtocol(TestProtocol.class) .setInstance(new TestImpl()) .setBindAddress(ADDRESS) .setPort(0) .setNumHandlers(5) .setVerbose(true) .build(); server.start(); final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, server.getListenerAddress(), conf); try { // this call will throw exception if server couldn't decode the ping proxy.sleep(pingInterval * 4); } finally { if (proxy != null) RPC.stopProxy(proxy); } }
public void startLobby() { server.broadcastMessage(GOLD + "[ServerGames]" + GREEN + " Countdown started."); clearAll(); bets.clear(); this.clearEnt(); load(); tpAll(waiting); ServerGames.current = worlds.get(new Random().nextInt(ServerGames.worlds.size())); for (Player p : server.getOnlinePlayers()) { showAllFor(p); showPlayer(p); if (isTribute(p) || isSpectator(p)) clearItems(p); } loaded.clear(); this.resetPlayers(); state = State.LOBBY; game = new Lobby(this); startTimer(); }
/** Test that server.stop() properly stops all threads */ @Test public void testStopsAllThreads() throws IOException, InterruptedException { int threadsBefore = countThreads("Server$Listener$Reader"); assertEquals("Expect no Reader threads running before test", 0, threadsBefore); final Server server = new RPC.Builder(conf) .setProtocol(TestProtocol.class) .setInstance(new TestImpl()) .setBindAddress(ADDRESS) .setPort(0) .setNumHandlers(5) .setVerbose(true) .build(); server.start(); try { // Wait for at least one reader thread to start int threadsRunning = 0; long totalSleepTime = 0; do { totalSleepTime += 10; Thread.sleep(10); threadsRunning = countThreads("Server$Listener$Reader"); } while (threadsRunning == 0 && totalSleepTime < 5000); // Validate that at least one thread started (we didn't timeout) threadsRunning = countThreads("Server$Listener$Reader"); assertTrue(threadsRunning > 0); } finally { server.stop(); } int threadsAfter = countThreads("Server$Listener$Reader"); assertEquals("Expect no Reader threads left running after test", 0, threadsAfter); }
/** * Konstruktor, uebernimmt eine Socket-Verbindung vom Server, initialisiert die Ein-und * Ausgabestreams des Sockets und speichert seine Spielernummer, die er vom Server zugewiesen * bekommt. Diese wird dann zuletzt an den Communicator gesendet. * * @param connection Socketverbindung * @param server Server-Objekt * @param cnt Spielernummer * @param gameID Spiel-ID * @param name Spielname * @exception IOException * @exception SocketException */ public ServerThread(Socket connection, Server server, int cnt, int gameID, String name) { this.connection = connection; this.server = server; this.myNumber = cnt; this.gameID = gameID; this.nameOfTheGame = name; try { out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(this.connection.getOutputStream()))); in = new BufferedReader(new InputStreamReader(this.connection.getInputStream())); } catch (IOException e) { String log = "player " + (myNumber + 1) + ":error creating ServerThread\n"; System.out.print(log); this.server.log(log, server.getPort()); } send("1" + Integer.toString(myNumber)); // sende die zugewiesene // Spielernummer // an den Communicator try { this.connection.setSoTimeout(1800000); this.connection.setSoLinger(true, 6); // optional? } catch (SocketException e) { String log = "player " + (myNumber + 1) + ": error setting socket options\n"; System.out.print(log); this.server.log(log, server.getPort()); } }
public void markServerDown(String id) { boolean triggered = false; id = Server.normalizeId(id); if (id == null) { return; } Lock writeLock = upServerLock.writeLock(); try { writeLock.lock(); final List<Server> changedServers = new ArrayList<Server>(); for (Server svr : upServerList) { if (svr.isAlive() && (svr.getId().equals(id))) { triggered = true; svr.setAlive(false); changedServers.add(svr); } } if (triggered) { logger.error("LoadBalancer: markServerDown called on [" + id + "]"); notifyServerStatusChangeListener(changedServers); } } finally { try { writeLock.unlock(); } catch (Exception e) { // NOPMD } } }
/* ------------------------------------------------------------ */ protected void doStart() throws Exception { if (_server == null) throw new IllegalStateException("No server"); // open listener port open(); super.doStart(); if (_threadPool == null) _threadPool = _server.getThreadPool(); if (_threadPool != _server.getThreadPool() && (_threadPool instanceof LifeCycle)) ((LifeCycle) _threadPool).start(); // Start selector thread synchronized (this) { _acceptorThread = new Thread[getAcceptors()]; for (int i = 0; i < _acceptorThread.length; i++) { if (!_threadPool.dispatch(new Acceptor(i))) { Log.warn("insufficient maxThreads configured for {}", this); break; } } } Log.info("Started {}", this); }
@Test public void testTwoEndPoints() throws Exception { new Thread( () -> { final ArrayList<ServiceDefinition> endpoints = new ArrayList<>(); endpoints.add(DEF); endpoints.add(DEF2); final Server server = new Server(logger, handlerFactory()); server.init(PORT, endpoints, Executors.newSingleThreadExecutor()); }) .start(); final ClientFactory clientFactory = new MultiplexedClientFactory(PORT); final TestService.AsyncIface client = clientFactory.create(DEF, HOSTNAME); final TestResponse response = callTestService(client); logger.info("Received: " + response); assertEquals(response.getResult(), Handler.RESULT); final TestService2.AsyncIface client2 = clientFactory.create(DEF2, HOSTNAME); final TestResponse2 response2 = callTestService2(client2); logger.info("Received: " + response2); assertEquals(response2.getResult(), Handler2.RESULT); clientFactory.close(); }
private void testSampler(final int count, float frequency) { server.setMaxConnections(1); final ArrayList<String> expected = new ArrayList<String>(count); Timeout gen = new Timeout() { Tag tag = new SimpleTag(0); int sent = 0; @Override public void onSample(DatawireEvent e) { String body = template.render(sent); expected.add(body); Message message = Message.Factory.create(); message.setBody(new AmqpValue(body)); DatawireUtils.send(e.getLink(), tag, message); sent += 1; if (sent >= count) { e.getLink().close(); cancel(); } } }; Sender snd = Sender.Builder() .withTarget(server.address()) .withHandlers(new Sampler(gen, frequency)) .create(); reactor.getHandler().add(snd); gen.setTimeout(reactor, 2000); snd.start(reactor); reactor.run(); assertTrue("Sampling timed out", gen.isCancelled()); assertEquals("Expected messages", expected, sink.getMessages()); }