List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:MyZone.Settings.java
public boolean retrieveCert() { while (true) { try {/*from w w w . ja va2 s.com*/ Socket toCAServer = new Socket(globalProperties.caAddress, globalProperties.caPort); toCAServer.setSoTimeout(IDLE_LIMIT); byte[] usernameBytes = username.getBytes("UTF-8"); DataOutputStream outToCAServer = new DataOutputStream(toCAServer.getOutputStream()); byte[] buffer = new byte[usernameBytes.length + 4]; int len = 0; System.arraycopy(intToByteArray(usernameBytes.length), 0, buffer, len, 4); len += 4; System.arraycopy(usernameBytes, 0, buffer, len, usernameBytes.length); outToCAServer.write(buffer, 0, buffer.length); outToCAServer.flush(); int i = 0; byte[] lenBytes = new byte[4]; while (i < 4) { i += toCAServer.getInputStream().read(lenBytes, i, 4 - i); if (i < 0) { if (DEBUG) { System.out.println("DEBUG: line 2529 of Settings.java"); } } try { Thread.sleep(100); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } } len = byteArrayToInt(lenBytes); byte[] certBytes = new byte[len]; i = 0; while (i < len) { i += toCAServer.getInputStream().read(certBytes, i, len - i); if (i < 0) { if (DEBUG) { System.out.println("DEBUG: line 2555 of Settings.java"); } len = 4; break; } try { Thread.sleep(100); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } } if (len == 4) { Thread.sleep(30000); outToCAServer.close(); toCAServer.close(); continue; } outToCAServer.close(); toCAServer.close(); globalProperties.caCertPath = prefix + "/CAs/"; CertVerifier y = new CertVerifier(); userCertificate uc = y.verifyCertificate(certBytes, globalProperties.caCertPath, globalProperties.keyPairAlgorithm, globalProperties.certSigAlgorithm); if (uc == null) { Thread.sleep(30000); continue; } File file = new File(prefix + username + "/cert/" + username + ".cert"); FileOutputStream fos = new FileOutputStream(file); fos.write(certBytes); fos.flush(); fos.close(); outToCAServer.close(); toCAServer.close(); return true; } catch (Exception e) { if (DEBUG) e.printStackTrace(); } } }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * @since 3.1/* ww w . j a va2 s . c o m*/ */ protected InputStream _retrieveFileStream(String command, String remote) throws IOException { Socket socket = _openDataConnection_(command, remote); if (socket == null) { return null; } InputStream input = socket.getInputStream(); if (__fileType == ASCII_FILE_TYPE) { // We buffer ascii transfers because the buffering has to // be interposed between FromNetASCIIOutputSream and the underlying // socket input stream. We don't buffer binary transfers // because we don't want to impose a buffering policy on the // programmer if possible. Programmers can decide on their // own if they want to wrap the SocketInputStream we return // for file types other than ASCII. input = getBufferedInputStream(input); input = new FromNetASCIIInputStream(input); } return new org.apache.commons.net.io.SocketInputStream(socket, input); }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * @since 3.1// w w w. jav a 2s.c om */ protected boolean _retrieveFile(String command, String remote, OutputStream local) throws IOException { Socket socket = _openDataConnection_(command, remote); if (socket == null) { return false; } InputStream input = getBufferedInputStream(socket.getInputStream()); if (__fileType == ASCII_FILE_TYPE) { input = new FromNetASCIIInputStream(input); } CSL csl = null; if (__controlKeepAliveTimeout > 0) { csl = new CSL(this, __controlKeepAliveTimeout, __controlKeepAliveReplyTimeout); } // Treat everything else as binary for now try { Util.copyStream(input, local, getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE, __mergeListeners(csl), false); } finally { Util.closeQuietly(input); Util.closeQuietly(socket); if (csl != null) { csl.cleanUp(); // fetch any outstanding keepalive replies } } // Get the transfer response boolean ok = completePendingCommand(); return ok; }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String RegisterTheDevice(String sSrvr, String sPort, String sData) { String sRet = ""; String line = ""; // Debug.waitForDebugger(); if (sSrvr != null && sPort != null && sData != null) { try {//from ww w . j av a 2 s. c o m int nPort = Integer.parseInt(sPort); Socket socket = new Socket(sSrvr, nPort); PrintWriter out = new PrintWriter(socket.getOutputStream(), false); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println(sData); if (out.checkError() == false) { socket.setSoTimeout(30000); while (socket.isInputShutdown() == false) { line = in.readLine(); if (line != null) { line = line.toLowerCase(); sRet += line; // ok means we're done if (line.contains("ok")) break; } else { // end of stream reached break; } } } out.close(); in.close(); socket.close(); } catch (NumberFormatException e) { sRet += "reg NumberFormatException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } catch (UnknownHostException e) { sRet += "reg UnknownHostException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } catch (IOException e) { sRet += "reg IOException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } } return (sRet); }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * Obtain a list of filenames in a directory (or just the name of a given * file, which is not particularly useful). This information is obtained * through the NLST command. If the given pathname is a directory and * contains no files, a zero length array is returned only * if the FTP server returned a positive completion code, otherwise * null is returned (the FTP server returned a 550 error No files found.). * If the directory is not empty, an array of filenames in the directory is * returned. If the pathname corresponds * to a file, only that file will be listed. The server may or may not * expand glob expressions.//from w w w . jav a2 s. c o m * <p> * @param pathname The file or directory to list. * Warning: the server may treat a leading '-' as an * option introducer. If so, try using an absolute path, * or prefix the path with ./ (unix style servers). * Some servers may support "--" as meaning end of options, * in which case "-- -xyz" should work. * @return The list of filenames contained in the given path. null if * the list could not be obtained. If there are no filenames in * the directory, a zero-length array is returned. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. */ public String[] listNames(String pathname) throws IOException { Socket socket = _openDataConnection_(FTPCmd.NLST, getListArguments(pathname)); if (socket == null) { return null; } BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), getControlEncoding())); ArrayList<String> results = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { results.add(line); } reader.close(); socket.close(); if (completePendingCommand()) { String[] names = new String[results.size()]; return results.toArray(names); } return null; }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * private method through which all listFiles() and * initiateListParsing methods pass once a parser is determined. * * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException/* ww w . j a v a 2 s .co m*/ * If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @see FTPListParseEngine */ private FTPListParseEngine initiateListParsing(FTPFileEntryParser parser, String pathname) throws IOException { Socket socket = _openDataConnection_(FTPCmd.LIST, getListArguments(pathname)); FTPListParseEngine engine = new FTPListParseEngine(parser); if (socket == null) { return engine; } try { engine.readServerList(socket.getInputStream(), getControlEncoding()); } finally { Util.closeQuietly(socket); } completePendingCommand(); return engine; }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * Initiate list parsing for MLSD listings. * * @param pathname//from www . j a v a 2 s .c o m * @return the engine * @throws IOException */ private FTPListParseEngine initiateMListParsing(String pathname) throws IOException { Socket socket = _openDataConnection_(FTPCmd.MLSD, pathname); FTPListParseEngine engine = new FTPListParseEngine(MLSxEntryParser.getInstance()); if (socket == null) { return engine; } try { engine.readServerList(socket.getInputStream(), getControlEncoding()); } finally { Util.closeQuietly(socket); completePendingCommand(); } return engine; }
From source file:de.prozesskraft.pradar.parts.PradarPartUi3.java
/** * asks for entities from the first pradar-server that responds * @return void/*from w w w. j a va2 s. com*/ */ void loadData() { for (String portAtMachineAsString : this.pradar_server_port_at_hostname) { String[] port_and_machine = portAtMachineAsString.split("@"); int portNumber = Integer.parseInt(port_and_machine[0]); String machineName = port_and_machine[1]; log("info", "want to load data from pradar-server"); log("info", "trying pradar-server " + portNumber + "@" + machineName); try { // socket einrichten und Out/Input-Streams setzen // log("debug", "machineName="+machineName+" | portNumber="+portNumber); // log("debug", "server objekt erstellen"); Socket connectToServerSocket = new Socket(machineName, portNumber); connectToServerSocket.setSoTimeout(20000); // log("debug", "outputStream erstellen"); OutputStream streamToServer = connectToServerSocket.getOutputStream(); // log("debug", "outputStream flushen"); streamToServer.flush(); // log("debug", "objectOutputStream erstellen"); ObjectOutputStream objectToServer = new ObjectOutputStream(streamToServer); // log("debug", "objectOutputStream flushen"); objectToServer.flush(); // Objekte zum server uebertragen // log("debug", "write: getallfromuser"); objectToServer.writeObject("getallfromuser"); objectToServer.writeObject(System.getProperty("user.name")); // log("debug", "outputStream flushen"); streamToServer.flush(); // log("debug", "objectOutputStream flushen"); objectToServer.flush(); // sende-object zerstoeren - wird nicht mehr gebraucht // log("debug", "objectOutputStream schliessen"); // objectToServer.close(); // log("debug", "inputStream erstellen"); InputStream streamFromServer = connectToServerSocket.getInputStream(); // log("debug", "objectInputStream erstellen"); ObjectInputStream objectFromServer = new ObjectInputStream(streamFromServer); // Antwort vom Server lesen - ein array aller Entities try { // log("debug", "reading"); Object serverAnswer = objectFromServer.readObject(); // log("debug", "reading done"); // lese-object zerstoeren - wird nicht mehr gebraucht objectFromServer.close(); // log("debug", "objectFromServer closed"); ArrayList<Object> serverAnswer2 = null; if (serverAnswer instanceof ArrayList) { // log("debug", "serverAnswer is an ArrayList"); serverAnswer2 = (ArrayList<Object>) serverAnswer; } // alle existierenden entities loeschen this.entities_all.clear(); // die neuen entities casten und in einem map unterbringen id->Entities erstellen um die children bei ihren parents einsortieren zu koennen Map<String, Entity> entities_all = new HashMap<String, Entity>(); for (Object actObject : serverAnswer2) { // if (actObject instanceof Entity) { // log("debug", "item of ArrayList<Object> is an Entity ---> adding to ArrayList<Entity>"); Entity newEntity = (Entity) actObject; this.entities_all.add(newEntity); } } // log("debug", "reading done! closing "); objectFromServer.close(); // log("debug", "read finished"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // daten holen aus db log("info", "refreshing data..."); connectToServerSocket.close(); } catch (UnknownHostException e) { log("warn", "unknown host " + machineName); this.pradar_server_port_at_hostname = null; } catch (IOException e) { log("warn", "input / output problems at " + portNumber + "@" + machineName); e.printStackTrace(); } this.refresh_last = Calendar.getInstance(); this.refresh_next = Calendar.getInstance(); this.refresh_next.add(13, this.refresh_interval); } }
From source file:Tcpbw100.java
public boolean test_s2c(Protocol ctl, Socket ctlSocket) throws IOException { byte buff[] = new byte[8192]; Message msg = new Message(); if ((tests & TEST_S2C) == TEST_S2C) { showStatus(messages.getString("inboundTest")); results.append(messages.getString("runningInboundTest") + " "); statistics.append(messages.getString("runningInboundTest") + " "); emailText += messages.getString("runningInboundTest") + " "; pub_status = "runningInboundTest"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; }/*from www . j av a 2 s .c o m*/ if (msg.type != TEST_PREPARE) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int s2cport = Integer.parseInt(new String(msg.body)); Socket inSocket; try { inSocket = new Socket(host, s2cport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = "unknown server\n"; return true; } catch (IOException e) { System.err.println("Couldn't get 3rd connection to: " + host); errmsg = "Server Failed while receiving data\n"; return true; } InputStream srvin = inSocket.getInputStream(); int bytes = 0; int inlth; // wait here for signal from server application if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("unknownServer") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_START) { errmsg = messages.getString("serverFail") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } inSocket.setSoTimeout(15000); t = System.currentTimeMillis(); pub_time = t; try { while ((inlth = srvin.read(buff, 0, buff.length)) > 0) { bytes += inlth; pub_bytes = bytes; if ((System.currentTimeMillis() - t) > 14500) break; } } catch (IOException e) { } t = System.currentTimeMillis() - t; System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs"); s2cspd = ((8.0 * bytes) / 1000) / t; /* receive the s2cspd from the server */ if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } try { String tmpstr3 = new String(msg.body); int k1 = tmpstr3.indexOf(" "); int k2 = tmpstr3.substring(k1 + 1).indexOf(" "); ss2cspd = Double.parseDouble(tmpstr3.substring(0, k1)) / 1000.0; ssndqueue = Integer.parseInt(tmpstr3.substring(k1 + 1).substring(0, k2)); sbytes = Double.parseDouble(tmpstr3.substring(k1 + 1).substring(k2 + 1)); } catch (Exception e) { e.printStackTrace(); errmsg = messages.getString("inboundWrongMessage") + "\n"; return true; } if (s2cspd < 1.0) { results.append(prtdbl(s2cspd * 1000) + "kb/s\n"); statistics.append(prtdbl(s2cspd * 1000) + "kb/s\n"); emailText += prtdbl(s2cspd * 1000) + "kb/s\n%0A"; } else { results.append(prtdbl(s2cspd) + "Mb/s\n"); statistics.append(prtdbl(s2cspd) + "Mb/s\n"); emailText += prtdbl(s2cspd) + "Mb/s\n%0A"; } // Expose download speed to JavaScript clients pub_s2cspd = s2cspd; dnlLbl.setText(String.format(padding + "%.3f Mbps", s2cspd)); pub_status = "done"; srvin.close(); inSocket.close(); buff = Double.toString(s2cspd * 1000).getBytes(); String tmpstr4 = new String(buff, 0, buff.length); System.out.println("Sending '" + tmpstr4 + "' back to server"); ctl.send_msg(TEST_MSG, buff); /* get web100 variables from server */ tmpstr = ""; int i = 0; // Try setting a 5 second timer here to break out if the read fails. ctlSocket.setSoTimeout(5000); try { for (;;) { if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type == TEST_FINALIZE) { break; } if (msg.type != TEST_MSG) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } tmpstr += new String(msg.body); i++; } } catch (IOException e) { } ctlSocket.setSoTimeout(0); } pub_status = "done"; return false; }