List of usage examples for java.net ConnectException getLocalizedMessage
public String getLocalizedMessage()
From source file:it.geosolutions.figis.requester.HTTPUtils.java
public static boolean httpPing(String url, String username, String pw) { GetMethod httpMethod = null;/*from w ww. j a v a2s . c o m*/ try { HttpClient client = new HttpClient(); setAuth(client, url, username, pw); httpMethod = new GetMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(2000); int status = client.executeMethod(httpMethod); if (status != HttpStatus.SC_OK) { LOGGER.warn("PING failed at '" + url + "': (" + status + ") " + httpMethod.getStatusText()); return false; } else { return true; } } catch (ConnectException e) { if (LOGGER.isInfoEnabled()) { LOGGER.log(Level.INFO, e.getLocalizedMessage(), e); } return false; } catch (IOException e) { if (LOGGER.isInfoEnabled()) { LOGGER.log(Level.INFO, e.getLocalizedMessage(), e); } return false; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
public static boolean httpPing(String url, String username, String pw) { GetMethod httpMethod = null;/* www. ja v a 2 s .c o m*/ HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(2000); int status = client.executeMethod(httpMethod); if (status != HttpStatus.SC_OK) { LOGGER.warn("PING failed at '" + url + "': (" + status + ") " + httpMethod.getStatusText()); return false; } else { return true; } } catch (ConnectException e) { return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return false; } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:it.geosolutions.figis.requester.HTTPUtils.java
/** * Send an HTTP request (PUT or POST) to a server. * <BR>Basic auth is used if both username and pw are not null. * <P>/*from ww w. ja v a2s.c om*/ * Only <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> are accepted as successful codes; in these cases the response string will be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { try { HttpClient client = new HttpClient(); setAuth(client, url, username, pw); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); if (requestEntity != null) { httpMethod.setRequestEntity(requestEntity); } int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); if (LOGGER.isInfoEnabled()) { LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); } return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.error("Couldn't connect to [" + url + "]", e); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage(), e); return null; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Send an HTTP request (PUT or POST) to a server. <BR> * Basic auth is used if both username and pw are not null. * <P>//from ww w . j a v a 2s . co m * Only * <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> * are accepted as successful codes; in these cases the response string will * be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); connectionManager.getParams().setConnectionTimeout(5000); if (requestEntity != null) httpMethod.setRequestEntity(requestEntity); int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); // LOGGER.info("================= POST " + url); if (LOGGER.isInfoEnabled()) LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:it.geosolutions.geonetwork.util.HTTPUtils.java
/** * Send an HTTP request (PUT or POST) to a server. * <BR>Basic auth is used if both username and pw are not null. * <P>//from w w w .j a va2s .com * Only <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> are accepted as successful codes; in these cases the response string will be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ protected String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity) { try { setAuth(client, url, username, pw); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); if (requestEntity != null) httpMethod.setRequestEntity(requestEntity); lastHttpStatus = client.executeMethod(httpMethod); switch (lastHttpStatus) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: if (LOGGER.isDebugEnabled()) LOGGER.debug("HTTP " + httpMethod.getStatusText() + " <-- " + url); if (ignoreResponseContentOnSuccess) return ""; String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); return response; default: String badresponse = IOUtils.toString(httpMethod.getResponseBodyAsStream()); String message = getGeoNetworkErrorMessage(badresponse); LOGGER.warn("Bad response: " + lastHttpStatus + " " + httpMethod.getStatusText() + " -- " + httpMethod.getName() + " " + url + " : " + message); if (LOGGER.isDebugEnabled()) LOGGER.debug("GeoNetwork response:\n" + badresponse); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) httpMethod.releaseConnection(); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient.java
/** * Creates an HTTP download connection item for the given download spec, * initialized for downloading a file from the TFS. The object returned is * an Apache HttpClient GetMethod object whose status code has been * validated to be HttpStatus.SC_OK. This means you can read the response * from this stream using getResponseBodyAsStream() or * getResponseBodyAsString() (or other methods). You must pass this method * object back into this class's finishDownloadRequest() when you are * finished./*from w w w .jav a 2s .com*/ * <p> * If a TFS download proxy was set during the construction of TFSConnection, * it is contacted here. Otherwise, the host passed to the TFSConnection * constructor is contacted. * <p> * <b>NOTE:</b> This method is not synchronized (but is thread-safe) because * doing so would allow deadlock during concurrent downloads. When there are * more downloader threads than available connections in the HttpClient's * pool, a thread may sleep in the HttpClient code (while holding a lock on * this object) until a connection becomes available, which can only happen * if other threads finish using their connections (which they can't because * they need to acquire a lock on this object to do so). * * @param spec * the spec object that describes the item being downloaded (not * @return a new GetMethod object that has been validated to have status * HttpStatus.SC_OK. The caller can read its data using * getResponseBodyAsStream or getResponseBodyAsString(), then close * the stream with releaseConnection(). * @throws MalformedURLException * if an error occured building the URL from the spec and the * existing connection information. * @throws DownloadProxyException * if a download proxy was used and the HTTP GET failed for any * reason. * @throws SocketException * if a socket error occurred. This method handles most IO * exceptions by rethrowing them as {@link VersionControlException} * s, but {@link SocketException}s are thrown so callers can detect * connection resets and retry their operation. Retrying * automatically inside this method is problematic because it knows * nothing about higher-level state that may need reset for a retry. */ private GetMethod beginDownloadRequest(final DownloadSpec spec) throws MalformedURLException, DownloadProxyException, SocketException { Check.notNull(spec, "spec"); //$NON-NLS-1$ final TFProxyServerSettings tfProxyServerSettings = connection.getTFProxyServerSettings(); String tfsProxyURL = null; if (tfProxyServerSettings.isAvailable()) { tfsProxyURL = tfProxyServerSettings.getURL(); } /* * A note about URL encoding / escaping: * * The download spec that TFS gives us contains some already-escaped * values. If we pass that string into a URI class constructor or * resolve it against a URI, the escape characters will be * double-escaped. So we deal with URI strings only here. */ String downloadURIString = null; String downloadHost = null; /* * URI Encoding Special Notice * * The download spec is a URI query string * ("name=value&zap=baz&other=stuff") but some of the query arguments * are already URI encoded ("s=before%2Fafter") and some of them are not * ("cp=/tfs/Collection Name With Spaces/")! * * To avoid breaking the string down into each args and encoding just * the ones we know are usually unencoded ("cp", which is the project * collection name), we call a special utility method in URIUtils which * exists pretty much just for this one case. */ final String reEncodedDownloadSpec = URIUtils.encodeQueryIgnoringPercentCharacters(spec.getQueryString()); if (tfsProxyURL == null) { /* * Use the existing server settings. */ final URI uri = getDownloadURI(); downloadURIString = uri.toString() + "?" + reEncodedDownloadSpec; //$NON-NLS-1$ downloadHost = uri.getHost(); } else { // TODO: Check with TFS2010 VC Proxy /* * TFS 2005 uses a proxy download file without a "V1.0" in it. TFS * 2008 introduced the "V1.0" part, but remains compatible with TFS * 2005's path. TFS 2010 drops the 2005 compat. To detect which * version, we check the supported features for "create branch", * which was introduced in 2008. Kind of a hack. */ final String proxyDownloadFile = getServerSupportedFeatures().contains(SupportedFeatures.CREATE_BRANCH) ? VersionControlConstants.PROXY_DOWNLOAD_FILE_2008 : VersionControlConstants.PROXY_DOWNLOAD_FILE_2005; final URI uri = URIUtils.newURI(tfsProxyURL).resolve(proxyDownloadFile); downloadURIString = uri.toString() + "?" //$NON-NLS-1$ + reEncodedDownloadSpec + "&" //$NON-NLS-1$ + VersionControlConstants.PROXY_REPOSITORY_ID_QUERY_STRING + "=" //$NON-NLS-1$ + getServerGUID(); downloadHost = uri.getHost(); } /* * Construct a Get method for our HttpClient to use. */ final GetMethod getMethod = new GetMethod(downloadURIString); getMethod.setDoAuthentication(true); final HttpClient client = getHTTPClient(); int status = -1; /* * If any exception happens, finish the method immediately because we * won't be returning it. This releases the connection to the connection * manager. */ try { status = client.executeMethod(getMethod); } catch (final ConnectException e) { finishDownloadRequest(getMethod); if (tfsProxyURL != null) { throw new DownloadProxyException(MessageFormat.format( Messages.getString("VersionControlClient.CouldNotConnectToDownloadProxyServerFormat"), //$NON-NLS-1$ downloadHost, e.getMessage())); } else { throw new VersionControlException( MessageFormat.format(Messages.getString("VersionControlClient.CouldNotConnecttoTFSFormat"), //$NON-NLS-1$ downloadHost, e.getLocalizedMessage())); } } catch (final UnknownHostException e) { finishDownloadRequest(getMethod); if (tfsProxyURL != null) { throw new DownloadProxyException(MessageFormat.format( Messages.getString( "VersionControlClient.CouldNotResolveDownloadProxyServertoNetworkAddressFormat"), //$NON-NLS-1$ downloadHost)); } else { throw new VersionControlException(MessageFormat.format( Messages.getString("VersionControlClient.CouldNotResolveTFSToNetworkAddressFormat"), //$NON-NLS-1$ downloadHost)); } } catch (final SocketException e) { finishDownloadRequest(getMethod); throw e; } catch (final SocketTimeoutException e) { finishDownloadRequest(getMethod); if (tfsProxyURL != null) { throw new DownloadProxyException(MessageFormat.format( Messages.getString("VersionControlClient.ErrorConnectingToDownloadProxyServerFormat"), //$NON-NLS-1$ downloadHost, e.getMessage())); } else { throw new VersionControlException( MessageFormat.format(Messages.getString("VersionControlClient.ErrorConnectingToTFSFormat"), //$NON-NLS-1$ downloadHost, e.getLocalizedMessage())); } } catch (final IOException e) { finishDownloadRequest(getMethod); if (tfsProxyURL != null) { throw new DownloadProxyException(MessageFormat.format( Messages.getString("VersionControlClient.ErrorConnectingToDownloadProxyServerFormat"), //$NON-NLS-1$ downloadHost, e.getMessage())); } else { throw new VersionControlException( MessageFormat.format(Messages.getString("VersionControlClient.ErrorConnectingToTFSFormat"), //$NON-NLS-1$ downloadHost, e.getLocalizedMessage())); } } if (status != HttpStatus.SC_OK) { /* * Finish the method before we throw. */ finishDownloadRequest(getMethod); if (tfsProxyURL != null) { throw new DownloadProxyException(MessageFormat.format( Messages.getString("VersionControlClient.DownloadProxyAtURLReturnedHTTPStatusForGETFormat"), //$NON-NLS-1$ tfsProxyURL.toString(), status)); } else { /* Handle status will always throw a VersionControlException */ handleStatus(getMethod); } } return getMethod; }
From source file:org.codehaus.mojo.cassandra.Utils.java
/** * Stops the Cassandra service./* w w w .j ava2s . co m*/ * * @param rpcAddress The rpcAddress to connect to in order to see if Cassandra has stopped. * @param rpcPort The rpcPort to connect on to check if Cassandra has stopped. * @param stopPort The port to stop on. * @param stopKey The key to stop with, * @param log The log to write to. */ static void stopCassandraServer(String rpcAddress, int rpcPort, String stopAddress, int stopPort, String stopKey, Log log) { try { Socket s = new Socket(InetAddress.getByName(stopAddress), stopPort); s.setSoLinger(false, 0); OutputStream out = s.getOutputStream(); out.write((stopKey + "\r\nstop\r\n").getBytes()); out.flush(); s.close(); } catch (ConnectException e) { log.info("Cassandra not running!"); return; } catch (Exception e) { log.error(e); return; } log.info("Waiting for Cassandra to stop..."); long maxWaiting = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30); boolean stopped = false; while (!stopped && System.currentTimeMillis() < maxWaiting) { TTransport tr = new TFramedTransport(new TSocket(rpcAddress, rpcPort)); try { TProtocol proto = new TBinaryProtocol(tr); Cassandra.Client client = new Cassandra.Client(proto); try { tr.open(); } catch (TTransportException e) { if (e.getCause() instanceof ConnectException) { stopped = true; continue; } log.debug(e.getLocalizedMessage(), e); try { Thread.sleep(500); } catch (InterruptedException e1) { // ignore } } } finally { if (tr.isOpen()) { tr.close(); } } } if (stopped) { log.info("Cassandra has stopped."); } else { log.warn("Gave up waiting for Cassandra to stop."); } }
From source file:org.geosdi.geoplatform.publish.HttpUtilsLocal.java
/** * Send an HTTP request (PUT or POST) to a server. * <BR>Basic auth is used if both username and pw are not null. * <P>/*from w w w .j a va 2 s. c om*/ * Only <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> are accepted as successful codes; in these cases the response string will be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { try { HttpClient client = new HttpClient(); setAuth(client, url, username, pw); // httpMethod = new PutMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); if (requestEntity != null) { httpMethod.setRequestEntity(requestEntity); } int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); // LOGGER.info("================= POST " + url); LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }