@Override public Map<String, Set<String>> getAttributes(String identifier) throws Exception { if (LOG.isInfoEnabled()) LOG.info("Retrieving attributes for user=" + identifier); // all attributes (name, description) retrieved from esg_ats.xml and esgf_ats_static.xml final Map<String, String> attributes = registryService.getAttributes(); // always request no attributes - i.e. ALL attributes final Set<String> requestedAttributeTypes = new HashSet<String>(); // global list used to avoid double invocations (if more than one attribute is served by the // same attribute service) final List<String> _urls = new ArrayList<String>(); // list of client threads, one for each remote attribute service to be queried List<ClientThread> threads = new ArrayList<ClientThread>(); // loop over attribute types for (final String atype : attributes.keySet()) { final List<URL> aservices = registryService.getAttributeServices(atype); // loop over attribute services for that type for (final URL url : aservices) { String _url = url.toString(); // don't query the same URL twice if (!_urls.contains(_url)) { _urls.add(_url); ClientThread clientThread = new ClientThread(url, identifier, requestedAttributeTypes); clientThread.start(); threads.add(clientThread); } } } // wait for all threads to finish for (Thread thread : threads) { thread.join(); } // global user attributes map final Map<String, Set<String>> map = new HashMap<String, Set<String>>(); // combine all retrieved SAML attributes for (ClientThread thread : threads) { final SAMLAttributes samlAttributes = thread.getSAMLAttributes(); final Map<String, Set<String>> _map = samlAttributes.getAttributes(); for (String key : _map.keySet()) { for (String value : _map.get(key)) { if (StringUtils.hasText(value)) { if (!map.containsKey(key)) { map.put(key, new HashSet<String>()); } map.get(key).add(value); } } } } return map; }
public void execute() { ServerSocket serverSocket = null; Socket socket = null; try { System.out.println("서버 준비 중..."); serverSocket = new ServerSocket(9999); ClientThread clientThread = null; while (true) { System.out.println("클라이언트 대기 중..."); socket = serverSocket.accept(); clientThread = new ClientThread(this, socket); clientThread.start(); clients.add(clientThread); } } catch (Exception e) { e.printStackTrace(); } finally { try { serverSocket.close(); } catch (Exception e) { } } }
private void testDynamicNameRevocation( KeyStore serverKeyStore, KeyStore serverTrustStore, KeyStore clientKeyStore, KeyStore clientTrustStore, String revokeName) throws Exception { logger.info("testRevoke: " + revokeName); Set<String> revokedNames = new ConcurrentSkipListSet(); SSLContext serverSSLContext = RevocableNameSSLContexts.create(serverKeyStore, pass, serverTrustStore, revokedNames); SSLContext clientSSLContext = SSLContexts.create(clientKeyStore, pass, clientTrustStore); ServerThread serverThread = new ServerThread(); try { serverThread.start(serverSSLContext, port, 2); Assert.assertNull(ClientThread.connect(clientSSLContext, port)); Assert.assertNull(serverThread.getErrorMessage()); revokedNames.add(revokeName); logger.debug("revokedNames: " + revokedNames); Thread.sleep(1000); Assert.assertNotNull(ClientThread.connect(clientSSLContext, port)); Assert.assertNotNull(serverThread.getErrorMessage()); } finally { serverThread.close(); serverThread.join(1000); } }
public static void main(String[] args) throws Exception { Properties properties = new Properties(); FileInputStream propFile = new FileInputStream("store.properties"); properties.load(propFile); final String id = properties.getProperty("ID"); final String placeForFiles = properties.getProperty("FilePlace"); int servicePort = Integer.parseInt(properties.getProperty("ServicePort")); int tcpPort = Integer.parseInt(properties.getProperty("TCPPort")); String ksName = properties.getProperty("KeyStore"); KeyStore ks = KeyStore.getInstance(properties.getProperty("KeyStoreType")); char[] password = properties.getProperty("Password").toCharArray(); char[] passwordForKey = properties.getProperty("PasswordForKey").toCharArray(); ks.load(new FileInputStream(ksName), password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passwordForKey); SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), null, null); SSLServerSocketFactory ssf = context.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(tcpPort); ServiceThread serviceThread = new ServiceThread(servicePort, id); serviceThread.start(); while (!serverSocket.isClosed()) { ClientThread client = new ClientThread(placeForFiles); SSLSocket socket = (SSLSocket) serverSocket.accept(); socket.startHandshake(); client.setSocket(socket); client.start(); } }
Server() { // Maak een socket aan om op clients te wachten ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(SERVER_PORT); System.out.println("Socket aangemaakt"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Wacht op binnenkomende client connectie requests. while (true) { try { Socket socket = serverSocket.accept(); verbonden.add(socket); System.out.println(verbonden.size()); // Als er een verbinding tot stand is gebracht, start een nieuwe // thread. ClientThread ct = new ClientThread(socket); System.out.println("Verbinding tot stand gebracht met client!"); ct.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // start de thread en roept run() aan. Gebruik hier niet // run(): dan wordt de code in de huidige thread gedraaid. } }
/* * 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; } } } }
private void doQuery(String cmd) { // if(cmd.charAt(0) == ' ') cmd = cmd.substring(1); cmd = cmd.trim(); if (onlineUsers.containsKey(cmd)) { ClientThread c = (ClientThread) onlineUsers.get(cmd); writeLine("CHAT *** " + c.getNickname() + " is from " + c.getRemoteAddr() + " ***"); } else { writeLine("CHAT *** " + cmd + " is UNKNOWN ***"); } } // doQuery
private void doMsg(String cmd) { cmd = cmd.trim(); int pos = cmd.indexOf(' '); // find tell whom if (pos < 0) return; // no message on the line String dst = cmd.substring(0, pos); String msg = cmd.substring(pos + 1); msg = msg.trim(); if (msg == null) msg = " "; if (onlineUsers.containsKey(dst)) { ClientThread c = (ClientThread) onlineUsers.get(dst); c.writeLine("*** [" + myName + "] " + msg); } else { writeLine("CHAT *** " + dst + " not in the ROOM ***"); } }
public void stop() { if (thread != null) { thread.stop(); thread = null; } try { if (console != null) console.close(); if (streamOut != null) streamOut.close(); if (socket != null) socket.close(); } catch (IOException ioe) { System.out.println("Error closing ..."); } client.close(); client.stop(); }
public void sendMessageToServer(String msg) { try { clientThread.send(msg); } catch (Exception e) { e.printStackTrace(); } }
public void registerUser(String nickname, String password, String name, String surname) { User user = new User(nickname, password, name, surname); Gson gson = new Gson(); String json = gson.toJson(user); // impacchetto user clientThread.sendToServerForRegistration(json); }
public void loginUser(String nickname, String password) { User user = new User(nickname, password); // LOGGING_USER Gson gson = new Gson(); String json = gson.toJson(user); clientThread.sendToServerForLogin(json); // clientThread.sendToServerForRegistration(json); }
public void userLogged(String serPrefs) { Gson gs = new Gson(); prefs = gs.fromJson(serPrefs, Preferences.class); clientThread.setUser(prefs.getUser()); Platform.runLater( new Runnable() { @Override public void run() { loginStage.hide(); loginStage.close(); /* clientController.welcomeLabel.setText("Bentornato, "+prefs.getUser().getNickname()); clientController.launchToMessagging(); clientController.regLabel.setVisible(false); clientController.loginButton.setText("LOGOUT"); clientController.registerButton.setVisible(false); clientController.registerButton.setDisable(true); */ isClientLogged = true; clientController.loginButton.setDisable(true); clientController.registerButton.setDisable(true); clientController.clientConnectButton.setVisible(false); clientController.welcomeLabel.setFont(robo); clientController.welcomeLabel.setText( "Bentornato, " + prefs.getUser().getNickname() + "!"); clientController.scuolaBox.setSelected(prefs.isScuola()); clientController.makingBox.setSelected(prefs.isMaking()); clientController.religioneBox.setSelected(prefs.isReligione()); clientController.promozione_territorioBox.setSelected(prefs.isPromozione_territorio()); clientController.donazione_sangueBox.setSelected(prefs.isDonazione_sangue()); clientController.anzianiBox.setSelected(prefs.isAnziani()); clientController.tasseBox.setSelected(prefs.isTasse()); } }); }
public void sendReport(String msg) { Reporting report = new Reporting(msg, prefs.getUser()); Gson gson = new Gson(); String repo = gson.toJson(report); clientThread.sendReport(repo); System.out.println("IL report: " + report.getUser().getNickname() + " " + report.getMsg()); }
private static boolean checkStatus() throws Exception { // Connect to Master and check if all the test operations are reproduced by Master successfully. for (ClientThread clientThread : sClientThreadList) { ClientOpType opType = clientThread.getOpType(); String workDir = clientThread.getWorkDir(); int successNum = clientThread.getSuccessNum(); LOG.info( "Expected Status: OpType[{}] WorkDir[{}] SuccessNum[{}].", opType, workDir, successNum); for (int s = 0; s < successNum; s++) { TachyonURI checkURI = new TachyonURI(workDir + s); if (ClientOpType.CREATE_FILE == opType) { try { sTfs.open(checkURI); } catch (Exception e) { // File not exist. This is unexpected for CREATE_FILE. LOG.error("File not exist for create test. Check failed! File: {}", checkURI); return false; } } else if (ClientOpType.CREATE_DELETE_FILE == opType) { try { sTfs.open(checkURI); } catch (Exception e) { // File not exist. This is expected for CREATE_DELETE_FILE. continue; } LOG.error("File exists for create/delete test. Check failed! File: {}", checkURI); return false; } else if (ClientOpType.CREATE_RENAME_FILE == opType) { try { sTfs.open(new TachyonURI(checkURI + "-rename")); } catch (Exception e) { // File not exist. This is unexpected for CREATE_RENAME_FILE. LOG.error( "File not exist for create/rename test. Check failed! File: {}-rename", checkURI); return false; } } // else if (ClientOpType.CREATE_TABLE == opType) { // if (tfs.getRawTable(new TachyonURI(workDir + s)).getId() == -1) { // tfs.close(); // return false; // } // } } } return true; }
protected boolean sendMessage(String message) { boolean bSend = false; if (mThread != null) { bSend = mThread.sendMessage(message); Log.v(TAG, "send messge-->" + message + ", bSend:" + bSend); } return bSend; }
/* * 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 void updatePrefences( boolean scuola, boolean making, boolean religione, boolean promozione_territorio, boolean donazione_sangue, boolean anziani, boolean tasse) { prefs = new Preferences( scuola, making, religione, promozione_territorio, donazione_sangue, anziani, tasse); prefs.setUser(clientThread.getUser()); // System.err.println("UTENTE: // "+prefs.getUser().getUsername()+prefs.getUser().getSurname());//TODO: non ho username etc Gson gson = new Gson(); String json = gson.toJson(prefs); clientThread.updatePrefs(json); }
public void stop() { Log.v(TAG, "invoke stop <<<<<<<<<<<<<<<<<<<<<<<<<<"); if (mIsStarted) { Log.v(TAG, " stop the client <<<<<<<<<<<<<<<<<<<<<<<<<<"); // mThread.interrupt(); mThread.quit(); mThread = null; mIsStarted = false; } }
public void start() { keepGoing = true; /* create socket server and wait for connection requests */ try { // the socket used by the server ServerSocket serverSocket = new ServerSocket(port); // infinite loop to wait for connections while (keepGoing) { // format message saying we are waiting display("Server menunggu koneksi Client pada port " + port + "."); Socket socket = serverSocket.accept(); // accept connection // if I was asked to stop if (!keepGoing) break; ClientThread t = new ClientThread(socket); // make a thread of it al.add(t); // save it in the ArrayList t.start(); } // I was asked to stop try { serverSocket.close(); for (int i = 0; i < al.size(); ++i) { ClientThread tc = al.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); } catch (IOException ioE) { // not much I can do } } } catch (Exception e) { display("Exception closing the server and clients: " + e); } } // something went bad catch (IOException e) { String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n"; display(msg); } }
public void close() { try { System.out.println("Removing observer #" + number); server.removeObserver(this); System.out.println("Closing client #" + number); clientThread.interrupt(); inputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
@Test public void singleMasterJournalCrashIntegrationTest() throws Exception { LocalTachyonCluster cluster = setupSingleMasterCluster(); CommonUtils.sleepMs(TEST_TIME_MS); // Shutdown the cluster cluster.stopTFS(); CommonUtils.sleepMs(TEST_TIME_MS); // Ensure the client threads are stopped. mExecutorsForClient.shutdown(); mExecutorsForClient.awaitTermination(TEST_TIME_MS, TimeUnit.MILLISECONDS); reproduceAndCheckState(mCreateFileThread.getSuccessNum()); // clean up cluster.stopUFS(); }
/** * Runs the client threads in the parallel test. * * @param clients The threads to run. * @return The time taken to run the threads. * @throws InterruptedException if a thread is interrupted. */ private double runClients(List<ClientThread> clients) throws InterruptedException { Date testStart = new Date(); // Execute threads. for (ClientThread client : clients) { client.start(); } // Block until clients are done. boolean isComplete = false; while (!isComplete) { isComplete = true; for (ClientThread client : clients) { isComplete = isComplete && !client.isAlive(); } // Prevent busy wait. if (!isComplete) { Thread.sleep(500); } } Date testEnd = new Date(); return testEnd.getTime() - testStart.getTime(); }
public void run() { try { ServerSocket serverSocket = new ServerSocket(7497); // infinite loop to wait for connections while (true) { log.info("Server waiting for Clients on port " + 7497); Socket socket = serverSocket.accept(); // accept connection log.info( " Connection Received from " + socket.getInetAddress() + " on port " + socket.getPort() + " to port " + socket.getLocalPort() + " of " + socket.getLocalAddress()); sInput = new DataInputStream(socket.getInputStream()); sOutput = new DataOutputStream(socket.getOutputStream()); MessageSender.instance.setup(sOutput); ClientThread t = new ClientThread(sInput); t.start(); // int version = sInput.read(); // log.info(version); write("76".getBytes()); // Send Server Id write("Test Time".getBytes()); // Send Test Time // int ClientId = sInput.read(); //Client Id // log.info(ClientId); } } catch (Exception e) { log.warn(e); } }
public static void main(String[] args) { Channel channel = new Channel(5); channel.startWorkers(); ClientThread alice = new ClientThread("Alice", channel); ClientThread bobby = new ClientThread("Bobby", channel); ClientThread chris = new ClientThread("Chris", channel); alice.start(); bobby.start(); chris.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } alice.stopThread(); bobby.stopThread(); chris.stopThread(); channel.stopAllWorkers(); }
public void stop() { try { if (thread != null) thread = null; if (console != null) console.close(); if (streamIn != null) streamIn.close(); if (streamOut != null) streamOut.close(); if (socket != null) socket.close(); this.socket = null; this.console = null; this.streamIn = null; this.streamOut = null; } catch (IOException ioe) { System.out.println(ioe.getMessage()); } client.close(); }
public void creaClient() { try { clientSocket = new Socket(hostname, port); // ISTANZIO CLIENT SOCKET } catch (IOException e) { e.printStackTrace(); } clientThread = new ClientThread( clientSocket, this); // nuovo clientThread, gli passo il client socket e il client main clientThread.start(); Platform.runLater( new Runnable() { @Override public void run() { clientController.clientConnectButton.setDisable(true); } }); }
@Ignore @Test public void multiMasterJournalCrashIntegrationTest() throws Exception { LocalTachyonClusterMultiMaster cluster = setupMultiMasterCluster(); // Kill the leader one by one. for (int kills = 0; kills < TEST_NUM_MASTERS; kills++) { CommonUtils.sleepMs(TEST_TIME_MS); Assert.assertTrue(cluster.killLeader()); } cluster.stopTFS(); CommonUtils.sleepMs(TEST_TIME_MS); // Ensure the client threads are stopped. mExecutorsForClient.shutdown(); while (!mExecutorsForClient.awaitTermination(TEST_TIME_MS, TimeUnit.MILLISECONDS)) {} reproduceAndCheckState(mCreateFileThread.getSuccessNum()); // clean up cluster.stopUFS(); }
public ChatClient(Subject server, Socket socket) throws IOException { this.server = server; counter++; number = counter; this.socket = socket; // run new thread for listening server System.out.println("New ChatClient #" + number + " created"); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); // TODO получение имени клиента вставить здесь // authorize(); clientThread = new ClientThread(); clientThread.start(); }
private void testConnection( KeyStore serverKeyStore, KeyStore serverTrustStore, KeyStore clientKeyStore, KeyStore clientTrustStore) throws Exception { SSLContext serverSSLContext = SSLContexts.create(serverKeyStore, pass, serverTrustStore); SSLContext clientSSLContext = SSLContexts.create(clientKeyStore, pass, clientTrustStore); ServerThread serverThread = new ServerThread(); try { serverThread.start(serverSSLContext, port, 1); String clientErrorMessage = ClientThread.connect(clientSSLContext, port); Assert.assertNull(clientErrorMessage); Assert.assertNull(serverThread.getErrorMessage()); } finally { serverThread.close(); } }