Example usage for java.net ConnectException getMessage

List of usage examples for java.net ConnectException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:se.vgregion.portal.rss.client.service.RssFetcherServiceImpl.java

/**
 * {@inheritDoc}//  w w  w.ja  va 2 s. c o  m
 * 
 * @throws FetcherException
 */
@Override
public List<SyndFeed> getRssFeeds(Set<String> feedUrls) throws FeedException, IOException, FetcherException {
    List<SyndFeed> syndFeeds = new ArrayList<SyndFeed>();
    if (feedUrls != null) {
        for (String feedLink : feedUrls) {
            // No feed link?
            if (!StringUtils.isBlank(feedLink)) {
                // Continue if feed is black listed
                if (!feedBlackList.contains(feedLink)) {
                    try {
                        URL feedUrl = new URL(feedLink);
                        SyndFeed syndFeed = feedFetcher.retrieveFeed(feedUrl);
                        feedFetcher.getAllInformationFromLatestFeed();
                        syndFeeds.add(syndFeed);
                    } catch (ConnectException e) {
                        feedBlackList.add(feedLink);
                        LOGGER.error("Failed to fetch feed [{}], received error [{}]", feedLink,
                                e.getMessage());
                    }
                } else {
                    LOGGER.warn("Feedlink {" + feedLink + "} is blacklisted. Skipping...");
                }
            }
        }
    }

    /*
     * for (SyndFeed syndFeed : syndFeeds) {
     * 
     * List<SyndEntry> syndEntries = syndFeed.getEntries();
     * 
     * for (SyndEntry syndEntry : syndEntries) { LOGGER.debug("Title " + syndEntry.getTitle());
     * LOGGER.debug("Enclosures " + syndEntry.getEnclosures()); LOGGER.debug("Description " +
     * syndEntry.getDescription()); LOGGER.debug("Source " + syndEntry.getSource()); } }
     */

    return syndFeeds;
}

From source file:com.olmectron.material.utils.MultipartUtility.java

public String sendPostRequest() {

    String respuesta = "";

    String query = "";
    try {//w w w.j  av  a2s. com
        for (int i = 0; i < parameters.size(); i++) {
            MultipartParameter param = parameters.get(i);
            String queryPart = String.format(param.getFieldName() + "=%s",
                    URLEncoder.encode(param.getValue(), charset));

            query = query + queryPart;

            if (i < parameters.size() - 1) {
                query = query + "&";
            }

        }

        // ...

        //System.out.println(query+" --- "+as);

        HttpURLConnection connection = (HttpURLConnection) new URL(requestURL).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
            //output.write(query.getBytes(charset));
            writer.write(query);
        } catch (ConnectException ex) {
            System.err.println(ex.getMessage());
            new MaterialToast("Error al conectar al servidor").unhide();
        }
        //List<String> response = new ArrayList<String>();

        // checks server's status code first
        //int status = httpConn.getResponseCode();
        //if (status == HttpURLConnection.HTTP_OK) {
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                respuesta = respuesta + line;
            }
            reader.close();
            connection.disconnect();

        } catch (SocketException ex) {
            System.err.println(ex.getMessage());
        } //} else {
          //    throw new IOException("Server returned non-OK status: " + status);
          //}

    } catch (UnknownHostException ex) {
        return "Imposible conectar con el servidor";
    } catch (NoRouteToHostException ex) {
        return "Imposible conectar con el servidor";
    }

    catch (IOException ex) {
        Logger.getLogger(MultipartUtility.class.getName()).log(Level.SEVERE, null, ex);
    }
    return respuesta;
}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Mtodo que se puede overridear en el caso de necesitar otro comportamiento al
 * producirse un error de conexin.//w w w  . j  a v  a  2  s .  c  o m
 * 
 * @param request
 * @param response
 * @param method
 * @param e
 * @throws Exception .
 */
protected void onConnectionException(final HttpServletRequest request, final HttpServletResponse response,
        final HttpMethod method, final ConnectException e) throws Exception {
    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
}

From source file:org.apache.hadoop.net.TestNetUtils.java

/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.//from  w w w.  jav  a  2  s . c om
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
    Configuration conf = new Configuration();

    Socket socket = NetUtils.getDefaultSocketFactory(conf).createSocket();
    socket.bind(new InetSocketAddress("localhost", 0));
    System.err.println("local address: " + socket.getLocalAddress());
    System.err.println("local port: " + socket.getLocalPort());
    try {
        NetUtils.connect(socket, new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()), 20000);
        socket.close();
        fail("Should not have connected");
    } catch (ConnectException ce) {
        System.err.println("Got exception: " + ce);
        assertTrue(ce.getMessage().contains("resulted in a loopback"));
    } catch (SocketException se) {
        // Some TCP stacks will actually throw their own Invalid argument
        // exception here. This is also OK.
        assertTrue(se.getMessage().contains("Invalid argument"));
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.io.TcpPacketTransport.java

/**
 * Connect the transport to its remote endpoint
 *///from  w  w  w.  j  a va 2  s.  c  o m
private Socket connect(URI transportURI) throws PacketTransportException {
    String protocol = transportURI.getScheme();
    String host = transportURI.getHost();
    int port = transportURI.getPort();
    int connectTimeout = settings.getIntProperty(FFMQClientSettings.TRANSPORT_TCP_CONNECT_TIMEOUT, 30);

    try {
        Socket socket = SocketUtils.setupSocket(createSocket(protocol), socketSendBufferSize,
                socketRecvBufferSize);

        log.debug("#" + id + " opening a TCP connection to " + host + ":" + port);
        socket.connect(new InetSocketAddress(host, port), connectTimeout * 1000);

        return socket;
    } catch (ConnectException e) {
        log.error("#" + id + " could not connect to " + host + ":" + port + " (timeout=" + connectTimeout
                + "s) : " + e.getMessage());
        throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString());
    } catch (Exception e) {
        log.error(
                "#" + id + " could not connect to " + host + ":" + port + " (timeout=" + connectTimeout + "s)",
                e);
        throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString());
    }
}

From source file:monasca.common.middleware.HttpAuthClient.java

private HttpResponse sendGet(HttpGet httpGet) throws ClientProtocolException {
    HttpResponse response;//  w w w. j  a va2 s .co  m

    if (appConfig.getAdminAuthMethod().equalsIgnoreCase(Config.TOKEN)) {
        httpGet.setHeader(new BasicHeader(TOKEN, appConfig.getAdminToken()));
    } else {
        httpGet.setHeader(new BasicHeader(TOKEN, getAdminToken()));
    }

    try {

        response = client.execute(httpGet);

    } catch (ConnectException c) {
        httpGet.abort();
        throw new ServiceUnavailableException(c.getMessage());
    } catch (IOException e) {
        httpGet.abort();

        throw new ClientProtocolException("IO Exception during GET request ", e);
    }
    return response;
}

From source file:client.ui.Container.java

private Response request(OkHttpClient client, URL url, String json) {
    Response response = null;//from   ww  w .  j a  v  a 2  s  .com

    try {
        log("Requesting: " + client.getProtocols().get(0) + " => " + url.toString());

        Builder builder = new Request.Builder().url(url.toString());
        if (!"".equals(json)) {
            builder.post(RequestBody.create(MediaType.parse("application/json"), json));
        }
        Request request = builder.build();

        response = client.newCall(request).execute();

        log("Completed: " + response.code());

    } catch (ConnectException e) {
        log("\n" + "Failed: " + e.getMessage());
    } catch (IOException e) {
        log("Failed: " + e.getMessage());
    }

    return response;
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

private void initPingThread(final int pingSeconds) {
    this.pingThread = new Thread() {
        @Override/*from   w  ww.  j a va2  s.c  o  m*/
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(1000 * pingSeconds);
                    try {
                        CloseableHttpResponse resp = doExec("rpc.http.ping", null, HttpMethod.GET, null);
                        resp.close();
                    } catch (ConnectException ex) {
                        LOGGER.log(Level.SEVERE, ex.getMessage() + " (" + HttpEndpoint.this.endpoint + ")");
                    } catch (IOException ex) {
                        LOGGER.log(Level.SEVERE, ex.getMessage() + " (" + HttpEndpoint.this.endpoint + ")", ex);
                    }
                } catch (InterruptedException ie) {
                    break;
                }
            }
        }
    };
    this.pingThread.setDaemon(true);
    this.pingThread.start();
}

