Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

In this page you can find the example usage for java.net UnknownHostException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    boolean retry = true;
    IOException cause = null;/*from  w w w .j  ava2  s. c o  m*/
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can
                // cause a retry which then results in an
                // UnknownHostException
                // while the WI-FI is initialising. The retry logic will be
                // invoked here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems
                // better than outright failure
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(e, ++executionCount, context);
            } catch (NullPointerException e) {
                // there's a bug in HttpClient 4.0.x that on some occasions
                // causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (IOException e) {
                if (isCancelled()) {
                    // Eating exception, as the request was cancelled
                    return;
                }
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry) {
                responseHandler.sendRetryMessage(executionCount);
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }

    // cleaned up to throw IOException
    throw (cause);
}

From source file:derson.com.httpsender.AsyncHttpClient.AsyncHttpRequest.java

private void makeRequestWithRetries() throws HPHttpError {
    boolean retry = true;
    HPHttpError error = null;//from  w ww .ja va2  s  .com
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException
                // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems better than outright failure
                error = new HPNetworkError("????", e);
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (NullPointerException e) {
                // there's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                error = new HPNetworkError("????", e);
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (IOException e) {
                if (isCancelled()) {
                    // Eating exception, as the request was cancelled
                    return;
                }
                error = new HPNetworkError("????", e);
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry && (responseHandler != null)) {
                responseHandler.sendRetryMessage(executionCount);
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        HPLog.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        error = new HPNetworkError("????");
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }

    // cleaned up to throw IOException
    throw error;
    //        throw (cause);
}

From source file:org.pentaho.di.trans.steps.httppost.HTTPPOST.java

private Object[] callHTTPPOST(Object[] rowData) throws KettleException {
    // get dynamic url ?
    if (meta.isUrlInField()) {
        data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);
    }//from   ww w. jav a  2  s  .c o m

    FileInputStream fis = null;
    try {
        if (isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ConnectingToURL", data.realUrl));
        }

        // Prepare HTTP POST
        //
        HttpClient HTTPPOSTclient = SlaveConnectionManager.getInstance().createHttpClient();
        PostMethod post = new PostMethod(data.realUrl);
        // post.setFollowRedirects(false);

        // Set timeout
        if (data.realConnectionTimeout > -1) {
            HTTPPOSTclient.getHttpConnectionManager().getParams()
                    .setConnectionTimeout(data.realConnectionTimeout);
        }
        if (data.realSocketTimeout > -1) {
            HTTPPOSTclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout);
        }

        if (!Const.isEmpty(data.realHttpLogin)) {
            HTTPPOSTclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin,
                    data.realHttpPassword);
            HTTPPOSTclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        }

        HostConfiguration hostConfiguration = new HostConfiguration();
        if (!Const.isEmpty(data.realProxyHost)) {
            hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort);
        }
        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed by the POSTMethod
        if (!data.contentTypeHeaderOverwrite) { // can be overwritten now
            if (Const.isEmpty(data.realEncoding)) {
                post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML);
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE,
                            CONTENT_TYPE_TEXT_XML));
                }
            } else {
                post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding);
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE,
                            CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding));
                }
            }
        }

        // HEADER PARAMETERS
        if (data.useHeaderParameters) {
            // set header parameters that we want to send
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                post.addRequestHeader(data.headerParameters[i].getName(),
                        data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue",
                            data.headerParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }

        // BODY PARAMETERS
        if (data.useBodyParameters) {
            // set body parameters that we want to send
            for (int i = 0; i < data.body_parameters_nrs.length; i++) {
                data.bodyParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.BodyValue",
                            data.bodyParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])));
                }
            }
            post.setRequestBody(data.bodyParameters);
        }

        // QUERY PARAMETERS
        if (data.useQueryParameters) {
            for (int i = 0; i < data.query_parameters_nrs.length; i++) {
                data.queryParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.QueryValue",
                            data.queryParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])));
                }
            }
            post.setQueryString(data.queryParameters);
        }

        // Set request entity?
        if (data.indexOfRequestEntity >= 0) {
            String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity);
            // Request content will be retrieved directly
            // from the input stream
            // Per default, the request content needs to be buffered
            // in order to determine its length.
            // Request body buffering can be avoided when
            // content length is explicitly specified

            if (meta.isPostAFile()) {
                File input = new File(tmp);
                fis = new FileInputStream(input);
                post.setRequestEntity(new InputStreamRequestEntity(fis, input.length()));
            } else {
                if ((data.realEncoding != null) && (data.realEncoding.length() > 0)) {
                    post.setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(tmp.getBytes(data.realEncoding)), tmp.length()));
                } else {
                    post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()),
                            tmp.length()));
                }
            }
        }

        // Execute request
        //
        InputStreamReader inputStreamReader = null;
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();

            // Execute the POST method
            int statusCode = HTTPPOSTclient.executeMethod(hostConfiguration, post);

            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;

            if (isDetailed()) {
                logDetailed(
                        BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseTime", responseTime, data.realUrl));
            }

            // Display status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseCode", String.valueOf(statusCode)));
            }
            String body = null;
            if (statusCode != -1) {
                if (statusCode == 204) {
                    body = "";
                } else {
                    // if the response is not 401: HTTP Authentication required
                    if (statusCode != 401) {

                        // Use request encoding if specified in component to avoid strange response encodings
                        // See PDI-3815
                        String encoding = data.realEncoding;

                        // Try to determine the encoding from the Content-Type value
                        //
                        if (Const.isEmpty(encoding)) {
                            String contentType = post.getResponseHeader("Content-Type").getValue();
                            if (contentType != null && contentType.contains("charset")) {
                                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "")
                                        .replace("\"", "").trim();
                            }
                        }

                        // Get the response, but only specify encoding if we've got one
                        // otherwise the default charset ISO-8859-1 is used by HttpClient
                        if (Const.isEmpty(encoding)) {
                            if (isDebug()) {
                                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", "ISO-8859-1"));
                            }
                            inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream());
                        } else {
                            if (isDebug()) {
                                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", encoding));
                            }
                            inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream(), encoding);
                        }

                        StringBuffer bodyBuffer = new StringBuffer();

                        int c;
                        while ((c = inputStreamReader.read()) != -1) {
                            bodyBuffer.append((char) c);
                        }
                        inputStreamReader.close();

                        // Display response
                        body = bodyBuffer.toString();

                        if (isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseBody", body));
                        }
                    } else { // the status is a 401
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "HTTPPOST.Exception.Authentication", data.realUrl));

                    }
                }
            }
            int returnFieldsOffset = data.inputRowMeta.size();
            if (!Const.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }

            if (!Const.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Const.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
            }
        } finally {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
            if (data.realcloseIdleConnectionsTime > -1) {
                HTTPPOSTclient.getHttpConnectionManager()
                        .closeIdleConnections(data.realcloseIdleConnectionsTime);
            }
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "HTTPPOST.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.CanNotReadURL", data.realUrl), e);

    } finally {
        if (fis != null) {
            BaseStep.closeQuietly(fis);
        }
    }
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Cette mthode permet l'envoie d'une commande  ClamAV et retourne le rsultat sous la forme d'une
 * chaine de caractre.//from   w ww  . j a v  a 2  s . co  m
 *
 * @param command
 *            - la commade  transmettre
 * @param strEndDetection
 *            - la chaine de caractre permettant de dtecter la dernire ligne du retour.
 * @return La rponse de clamAV sans traitement
 * @throws ClamAVException
 *             the clam av exception
 */
private ClamAvResponse callClamAV(final TypeResponse command, final String strEndDetection)
        throws ClamAVException {

    ClamAvResponse result;

    final StringBuilder resultat = new StringBuilder();
    final Date dateDebut = new Date();
    Socket socket = null;
    BufferedReader buffer = null;

    try {
        socket = this.connect(command);
        if (socket == null) {
            result = ClamAvResponse.createNoServiceResponse();
        } else {
            // timeout pour l'ensemble des oprations sur la
            // socket
            socket.setSoTimeout(this.timeout);
            final InputStream input = socket.getInputStream();
            final OutputStream ouput = socket.getOutputStream();

            // envoi de la commande  clamAV
            ouput.write(("n" + command.toString() + "\n").getBytes(UTF_8));

            // Attente et traitement de la rponse
            buffer = new BufferedReader(new InputStreamReader(input, UTF_8));

            String retour = "";
            int indexResultat = -1;
            while (retour != null && indexResultat == -1) {
                retour = buffer.readLine();
                if (retour != null) {
                    indexResultat = retour.indexOf(strEndDetection);
                    resultat.append(retour);
                    resultat.append('\n');
                }
            }
            ClamAVCheckService.LOGGER.debug("Retour ClamAV (en {} ms) :\n{}",
                    new Date().getTime() - dateDebut.getTime(), resultat);
            result = this.traitementReponseClamAV(resultat.toString(), command);
        }
    } catch (final UnknownHostException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } catch (final IOException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } finally {
        this.safeClose(command, socket, buffer);
    }

    return result;
}

From source file:com.louding.frame.http.download.SimpleDownloader.java

/**
 * /*from w ww. j  a v  a 2s.  co m*/
 * 
 * @param request
 * @throws IOException
 */
private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }
        if (fileLen > 0) {
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
        }
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                if (!isCancelled()) {
                    handleResponse(response);
                }
            }
            return;
        } catch (UnknownHostException e) {
            publishProgress(UPDATE_FAILURE, e, 0, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // HttpClient 4.0.x ?bug
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (Exception e) {
            cause = new IOException("Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }
    if (cause != null) {
        throw cause;
    } else {
        throw new IOException("");
    }
}

From source file:com.qcadoo.maven.plugins.validator.ValidatorMojo.java

private void validateSchema(final String file) throws MojoFailureException {
    try {// ww w.  j av  a 2s. co  m
        getLog().info("Validating file: " + file);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        try {
            URL url = new URL("http://www.qcadoo.com");
            url.openConnection();
            factory.setValidating(true);
        } catch (UnknownHostException e) {
            factory.setValidating(false);
        } catch (IOException e) {
            factory.setValidating(false);
        }

        factory.setValidating(false);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        DocumentBuilder parser = factory.newDocumentBuilder();
        parser.setErrorHandler(new ValidationErrorHandler());
        parser.parse(new File(file));

    } catch (ParserConfigurationException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    } catch (SAXException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    } catch (IOException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    }
}

From source file:org.apache.nifi.web.api.DataTransferResource.java

private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
        final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {/*from   www.j av  a2  s.  c o  m*/
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream,
            outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private CensorPayload checkURL(String checkURL) throws IllegalArgumentException, URISyntaxException {
    if (!checkURL.startsWith("http"))
        checkURL = "http://" + checkURL;

    CensorPayload censorPayload = new CensorPayload(checkURL);

    Uri mUri = Uri.parse(checkURL);/*from  w ww. j  av a 2s . c  o m*/

    if (null == mUri.getEncodedQuery()) {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath();
    } else {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath() + "?"
                + URLEncoder.encode(mUri.getEncodedQuery());
    }

    Log.e("Checking url", checkURL);

    client = new DefaultHttpClient();

    /*headRequest = new HttpHead(checkURL);
    headRequest.setHeader("User-Agent", "OONI Android Probe");*/

    httpGet = new HttpGet(checkURL);
    httpGet.setHeader("User-Agent", "OONI Android Probe");

    try {
        //response = client.execute(headRequest);
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse httpResponse, HttpContext httpContext)
                    throws HttpException, IOException {
                if (httpResponse.getStatusLine().getStatusCode() == 302
                        || httpResponse.getStatusLine().getStatusCode() == 301) {
                    for (Header hdr : httpResponse.getAllHeaders()) {
                        if (hdr.getName().equals("Location")) {
                            /*if (hdr.getValue().equals("http://ee-outage.s3.amazonaws.com/content-blocked/content-blocked-v1.html") ||
                            hdr.getValue().contains("http://ee-outage.s3.amazonaws.com"))
                            {
                            Log.e("Blocked", "Blocked by EE");
                            throw new CensoredException("Blocked by EE", "EE", 100);
                            }
                            else if (hdr.getValue().contains("http://www.t-mobile.co.uk/service/wnw-mig/entry/") ||
                                 hdr.getValue().contains("http://tmobile.ee.co.uk/common/system_error_pages/outage_wnw.html"))
                            {
                            Log.e("Blocked", "Blocked by TMobile");
                            throw new CensoredException("Blocked by TMobile", "TMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://online.vodafone.co.uk/dispatch/Portal/ContentControlServlet?type=restricted"))
                            {
                            Log.e("Blocked", "Blocked by Vodafone");
                            throw new CensoredException("Blocked by Vodafone", "Vodafone", 100);
                            }
                            else if (hdr.getValue().contains("http://blockpage.bt.com/pcstaticpage/blocked.html"))
                            {
                            Log.e("Blocked", "Blocked by BT");
                            throw new CensoredException("Blocked by BT", "BT", 100);
                            }
                            else if (hdr.getValue().contains("http://www.talktalk.co.uk/notice/parental-controls?accessurl"))
                            {
                            Log.e("Blocked", "Blocked by TalkTalk");
                            throw new CensoredException("Blocked by TalkTalk", "TalkTalk", 100);
                            }
                            else if (hdr.getValue().contains("http://www.plus.net/support/security/abuse/blocked.shtml"))
                            {
                            Log.e("Blocked", "Blocked by PlusNet");
                            throw new CensoredException("Blocked by PlusNet", "PlusNet", 100);
                            }
                            else if (hdr.getValue().contains("http://mobile.three.co.uk/pc/Live/pcreator/live/100004/pin/blocked?"))
                            {
                            Log.e("Blocked", "Blocked by Three");
                            throw new CensoredException("Blocked by Three", "Three", 100);
                            }
                            else if (hdr.getValue().contains("http://m.virginmedia.com/MiscPages/AdultWarning.aspx"))
                            {
                            Log.e("Blocked", "Blocked by VirginMobile");
                            throw new CensoredException("Blocked by VirginMobile", "VirginMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://assets.o2.co.uk/18plusaccess/"))
                            {
                            Log.e("Blocked", "Blocked by O2");
                            throw new CensoredException("Blocked by O2", "O2", 100);
                            }*/
                            api.checkHeader(hdr);
                        }
                    }
                }

                /*Log.e("intercepted return code",httpResponse.getStatusLine().toString());
                        
                for(Header hdr : httpResponse.getAllHeaders())
                {
                Log.e("intercepted header",hdr.getName().toString() + " / " + hdr.getValue().toString());
                }
                Log.e("intercepted header","------------------\r\n------------------\r\n------------------\r\n------------------\r\n------------------\r\n");*/

            }
        });
        response = client.execute(httpGet);
    }
    //This is the best case scenario!
    catch (CensoredException CE) {
        censorPayload.consumeCensoredException(CE);
        return censorPayload;
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        censorPayload.consumeError(uhe.getMessage());
        return censorPayload;
    } catch (ConnectTimeoutException CTE) {
        CTE.printStackTrace();
        censorPayload.consumeError(CTE.getMessage());
        return censorPayload;
    } catch (NoHttpResponseException NHRE) {
        NHRE.printStackTrace();
        censorPayload.consumeError(NHRE.getMessage());
        return censorPayload;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        censorPayload.consumeError(ioe.getMessage());
        return censorPayload;
    } catch (IllegalStateException ise) {
        ise.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    } catch (Exception e) {
        e.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    }

    int statusCode = response.getStatusLine().getStatusCode();

    censorPayload.setReturnCode(statusCode);

    Log.e("checkURL code", Integer.toString(statusCode));
    if (statusCode == 403 || statusCode == 404) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(25);
        return censorPayload;
    } else if (statusCode == 504 || statusCode == 503 || statusCode == 500) {
        censorPayload.consumeError("Server Issue " + Integer.toString(statusCode));
        return censorPayload;
    }

    String phrase = response.getStatusLine().getReasonPhrase();

    Log.e("checkURL phrase", phrase);

    if (phrase.contains("orbidden")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(50);
        return censorPayload;
    }

    if (phrase.contains("blocked")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(100);
        return censorPayload;
    }

    for (Header hdr : response.getAllHeaders()) {
        Log.e("checkURL header", hdr.getName() + " / " + hdr.getValue());
    }

    censorPayload.setCensored(false);
    censorPayload.setConfidence(1);
    return censorPayload;
}

