List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:com.talis.platform.sequencing.zookeeper.ZkTestHelper.java
public boolean waitForServerUp(String hp, long timeout) { long start = System.currentTimeMillis(); String split[] = hp.split(":"); String host = split[0];// ww w . j a v a 2 s .c o m int port = Integer.parseInt(split[1]); while (true) { try { Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server " + hp + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; }
From source file:gov.hhs.fha.nhinc.lift.clientController.SocketClientManagerController.java
@Override public final void run() { while (true) { Socket socket = null; InputStream in = null;//from w w w. j a v a 2 s . c om URI writtenFile = null; String errorMesg = null; LiftMessage mesg = null; try { socket = server.accept(); while (socket == null) { socket = server.accept(); } in = socket.getInputStream(); log.debug("Server " + server.getInetAddress() + " connecting to socket " + socket.getInetAddress() + ": " + socket.getPort()); InterProcessSocketProtocol processSocket = new InterProcessSocketProtocol(); String message = processSocket.readData(in); log.info("SocketClientManagerController received message: " + message); if (message != null) { mesg = (LiftMessage) JaxbUtil.unmarshalFromReader(new StringReader(message), LiftMessage.class); System.out.println("Setting " + mesg.getRequest().getRequest() + " to in progress"); mesgState.add(mesg.getRequest().getRequest()); writtenFile = manager.startClient(mesg, this); } } catch (JAXBException ex) { errorMesg = "Client is unable to process LiftMessage " + ex.getMessage(); log.error(errorMesg); } catch (IOException e) { errorMesg = "Client is unable to process incoming socket information " + e.getMessage(); log.error(errorMesg); } finally { if (socket != null) { try { log.debug("Closing socket " + socket); socket.close(); } catch (IOException ex) { log.warn("Unable to close socket " + socket); } } if (writtenFile != null) { reportSuccess(mesg.getRequest().getRequest(), writtenFile); } else { if (mesg != null && mesg.getRequest() != null && mesg.getRequest().getRequest() != null) { reportFailure(mesg.getRequest().getRequest(), errorMesg); } else { reportFailure(null, errorMesg); } } } } }
From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1.java
public boolean start(Socket sock) { try {//from ww w. jav a 2s . c o m this.sock = sock; sock.connect(new InetSocketAddress(host, port), 5000); sock.setSendBufferSize(64 * 1024); out = sock.getOutputStream(); PrintWriter output = writeAuthentication(); InputStreamReader isr = new InputStreamReader(sock.getInputStream()); BufferedReader in = new BufferedReader(isr); String line = in.readLine(); if (line == null || !line.contains("OK")) { if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } while (line != null && line.length() > 0) { line = in.readLine(); } writeHeaders(output); } catch (Exception e) { e.printStackTrace(); try { if (sock != null) sock.close(); } catch (IOException e1) { e1.printStackTrace(); } if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } started = true; if (listener != null) { listener.onConnected(); } return true; }
From source file:com.sshtools.j2ssh.agent.SshAgentConnection.java
SshAgentConnection(KeyStore keystore, Socket socket) throws IOException { this.keystore = keystore; this.in = socket.getInputStream(); this.out = socket.getOutputStream(); this.socket = socket; socket.setSoTimeout(5000);/*w ww .j av a 2 s . c o m*/ thread = new Thread(this); thread.start(); }
From source file:org.vietspider.net.apache.SocketInputBuffer.java
/** * Creates an instance of this class. //from w ww. ja v a2s. c o m * <p> * The following HTTP parameters affect the initialization: * <p> * The {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} * parameter determines the charset to be used for decoding HTTP lines. If * not specified, <code>US-ASCII</code> will be used per default. * <p> * The {@link CoreConnectionPNames#MAX_LINE_LENGTH} parameter determines * the maximum line length limit. If set to a positive value, any HTTP * line exceeding this limit will cause an IOException. A negative or zero * value will effectively disable the check. Per default the line length * check is disabled. * * @param socket the socket to read data from. * @param buffersize the size of the internal buffer. If this number is less * than <code>0</code> it is set to the value of * {@link Socket#getReceiveBufferSize()}. If resultant number is less * than <code>1024</code> it is set to <code>1024</code>. * @param params HTTP parameters. * * @see CoreProtocolPNames#HTTP_ELEMENT_CHARSET * @see CoreConnectionPNames#MAX_LINE_LENGTH */ public SocketInputBuffer(final Socket socket, int buffersize, final HttpParams params) throws IOException { super(); if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } this.socket = socket; this.eof = false; if (buffersize < 0) { buffersize = socket.getReceiveBufferSize(); } if (buffersize < 1024) { buffersize = 1024; } init(socket.getInputStream(), buffersize, params); }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChecker.java
public void check(Properties dbProps) throws IOException { String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); s_logger.debug("Encryption Type: " + encryptionType); if (encryptionType == null || encryptionType.equals("none")) { return;/* w w w . j a v a 2s.co m*/ } if (s_useEncryption) { s_logger.warn("Encryption already enabled, is check() called twice?"); return; } s_encryptor.setAlgorithm("PBEWithMD5AndDES"); String secretKey = null; SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); if (encryptionType.equals("file")) { InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile); if (is == null) { is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile); } if (is == null) { //This is means we are not able to load key file from the classpath. throw new CloudRuntimeException( s_keyFile + " File containing secret key not found in the classpath: "); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(is)); secretKey = in.readLine(); //Check for null or empty secret key } catch (IOException e) { throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e); } finally { IOUtils.closeQuietly(in); } if (secretKey == null || secretKey.isEmpty()) { throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile); } } else if (encryptionType.equals("env")) { secretKey = System.getenv(s_envKey); if (secretKey == null || secretKey.isEmpty()) { throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty"); } } else if (encryptionType.equals("web")) { ServerSocket serverSocket = null; int port = 8097; try { serverSocket = new ServerSocket(port); } catch (IOException ioex) { throw new CloudRuntimeException("Error initializing secret key reciever", ioex); } s_logger.info("Waiting for admin to send secret key on port " + port); Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { throw new CloudRuntimeException("Accept failed on " + port); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { secretKey = inputLine; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } else { throw new CloudRuntimeException("Invalid encryption type: " + encryptionType); } stringConfig.setPassword(secretKey); s_encryptor.setConfig(stringConfig); s_useEncryption = true; }
From source file:com.jiangge.apns4j.impl.ApnsConnectionImpl.java
private void startErrorWorker() { Thread thread = new Thread(new Runnable() { @Override/*from w w w . ja v a2 s . c o m*/ public void run() { Socket curSocket = socket; try { if (!isSocketAlive(curSocket)) { return; } InputStream socketIs = curSocket.getInputStream(); byte[] res = new byte[ERROR_RESPONSE_BYTES_LENGTH]; int size = 0; while (true) { try { size = socketIs.read(res); if (size > 0 || size == -1) { // break, when something was read or there is no data any more break; } } catch (SocketTimeoutException e) { // There is no data. Keep reading. } } int command = res[0]; /** EN: error-response,close the socket and resent notifications * CN: ??????? */ if (size == res.length && command == Command.ERROR) { int status = res[1]; int errorId = ApnsTools.parse4ByteInt(res[2], res[3], res[4], res[5]); if (logger.isInfoEnabled()) { logger.info( String.format("%s Received error response. status: %s, id: %s, error-desc: %s", connName, status, errorId, ErrorResponse.desc(status))); } Queue<PushNotification> resentQueue = new LinkedList<PushNotification>(); synchronized (lock) { boolean found = false; errorHappendedLastConn = true; while (!notificationCachedQueue.isEmpty()) { PushNotification pn = notificationCachedQueue.poll(); if (pn.getId() == errorId) { found = true; } else { /** * https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html * As the document said, add the notifications which need be resent to the queue. * Igonre the error one */ if (found) { resentQueue.add(pn); } } } if (!found) { logger.warn(connName + " Didn't find error-notification in the queue. Maybe it's time to adjust cache length. id: " + errorId); } } // resend notifications if (!resentQueue.isEmpty()) { ApnsResender.getInstance().resend(name, resentQueue); } } else { // ignore and continue reading logger.error( connName + " Unexpected command or size. commend: " + command + " , size: " + size); } } catch (Exception e) { // logger.error(connName + " " + e.getMessage(), e); logger.error(connName + " " + e.getMessage()); } finally { /** * EN: close the old socket although it may be closed once before. * CN: ??? */ closeSocket(curSocket); } } }); thread.start(); }
From source file:com.sshtools.j2ssh.agent.SshAgentClient.java
SshAgentClient(boolean isForwarded, String application, Socket socket) throws IOException { log.info("New SshAgentClient instance created"); this.socket = socket; this.in = socket.getInputStream(); this.out = socket.getOutputStream(); this.isForwarded = isForwarded; registerMessages();/* w ww .j a v a 2 s . c om*/ if (isForwarded) { sendForwardingNotice(); } else { sendVersionRequest(application); } }
From source file:cn.devit.app.ip_messenger.DownloadTask.java
@Override protected Integer doInBackground(PigeonMessage... params) { long got = 0;// store all file's byte size. int count = 0;// store number of files received. for (PigeonMessage item : params) { for (int i = 0; i < item.getAttachements().size(); i++) { size += item.getAttachements().get(i).getLength(); }/*from w w w .j av a 2s . c o m*/ } Log.d("main", "total bytes of file:" + size); // TODO ?publish for (PigeonMessage item : params) { for (int i = 0; i < item.getAttachements().size(); i++) { noteId = item.hashCode(); AttachementLink link = item.getAttachements().get(i); if (link.getType() == PigeonCommand.IPMSG_FILE_REGULAR) { count++; Socket socket = null; try { socket = network.getAttachementStream(item, i); } catch (IOException e) { e.printStackTrace(); continue; } InputStream stream = null; try { stream = socket.getInputStream(); } catch (IOException e) { e.printStackTrace(); continue; } File download = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); String filename = link.getFilename(); File file = new File(download, filename); if (file.exists()) { file.delete(); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Log.d("main", "download file:" + file.getName()); try { FileOutputStream fos = new FileOutputStream(file); byte[] cache = new byte[1024]; try { int len = 0; while ((len = stream.read(cache)) >= 0) { got += len; fos.write(cache, 0, len); this.publishProgress(got); } fos.close(); stream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } // try { // } catch (IOException e) { // if(socket!=null){ // socket. // } // } } } // TODO Auto-generated method stub return count; }
From source file:SendMail.java
/** * Called when the send button is clicked. Actually sends the mail message. * //from w ww .java 2 s . c o m * @param event * The event. */ void Send_actionPerformed(java.awt.event.ActionEvent event) { try { java.net.Socket s = new java.net.Socket(_smtp.getText(), 25); _out = new java.io.PrintWriter(s.getOutputStream()); _in = new java.io.BufferedReader(new java.io.InputStreamReader(s.getInputStream())); send(null); send("HELO " + java.net.InetAddress.getLocalHost().getHostName()); send("MAIL FROM: " + _from.getText()); send("RCPT TO: " + _to.getText()); send("DATA"); _out.println("Subject:" + _subject.getText()); _out.println(_body.getText()); send("."); s.close(); } catch (Exception e) { _model.addElement("Error: " + e); } }