From source file:noThreads.ParseLevel2.java

/**
 * @param theUrl/*from  w w  w.  ja  v a  2 s  .c  om*/
 * @param conAttempts
 * @return
 * @throws IOException
 */
public boolean validUrl(String theUrl, int conAttempts) throws IOException {
    long total_time = 0, endTime = 0;
    long startTime = System.currentTimeMillis();
    URL link = new URL(theUrl);
    int CONNECT_TIMEOUT = 5000, READ_TIMEOUT = 2000;

    HttpURLConnection huc = (HttpURLConnection) link.openConnection();
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setConnectTimeout(CONNECT_TIMEOUT);
    huc.setReadTimeout(READ_TIMEOUT);
    try {
        huc.connect();

    } catch (java.net.ConnectException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("Connection timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (java.net.SocketTimeoutException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("connect timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (IOException e) {
        print(e.getMessage() + "\n");
        return false;
    }
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(theUrl) == true) {
        print("valid url form");
        if (huc.getContentType() != null) {
            print("Content: " + huc.getContentType());
            if (huc.getContentType().equals("text/html") || huc.getContentType().equals("unknown/unknown")) {
                if (getResposeCode(theUrl, 0) >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
                    print("Server Response Code: " + getResposeCode(theUrl, 0));
                    return false;
                }
            }
            print(huc.getContentType());
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            return true;
        } else {//edw erxetai an den prolavei na diavasei h an einai null to content
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        }
    } else {
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        print("Total elapsed time is :" + total_time + "\n");
        return false;
    }
}

From source file:ubic.gemma.core.loader.protein.StringBiomartGene2GeneProteinLoaderTest.java

@Test
public void testDoLoadRemoteBiomartFileLocalStringFileMultipleTaxon() {
    String testPPis = "/data/loader/protein/string/protein.links.multitaxon.txt";
    URL testPPisURL = this.getClass().getResource(testPPis);

    String biomartTestfile = "/data/loader/protein/biomart/biomart.drerio.and.rat.test.txt";
    URL biomartTestfileURL = this.getClass().getResource(biomartTestfile);

    int counterAssociationsSavedZebra = 0;
    int counterAssociationsSavedRat = 0;

    try {//from   w w  w .ja  va  2  s .c  o m
        stringBiomartGene2GeneProteinAssociationLoader.load(new File(testPPisURL.getFile()), null,
                new File(biomartTestfileURL.getFile()), this.getTaxonToProcess());
    } catch (ConnectException e) {
        log.warn("Connection error, skipping test");
    } catch (IOException e) {
        if (e.getMessage().startsWith("Error from BioMart")) {
            log.warn(e.getMessage());
            return;
        }
    }

    Collection<Gene2GeneProteinAssociation> associations = gene2GeneProteinAssociationService.loadAll();

    assertEquals(6, associations.size());

    for (Gene2GeneProteinAssociation association : associations) {
        gene2GeneProteinAssociationService.thaw(association);
        Gene secondGene = association.getSecondGene();
        secondGene = this.geneService.thaw(secondGene);
        String taxonScientificName = secondGene.getTaxon().getScientificName();
        if (taxonScientificName.equals(zebraFish.getScientificName())) {
            counterAssociationsSavedZebra++;
        } else if (taxonScientificName.equals(rat.getScientificName())) {
            counterAssociationsSavedRat++;
        } else {
            fail();
        }

    }
    assertEquals("Wrong number of rat PPIs", 3, counterAssociationsSavedRat);
    assertEquals("Wrong number of fish PPIs", 3, counterAssociationsSavedZebra);

}