From source file:org.apache.stratos.cartridge.agent.registrant.RegistrantUtil.java

/**
 * Before adding a member, we will try to verify whether we can connect to it
 *
 * @param registrant The member whose connectvity needs to be verified
 * @return true, if the member can be contacted; false, otherwise.
 *//*w w w  . j  ava 2s  .co  m*/
public static boolean isHealthy(Registrant registrant) {
    if (log.isDebugEnabled()) {
        log.debug("Trying to connect to registrant " + registrant + "...");
    }
    if (log.isDebugEnabled()) {
        log.debug("***********************************************isHealthy() method for registrant "
                + registrant);
    }
    String registrantRemoteHost = registrant.getRemoteHost();
    log.debug("remote host : " + registrantRemoteHost);
    if (registrantRemoteHost == null) {
        registrantRemoteHost = "localhost";
    }
    InetAddress addr;
    try {
        addr = InetAddress.getByName(registrantRemoteHost);
        if (log.isDebugEnabled()) {
            log.debug("***********************************************Host resolved for registrant "
                    + registrant);
        }
    } catch (UnknownHostException e) {
        log.error("Registrant " + registrant + " is unhealthy");
        return false;
    }
    PortMapping[] portMappings = registrant.getPortMappings();

    int maxRetries = Integer.parseInt(System.getProperty("clustering.maxRetries"));

    for (int retries = maxRetries; retries > 0; retries--) {
        try {
            for (PortMapping portMapping : portMappings) {
                int port = portMapping.getPrimaryPort();
                if (log.isDebugEnabled()) {
                    log.debug("***********************************************primary port" + port
                            + " registrant " + registrant);
                }
                if (port != -1 && port != 0) {
                    if (log.isDebugEnabled()) {
                        log.debug("***********************************************connecting to " + registrant
                                + " re-try: " + retries);
                    }
                    SocketAddress httpSockaddr = new InetSocketAddress(addr, port);
                    new Socket().connect(httpSockaddr, 10000);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "***********************************************connected successfully to port: "
                                        + port);
                    }
                }
            }
            return true;
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error occurred.. " + e.getMessage());
            }
            String msg = e.getMessage();
            if (!msg.contains("Connection refused") && !msg.contains("connect timed out")) {
                String msg2 = "Cannot connect to registrant " + registrant;
                log.error(msg2, e);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignored) {
            }
        }
    }
    return false;
}