001 /*
002 * $Id: SocketExceptionHelper.java,v 1.7 2010/09/06 09:19:11 oboehm Exp $
003 *
004 * Copyright (c) 2010 by Oliver Boehm
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 *
018 * (c)reated 12.05.2010 by oliver (ob@oasd.de)
019 */
020
021 package patterntesting.exception.net;
022
023 import java.net.*;
024
025 import org.apache.commons.lang.StringUtils;
026
027 /**
028 * The Class SocketExceptionHelper with some utility methods for better
029 * SocketExceptions or NoRouteToHostExceptions.
030 *
031 * @author oliver
032 * @since 1.0 (12.05.2010)
033 */
034 public final class SocketExceptionHelper {
035
036 /** No need for to instantiate this class (utility class). */
037 private SocketExceptionHelper() {
038 }
039
040 /**
041 * If the given NoRouteToHostException has only the default message
042 * ("No route to host") this message will be replaced by a better one.
043 *
044 * @param e the original NoRouteToHostException
045 * @param connection the connection
046 * @return a NoRouteToHostException which contains the host name or address
047 */
048 public static NoRouteToHostException getBetterNoRouteToHostException(
049 final NoRouteToHostException e, final URLConnection connection) {
050 String msg = e.getMessage();
051 URL url = connection.getURL();
052 if ("No route to host".equalsIgnoreCase(msg)) {
053 msg = "No route to " + url.getHost();
054 } else {
055 msg = msg + " (" + url.getHost() + ")";
056 }
057 return new NoRouteToHostException(msg);
058 }
059
060 /**
061 * The given SocketException is checked if it contains the host in the
062 * error message. If not it is appended.
063 *
064 * @param e the original SocketException
065 * @param connection the URLConnection
066 * @return a better SocketException if in the original the host is missing
067 */
068 public static SocketException getBetterSocketException(final SocketException e,
069 final URLConnection connection) {
070 String msg = e.getMessage();
071 URL url = connection.getURL();
072 String host = url.getHost();
073 if (StringUtils.contains(msg, host)) {
074 return e;
075 }
076 String betterMsg = msg + " (can't connect " + host + ")";
077 return new SocketException(betterMsg);
078 }
079
080 }
081