List of usage examples for java.net SocketException getMessage
public String getMessage()
From source file:com.comcast.cats.telnet.TelnetConnection.java
/** * Connect to the telnet client.// ww w. jav a 2 s. c o m * * @param isEnterRequired * : sometime an ENTER key maybe required to reach the prompt. * * @return true: if connected. * * @throws SocketException * @throws IOException */ public synchronized Boolean connect(Boolean isEnterRequired) throws SocketException, IOException { if (!isConnected) { try { telnetClient.connect(getHost(), getPort()); logger.info("connected to telnet host " + host + " port " + port + " defaultPromptString " + defaultPromptString); } catch (SocketException e) { logger.warn("Could not connect to telnetSession " + e.getMessage()); throw new SocketException(e.getMessage()); } is = telnetClient.getInputStream(); os = new PrintStream(telnetClient.getOutputStream()); if (isEnterRequired) { os.println(); } isConnected = true; lastActiveTime = new Date(); } return isConnected; }
From source file:com.mirth.connect.connectors.mllp.protocols.LlpProtocol.java
private byte[] readTCP(InputStream is) throws IOException { String charset = _mllpConnector.getCharsetEncoding(); UtilReader myReader = new UtilReader(is, charset); int c = 0;//from w w w . ja v a 2s. c o m try { c = myReader.read(); } catch (SocketException e) { logger.info( "SocketException on read() attempt. Socket appears to have been closed: " + e.getMessage()); return null; } catch (SocketTimeoutException ste) { logger.info("SocketTimeoutException on read() attempt. Socket appears to have been closed: " + ste.getMessage()); return null; } // trying to read when there is no data (stream may have been closed at // other end) if (c == -1) { logger.info("End of input stream reached."); return null; } while (c != -1) { myReader.append((char) c); try { c = myReader.read(); } catch (Exception e) { c = -1; } } return myReader.getBytes(); }
From source file:com.comcast.cats.telnet.TelnetConnection.java
/** * Connect to the telnet client with a password. * * @param isEnterRequired/* w w w . j a v a 2 s . co m*/ * : sometime an ENTER key maybe required to reach the prompt. * * @param password * @param passwordPromptString * : the prompt that asks for a password : usually something like * "Enter Password :" * @return true if connected successfully * @throws SocketException * @throws IOException */ public synchronized Boolean connectWithPassword(String password, String passwordPromptString, Boolean isEnterRequired) throws SocketException, IOException { if (!isConnected && password != null && passwordPromptString != null) { try { telnetClient.connect(getHost(), getPort()); logger.info("connected to telnet host " + host + " port " + port); } catch (SocketException e) { logger.warn("Could not connect to telnetSession " + e.getMessage()); throw new SocketException(e.getMessage()); } is = telnetClient.getInputStream(); os = new PrintStream(telnetClient.getOutputStream()); if (isEnterRequired) { os.println(); } String passwordPrompt = readUntil(passwordPromptString); logger.debug("passwordPrompt " + passwordPrompt); if (passwordPrompt != null) { write(password); isConnected = true; lastActiveTime = new Date(); } else { logger.info("Prompt string could not be reached"); disconnect(); } } return isConnected; }
From source file:com.googlecode.jcimd.TcpNetConnection.java
@Override public void run() { logger.debug("Ready for replies..."); Packet reply;// w w w .ja va2s. c o m while (true) { try { reply = this.serializer.deserialize(this.socket.getInputStream()); } catch (SocketException e) { break; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Read exception " + e.getClass().getName() + ": " + e.getCause() + ": " + e.getMessage()); } // since it's a socket exception, let's close without sending a logout operation closeSocket(); break; // get out of this while-loop } AsyncReply asyncReply = pendingReplies.get(""); asyncReply.setReply(reply); } }
From source file:net.yacy.http.ProxyHandler.java
@Override public void handleRemote(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { sb.proxyLastAccess = System.currentTimeMillis(); RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request); setProxyHeaderForClient(request, proxyHeaders); final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent); client.setTimout(timeout);/* ww w .j a va 2s . co m*/ client.setHeader(proxyHeaders.entrySet()); client.setRedirecting(false); // send request try { String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : ""; DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI() + queryString); if (request.getMethod().equals(HeaderFramework.METHOD_GET)) { client.GET(digestURI, false); } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) { client.POST(digestURI, request.getInputStream(), request.getContentLength(), false); } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) { client.HEADResponse(digestURI, false); } else { throw new ServletException("Unsupported Request Method"); } HttpResponse clientresponse = client.getHttpResponse(); int statusCode = clientresponse.getStatusLine().getStatusCode(); final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode, clientresponse.getAllHeaders()); if (responseHeaderLegacy.isEmpty()) { throw new SocketException(clientresponse.getStatusLine().toString()); } cleanResponseHeader(clientresponse); // reserver cache entry final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null, digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0, sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete); final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy, sb.crawler.defaultProxyProfile, false, null); final String storeError = yacyResponse.shallStoreCacheForProxy(); final boolean storeHTCache = yacyResponse.profile().storeHTCache(); final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType()); if ( /* * Now we store the response into the htcache directory if * a) the response is cacheable AND */ (storeError == null) && /* * b) the user has configured to use the htcache OR * c) the content should be indexed */ ((storeHTCache) || (supportError != null))) { // we don't write actually into a file, only to RAM, and schedule writing the file. int l = responseHeaderLegacy.size(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l); final OutputStream toClientAndMemory = new MultiOutputStream( new OutputStream[] { response.getOutputStream(), byteStream }); convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); client.writeTo(toClientAndMemory); // cached bytes storeToCache(yacyResponse, byteStream.toByteArray()); } else { // no caching /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." + " StoreError=" + ((storeError==null)?"None":storeError) + " StoreHTCache=" + storeHTCache + " SupportError=" + supportError);*/ convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content) client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream } } } catch (final SocketException se) { throw new ServletException("Socket Exception: " + se.getMessage()); } finally { client.finish(); } // we handled this request, break out of handler chain logProxyAccess(request); baseRequest.setHandled(true); }
From source file:org.npr.android.test.HttpServer.java
private void processRequest(DataSource dataSource, Socket client) throws IllegalStateException, IOException { if (dataSource == null) { Log.e(TAG, "Invalid (null) resource."); client.close();/*from ww w . j ava2 s. c o m*/ return; } Log.d(TAG, "setting response headers"); StringBuilder httpString = new StringBuilder(); httpString.append(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK")); httpString.append("\n"); httpString.append("Content-Type: ").append(dataSource.getContentType()); httpString.append("\n"); // Some content (e.g. streams) does not define a length long length = dataSource.getContentLength(); if (length >= 0) { httpString.append("Content-Length: ").append(length); httpString.append("\n"); } httpString.append("\n"); Log.d(TAG, "headers done"); InputStream data = null; try { data = dataSource.createInputStream(); byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start sending content. byte[] buff = new byte[1024 * 50]; while (isRunning) { readBytes = data.read(buff, 0, buff.length); if (readBytes == -1) { if (simulateStream) { data.close(); data = dataSource.createInputStream(); readBytes = data.read(buff, 0, buff.length); if (readBytes == -1) { throw new IOException("Error re-opening data source for looping."); } } else { break; } } client.getOutputStream().write(buff, 0, readBytes); } } catch (SocketException e) { // Ignore when the client breaks connection Log.w(TAG, "Ignoring " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "Error getting content stream.", e); } catch (Exception e) { Log.e(TAG, "Error streaming file content.", e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:org.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java
/** * Checks whether we are effected by the JDK issue on windows, and if so * ensures that we are running with preferIPv4Stack=true. *//* ww w. ja va2 s.c o m*/ @Test public void testServerSocket() throws IOException { byte[] addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; InetAddress inetAddr = InetAddress.getByAddress(addr); try { bindServerSocket(inetAddr); bindNIOServerSocket(inetAddr); //if on *nix or windows JDK7, both will pass } catch (java.net.SocketException ex) { //On Windows JDK6, we will get expected exception: //java.net.SocketException: Address family not supported by protocol family //or java.net.SocketException: Protocol family not supported Assert.assertFalse(ex.getClass().isInstance(BindException.class)); Assert.assertTrue(ex.getMessage().toLowerCase().contains("protocol family")); LOG.info("Received expected exception:"); LOG.info(ex); //if this is the case, ensure that we are running on preferIPv4=true ensurePreferIPv4(); } }
From source file:uk.co.marcoratto.net.ClientFTP.java
/** A convenience method for connecting and logging in */ public int connect(String host, int port) throws ClientFTPException { int reply = -1; try {// ww w .j a v a 2s. com ftp.connect(host, port); reply = ftp.getReplyCode(); ftp.addProtocolCommandListener(new PrintCommandListener()); } catch (SocketException e) { logger.error(e.getMessage(), e); throw new ClientFTPException(e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new ClientFTPException(e); } return reply; }
From source file:com.android.mms.service.http.NetworkAwareClientConnectionOperator.java
/** * This method is mostly copied from the overridden one in parent. The only change * is how we resolve host name./*from w w w . j av a 2s. com*/ */ @Override public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection must not be null."); } if (target == null) { throw new IllegalArgumentException("Target host must not be null."); } // local address may be null //@@@ is context allowed to be null? if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } if (conn.isOpen()) { throw new IllegalArgumentException("Connection must not be open."); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); final SocketFactory sf = schm.getSocketFactory(); final SocketFactory plain_sf; final LayeredSocketFactory layered_sf; if (sf instanceof LayeredSocketFactory) { plain_sf = staticPlainSocketFactory; layered_sf = (LayeredSocketFactory) sf; } else { plain_sf = sf; layered_sf = null; } // CHANGE FOR MmsService ArrayList<InetAddress> addresses = resolveHostName(target.getHostName()); for (int i = 0; i < addresses.size(); ++i) { Log.d(TAG, "NetworkAwareClientConnectionOperator: connecting " + addresses.get(i)); Socket sock = plain_sf.createSocket(); conn.opening(sock, target); try { Socket connsock = plain_sf.connectSocket(sock, addresses.get(i).getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params); if (sock != connsock) { sock = connsock; conn.opening(sock, target); } /* * prepareSocket is called on the just connected * socket before the creation of the layered socket to * ensure that desired socket options such as * TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set * before any I/O is performed on the socket. This * happens in the common case as * SSLSocketFactory.createSocket performs hostname * verification which requires that SSL handshaking be * performed. */ prepareSocket(sock, context, params); if (layered_sf != null) { Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true); if (layeredsock != sock) { conn.opening(layeredsock, target); } conn.openCompleted(sf.isSecure(layeredsock), params); } else { conn.openCompleted(sf.isSecure(sock), params); } break; // BEGIN android-changed // catch SocketException to cover any kind of connect failure } catch (SocketException ex) { if (i == addresses.size() - 1) { ConnectException cause = ex instanceof ConnectException ? (ConnectException) ex : (ConnectException) new ConnectException(ex.getMessage()).initCause(ex); throw new HttpHostConnectException(target, cause); } // END android-changed } catch (ConnectTimeoutException ex) { if (i == addresses.size() - 1) { throw ex; } } } }
From source file:com.mirth.connect.connectors.mllp.protocols.LlpProtocol.java
private byte[] readLLP(InputStream is) throws IOException { // ast: new function to process the MLLP protocol // ast: wrapper for the reader String charset = _mllpConnector.getCharsetEncoding(); UtilReader myReader = new UtilReader(is, charset); boolean end_of_message = false; int c = 0;//from ww w .j a v a2 s . c o m try { c = myReader.read(); } catch (SocketException e) { logger.info( "SocketException on read() attempt. Socket appears to have been closed: " + e.getMessage()); return null; } catch (SocketTimeoutException ste) { logger.info("SocketTimeoutException on read() attempt. Socket appears to have been closed: " + ste.getMessage()); return null; } // trying to read when there is no data (stream may have been closed at // other end) if (c == -1) { logger.info("End of input stream reached."); return null; } while ((c != START_MESSAGE) && (c != -1)) { try { c = myReader.read(); } catch (Exception e) { c = -1; } } if (c == -1) { // End of stream reached without start of message character. String message = myReader.toString(); logger.error("Bytes received violate the MLLP: no start of message indicator received.\r\n" + message); return null; } myReader.append((char) c); while (!end_of_message) { c = myReader.read(); if (c == -1) { logger.error("Message violates the " + "minimal lower protocol: message terminated without " + "a terminating character."); return null; } myReader.append((char) c); if (c == END_MESSAGE) { if (END_OF_RECORD != 0) { // subsequent character should be a carriage return try { c = myReader.read(); if (END_OF_RECORD != 0 && c != END_OF_RECORD) { logger.error( "Message terminator was: " + c + " Expected terminator: " + END_OF_RECORD); return null; } myReader.append((char) c); } catch (SocketException e) { logger.info("SocketException on read() attempt. Socket appears to have been closed: " + e.getMessage()); } catch (SocketTimeoutException ste) { logger.info( "SocketTimeoutException on read() attempt. Socket appears to have been closed: " + ste.getMessage()); } } end_of_message = true; } } // end while return myReader.getBytes(); }