/* * to broadcast a private message to all Clients */ private synchronized void broadcastOnlyOne(String message, ChatMessage cm) { // add HH:mm:ss and \n to the message String time = sdf.format(new Date()); String messageLf = time + " " + message + "\r\n"; System.out.print(messageLf); serverGUI.serverTextArea.append(messageLf); // we loop in reverse order in case we would have to remove a Client // because it has disconnected for (int i = al.size(); --i >= 0; ) { ClientThread ct = al.get(i); // try to write to the Client if it fails remove it from the list if (cm.getType() == ChatMessage.ESTABLISHCONNECTION || cm.getType() == ChatMessage.ESTABLISHCONNECTIONANDPLAY) { if (cm.getTO().equalsIgnoreCase(ct.username) && !ct.writeMsg(cm)) { al.remove(i); display("Disconnected Client " + ct.username + " removed from list."); break; } } else { if (cm.getTO().equalsIgnoreCase(ct.username) && !ct.writeMsg(message)) { al.remove(i); display("Disconnected Client " + ct.username + " removed from list."); break; } } } }
public Mapa(String w, String h, String s, String j) { WIDTH = Integer.parseInt(w); HEIGHT = Integer.parseInt(h); SCALE = Integer.parseInt(s); numGamers = Integer.parseInt(j); hacerJugadores(); if (Integer.parseInt(j) != 4) { switch (Integer.parseInt(j)) { case 1: jugadores.remove(1); jugadores.remove(1); jugadores.remove(1); break; case 2: jugadores.remove(1); jugadores.remove(1); break; case 3: jugadores.remove(1); break; default: break; } } restriccion = lectura(Integer.parseInt(w), Integer.parseInt(h), Integer.parseInt(s)); }
public synchronized void removeClientData(ClientData cd) { try { clientList.remove(cd); clientList.trimToSize(); sendList(); } catch (IOException e) { e.printStackTrace(); } }
// for a client who logoff using the LOGOUT message synchronized void remove(int id) { // scan the array list until we found the Id for (int i = 0; i < al.size(); ++i) { ClientThread ct = al.get(i); // found it if (ct.id == id) { al.remove(i); return; } } }
/** * Gets the list of the vnmrj users(operators) for the current unix user logged in * * @return the list of vnmrj users */ protected Object[] getOperators() { String strUser = System.getProperty("user.name"); User user = LoginService.getDefault().getUser(strUser); ArrayList<String> aListOperators = user.getOperators(); if (aListOperators == null || aListOperators.isEmpty()) aListOperators = new ArrayList<String>(); Collections.sort(aListOperators); if (aListOperators.contains(strUser)) aListOperators.remove(strUser); aListOperators.add(0, strUser); return (aListOperators.toArray()); }
/** {@inheritDoc} */ public void removeHostListener(HostListener listener) { /* * XXX: if a disconnect method is added, make sure it calls * this method to unregister this object from the watcher. otherwise, * an unused MonitoredHostProvider instance may go uncollected. */ synchronized (listeners) { listeners.remove(listener); if (listeners.isEmpty() && (task != null)) { task.cancel(); task = null; } } }
public void RegretChess() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (cell[i][j].changed == true) { cell[i][j].ChangeBack(); } turn = TakeTurn(); try { stateList.remove(stateList.size() - 1); takenList.remove(takenList.size() - 1); char[][] states = stateList.get(stateList.size() - 1); boolean[][] takens = takenList.get(takenList.size() - 1); for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cell[i][j].state = states[i][j]; cell[i][j].taken = takens[i][j]; cell[i][j].repaint(); } for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (cell[i][j].taken == false) { CheckPlace(cell[i][j]); if (canPut) { cell[i][j].ChangeBackground(); canPut = false; } } } catch (ArrayIndexOutOfBoundsException e1) { JOptionPane.showMessageDialog(null, "æ— æ³•æ‚”æ£‹"); } if (stateList.size() == 0) { RememberState(); } }
/* * to broadcast a message to all Clients */ private synchronized void broadcast(String message) { // add HH:mm:ss and \n to the message String time = sdf.format(new Date()); String messageLf = time + " " + message + "\n"; System.out.print(messageLf); serverGUI.serverTextArea.append(messageLf); // we loop in reverse order in case we would have to remove a Client // because it has disconnected for (int i = al.size(); --i >= 0; ) { ClientThread ct = al.get(i); // try to write to the Client if it fails remove it from the list if (!ct.writeMsg(messageLf)) { al.remove(i); display("Disconnected Client " + ct.username + " removed from list."); } } }
public static Result textSelList(Element elsPar, ArrayList<String> jsoupSelectors) { Result res = new Result(); Elements els; Elements elsTemp; els = elsPar.select(jsoupSelectors.remove(0)); for (String sel : jsoupSelectors) { elsTemp = els.select(sel); if (elsTemp != null) els = elsTemp; } if (els == null || els.size() != 1) { log.error("jsoup selector on elements does not match 1"); System.exit(1); return res.setContinua(false); } return res.setRetStr(els.get(0).text()); }
protected synchronized Message receiveMessage() throws IOException { if (messageBuffer.size() > 0) { Message m = (Message) messageBuffer.get(0); messageBuffer.remove(0); return m; } try { InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer); if (remoteAddress != null) { int len = receiveBuffer.position(); receiveBuffer.rewind(); receiveBuffer.get(buf, 0, len); try { IP address = IP.fromInetAddress(remoteAddress.getAddress()); int port = remoteAddress.getPort(); extractor.appendData(buf, 0, len, new SocketDescriptor(address, port)); receiveBuffer.clear(); extractor.updateAvailableMessages(); return extractor.nextMessage(); } catch (EOFException exc) { exc.printStackTrace(); System.err.println(buf.length + ", " + len); } catch (InvocationTargetException exc) { exc.printStackTrace(); } catch (IllegalAccessException exc) { exc.printStackTrace(); } catch (InstantiationException exc) { exc.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvalidCompressionMethodException e) { e.printStackTrace(); } } } catch (ClosedChannelException exc) { if (isKeepAlive()) { throw exc; } } return null; }
public void removethread(ServerThread st) { clientList.remove(st); clientList.trimToSize(); }
/** * Asks the user for a card in their hand to play. This method handles all possiblities of invalid * input and invalid card, as well as choosing cards that are not in player's hand. * * @param ArrayList<CardFamily> requiredFamilies Required families. Use null if there is no * required family. * @return Card Card selected by player. */ private Card askForCard(ArrayList<CardFamily> requiredFamilies) { boolean familyIsCorrect = (!this.hand.hasOfFamily(requiredFamilies)) ? true : false; boolean userIsSure = false; Card card = null; // Start confirmation check do { boolean inputWasCorrect = false; this.output().println("\nYour hand:\n"); this.output().println(this.hand); this.output().println(this.name() + ", what card do you want to play?"); // Start hand check do { boolean cardWasCorrect = false; // Start card check do { int value = -1; String family = ""; // Start syntax check do { try { if (this.hand.hasOfFamily(requiredFamilies)) { String alert = "\nRebember: You have to play a card of "; for (int _i = 0; _i < requiredFamilies.size(); _i++) { alert += requiredFamilies.get(_i); if (_i + 2 < requiredFamilies.size()) alert += ", "; else if (_i + 1 < requiredFamilies.size()) alert += " or "; } this.output().println(alert + "."); } // this.output().println( "\n\tValue (S=10, C=11, R=12): " ); this.output().println("\n\tValue (1-7, S, C, R): "); char val = this.input().nextLine().trim().charAt(0); if (val >= 49 && val <= 55) value = (int) (val - 48); else { switch (val) { case 'S': // Trama: si sale la mayuscula, ejecuta hasta la minuscula y ahorro // repetir lineas xD case 's': value = 10; break; case 'C': case 'c': value = 11; break; case 'R': case 'r': value = 12; break; default: throw new Exception(); // si no es ni un numero ni una de estas letras, lanzo // Exception } } // value = this.input().nextInt(); this.output().println("\n\tFamily (Oros, Copas, Bastos, Espadas): "); char fam = this.input().nextLine().trim().charAt(0); switch (fam) { case 'O': // Trama: si sale la mayuscula, ejecuta hasta la minuscula y ahorro // repetir lineas xD case 'o': family = "oros"; break; case 'C': case 'c': family = "copas"; break; case 'B': case 'b': family = "bastos"; break; case 'E': case 'e': family = "espadas"; break; default: throw new Exception(); // si no es una de estas letras, lanzo Exception } // family = this.input().nextLine().trim(); inputWasCorrect = true; } catch (NoSuchElementException nsee) { ArrayList<Player> otherPlayers = new ArrayList<Player>(ServerApp.match().players()); otherPlayers.remove(this); ServerApp.match() .sendToSomePlayers( this.name() + " has been disconnected. The match is finished.", otherPlayers); ServerApp.match().finishGame(); } catch (Exception e) { this.output() .println( "Invalid syntax, try again. Rembember that the syntax is {value} {family}, for instance: 7 espadas."); inputWasCorrect = false; } if (this.hand.hasOfFamily(requiredFamilies) && inputWasCorrect) { try { inputWasCorrect = requiredFamilies.contains(new CardFamily(family)); } catch (Exception icfe) { inputWasCorrect = false; } } } while (!inputWasCorrect); // End syntax check inputWasCorrect = false; try { card = new Card(value, family); cardWasCorrect = true; } catch (Exception e) { this.output() .println( "That card ( " + value + " of " + family + " ) does not exist. Rembember that the syntax is {value} {family}, for instance: 7 espadas"); } } while (!cardWasCorrect); // End card check if (!this.hand.has(card)) { this.output().println("That card is not in your hand!"); } } while (!this.hand.has(card)); // End hand check userIsSure = askForBoolean( "=====\nAre you sure that you want to play this card?\n\n" + card + "\n\n=====\n"); } while (!userIsSure); // End confirmation check this.hand.removeCard(card); return card; }
/** The run method. */ public void run() { instances.add(this); try { listener.startUnpack(); String currentOs = System.getProperty("os.name").toLowerCase(); // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); String fname = pathFile.getName(); int z = fname.length(); File dest = pathFile.getParentFile(); if (!dest.exists()) dest.mkdirs(); // We add the path to the log, udata.addFile(path); listener.progressUnpack(j, path); // if this file exists and shouldnot override skip this file if (((pf.override == false) && (pathFile.exists()))) { objIn.skip(pf.length); continue; } // We copy the file out = new FileOutputStream(path); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0) javax.swing.JOptionPane.showMessageDialog( null, "The installation was not completed.", "Installation warning", javax.swing.JOptionPane.WARNING_MESSAGE); // We put the uninstaller putUninstaller(); // The end :-) listener.stopUnpack(); } catch (Exception err) { listener.stopUnpack(); listener.errorUnpack(err.toString()); } instances.remove(instances.indexOf(this)); }
@SuppressWarnings({"unchecked", "rawtypes"}) public static void main(String[] args) throws IOException { boolean useArguments = false; Map config = null; try { yamlInstance = new Yaml(); /* * Try to load configuration file */ FileReader configFile = new FileReader(YAML_PATH + CONFIGURATION_FILE); config = (Map) yamlInstance.load(configFile); } catch (FileNotFoundException e) { System.out.println( "Could not load configuration file. Using program " + "arguments instead."); useArguments = true; } /* Scan for program arguments */ int port = -1; try { if (useArguments) port = Integer.parseInt(args[0]); else // take the port number from the config file port = (Integer) config.get("port"); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("DungeonServer: specify a port to which to bind"); System.out.println(usage()); System.exit(1); } /* Attempt to bind to port */ ServerSocket server = null; try { server = new ServerSocket(port); } catch (IOException e) { System.err.printf("DungeonServer: could not listen on port %d\n", port); System.exit(2); } System.out.printf("bound to port %d\n", port); System.out.println("loading universe:"); /* Load universe */ try { System.out.println("\tfinding universe file"); FileReader universeFile = null; if (useArguments) universeFile = new FileReader(YAML_PATH + DEFAULT_UNIVERSE_FILE); else universeFile = new FileReader(YAML_PATH + config.get("world") + ".universe.yml"); Object[] docs = new Object[3]; Map<String, Object> preamble = null; Map<String, Map<String, Object>> rooms = null, items = null; try { System.out.println("\tchecking universe file"); int i = 0; for (Object o : yamlInstance.loadAll(universeFile)) docs[i++] = o; preamble = (Map<String, Object>) docs[0]; rooms = (Map<String, Map<String, Object>>) docs[1]; items = (Map<String, Map<String, Object>>) docs[2]; if (preamble == null || rooms == null || items == null) throw new NullPointerException(); } catch (ArrayIndexOutOfBoundsException e) { System.err.println( "DungeonServer: error parsing universe " + "file: too many documents in universe file"); System.exit(3); } catch (NullPointerException e) { System.err.println( "DungeonServer: error parsing universe " + "file: too few documents in universe file"); System.exit(3); } /* * Used after parsing rooms to set universe parameters */ boolean doWeather = false; String spawnRoomID = null; int timescale = -1; try { System.out.println("\treading preamble"); /* * Load universe parameters from the preamble */ doWeather = (Boolean) validateAndGet(preamble, "weather", Boolean.class); spawnRoomID = (String) validateAndGet(preamble, "spawn", String.class); timescale = (Integer) validateAndGet(preamble, "timescale", Integer.class); } catch (Exception e) { System.err.println("DungeonServer: failed parsing preamble (" + e.getMessage() + ")"); System.exit(4); } /* * Loop through room definitions in universe file */ /** * This hash map is used to resolve references from one room to another. Each time a room is * parsed, it is added to this map, and henceforth back references to the newly added room * will be resolved by checking this map. */ HashMap<String, Room> knownRooms = new HashMap<String, Room>(); /** * This list is maintained to easily check at the end of parsing if there are still references * to unseen rooms. */ ArrayList<String> unseenRooms = new ArrayList<String>(); /** * This is a list of triples (A, B, C) such that A is a room waiting for a reference to * another room, C, through a direction B. For A and B, the string ID of the rooms are used * (the same key used in the knownRooms hash map). This list is used whenever a room's exit * references cannot actually be resolved because the destination room has not yet been * parsed. At the end of parsing, as long as the unseenRooms list is empty, this list is * traversed to resolve the remaining references. */ ArrayList<Triple<String, Direction, String>> unresolved; unresolved = new ArrayList<Triple<String, Direction, String>>(); String thisRoomID = null; try { System.out.println("\tparsing rooms"); for (Map.Entry<String, Map<String, Object>> m : rooms.entrySet()) { thisRoomID = m.getKey(); Map<String, Object> thisMap = m.getValue(); String roomName = (String) validateAndGet(thisMap, "name", String.class); String description = (String) validateAndGet(thisMap, "description", String.class); Hashtable<Pair<DayPart, Weather>, String> details; details = getDetails(thisMap); Room r = new Room(roomName, description, details); if (thisMap.containsKey("neverUseArticle")) { boolean neverUseArticle = (Boolean) validateAndGet(thisMap, "neverUseArticle", Boolean.class); r.setNeverUseArticle(neverUseArticle); } if (unseenRooms.contains(thisRoomID)) unseenRooms.remove(thisRoomID); knownRooms.put(thisRoomID, r); /* * Process exits out of this room */ Map<String, String> exits = (Map) validateAndGet(thisMap, "exits", Map.class); for (Map.Entry<String, String> exit : exits.entrySet()) { String thisDirection = exit.getKey(); String toRoomID = exit.getValue(); /* * Verify the direction from the file */ Direction dir; dir = Direction.fromString(thisDirection); if (dir == null) throw new InvalidDirectionException(thisDirection); /* * Look up the destination room in the hash map */ if (knownRooms.containsKey(toRoomID)) r.addExit(dir, knownRooms.get(toRoomID)); else { if (!unseenRooms.contains(toRoomID)) unseenRooms.add(toRoomID); Triple<String, Direction, String> t; t = new Triple<String, Direction, String>(thisRoomID, dir, toRoomID); unresolved.add(t); } } } } catch (Exception e) { System.err.println( "DungeonServer: failed parsing room '" + thisRoomID + "' (" + e.getMessage() + ")"); System.exit(4); } if (!unseenRooms.isEmpty()) throw new UnresolvedReferenceException(unseenRooms); /* * Invariant: There were no references to undefined rooms in the * file. Invariant: All the rooms in the file have been * instantiated. * * All rooms in the universe file have been parsed, but there may * still be exits waiting to be added because their destination was * not yet parsed at the time. Now loop through the unresolved list * to set them up. */ for (Triple<String, Direction, String> t : unresolved) { Room fromRoom = knownRooms.get(t.first); Room toRoom = knownRooms.get(t.third); Direction dir = t.second; fromRoom.addExit(dir, toRoom); } /* * Invariant: All exits in the file have been set up among the * rooms. */ Room spawnRoom = knownRooms.get(spawnRoomID); universe = new DungeonUniverse(spawnRoom, doWeather, timescale, knownRooms.values()); universeFile.close(); } catch (Exception e) { System.err.println("DungeonServer: failed loading universe " + "(" + e.getMessage() + ")"); System.exit(2); } System.out.println("loaded universe"); /* Start narrator */ try { narrator = new DungeonNarrator(); } catch (Exception e) { System.err.println("DungeonServer: failed starting narrator"); System.exit(3); } System.out.println("started narrator"); /* Start the game tick */ try { tick = new DungeonGameTick(); tick.start(); } catch (Exception e) { System.err.println("DungeonServer: failed starting game tick"); System.exit(3); } System.out.println("started game tick"); /* Start accepting events */ try { events = new DungeonDispatcher(); events.start(); } catch (Exception e) { System.err.println("DungeonServer: failed starting event queue"); System.exit(3); } System.out.println("started event queue"); /* Listen for clients */ try { System.out.println("listening for clients"); while (true) new DungeonConnectionThread(server.accept()).start(); } catch (IOException e) { System.err.printf("DungeonServer: failed accepting client on port %d\n", port); System.exit(2); } finally { server.close(); } }
public void removeIRCRawDataListener(IRCRawDataListener l) { if (rawDataListeners.contains(l)) { rawDataListeners.remove(l); } }
// Connects to server, starts a NetThread, then waits for messages. public static void main(String[] args) { int port = -1; String host = null; if (args.length >= 3) { name = args[0]; host = args[1]; try { port = Integer.parseInt(args[2]); } catch (Exception e) { port = -1; } } if (port == (-1)) { io.p("What server would you like to connect to? "); host = io.readLine(); io.p("What port would you like to connect on? "); port = io.readInt(); if ((port < 1) || (port > 65535)) { io.pl("Invalid port number."); System.exit(1); } } io.pl("Connecting to " + host + ":" + port + "..."); Socket s = null; try { s = new Socket(host, port); } catch (Exception e) { io.pl("Couldn't connect to that server."); UIWindow.alert(null, "Couldn't connect to that server."); System.exit(1); } server = new NetThread(s, al, -1); io.pl("Connected to server."); Message nameMessage = new Message(Message.SET_NAME, name, null); server.sendMessage(nameMessage); while (true) { synchronized (al) { if (haveMessages()) { Message m = null; m = al.get(0); al.remove(0); handleMessage(m); } else { try { al.wait(); } catch (Exception e) { io.pl("An exception occurred while trying to wait for messages from the server."); UIWindow.alert(null, "AI Client error occurred."); System.exit(1); } } } } }
public void removeIRCAuthListener(IRCAuthListener l) { if (authListeners.contains(l)) { authListeners.remove(l); } }
public void addPoint(long handId, PVector handPoint) { ArrayList curList = getPointList(handId); curList.add(0, handPoint); if (curList.size() > _maxPoints) curList.remove(curList.size() - 1); }
/* space ship has died from some sort of collision */ public void kill(ArrayList movingObjects) { int index = movingObjects.indexOf(this); movingObjects.remove(index); }