Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

In this page you can find the example usage for java.net URLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:ste.xtest.net.BugFreeXTestHandler.java

@Test
public void hostNotFound() throws Exception {
    final UnknownHostException EXCEPTION = new UnknownHostException("test.nowhere.com");
    XTestHandler.exceptionOnConnect = EXCEPTION;

    try {// w w  w  . j a  v a2 s  . co m
        URL url = new URL("xtest://test.nowhere.com");
        URLConnection conn = url.openConnection();
        conn.connect();
        fail("UnknownHostException not thrown");
    } catch (UnknownHostException x) {
        //
        // OK
        //
        assertSame(EXCEPTION, x);
    }

}

From source file:org.apache.hadoop.log.TestLogLevel.java

public void testDynamicLogLevel() throws Exception {
    String logName = TestLogLevel.class.getName();
    Log testlog = LogFactory.getLog(logName);

    //only test Log4JLogger
    if (testlog instanceof Log4JLogger) {
        Logger log = ((Log4JLogger) testlog).getLogger();
        log.debug("log.debug1");
        log.info("log.info1");
        log.error("log.error1");
        assertTrue(!Level.ERROR.equals(log.getEffectiveLevel()));

        HttpServer server = new HttpServer("..", "localhost", 22222, true);
        server.start();// w ww . j a v  a  2  s  . co  m
        int port = server.getPort();

        //servlet
        URL url = new URL("http://localhost:" + port + "/logLevel?log=" + logName + "&level=" + Level.ERROR);
        out.println("*** Connecting to " + url);
        URLConnection connection = url.openConnection();
        connection.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        for (String line; (line = in.readLine()) != null; out.println(line))
            ;
        in.close();

        log.debug("log.debug2");
        log.info("log.info2");
        log.error("log.error2");
        assertTrue(Level.ERROR.equals(log.getEffectiveLevel()));

        //command line
        String[] args = { "-setlevel", "localhost:" + port, logName, "" + Level.DEBUG };
        LogLevel.main(args);
        log.debug("log.debug3");
        log.info("log.info3");
        log.error("log.error3");
        assertTrue(Level.DEBUG.equals(log.getEffectiveLevel()));
    } else {
        out.println(testlog.getClass() + " not tested.");
    }
}

From source file:org.filteredpush.qc.sciname.services.WoRMSService.java

protected void test() throws IOException {
    logger.debug(wormsService.getEndpoint());
    URL test = new URL(wormsService.getEndpoint());
    URLConnection conn = test.openConnection();
    conn.connect();
}

From source file:org.apache.hadoop.hbase.TestInfoServers.java

private String getUrlContent(URL u) throws IOException {
    java.net.URLConnection c = u.openConnection();
    c.connect();
    StringBuilder sb = new StringBuilder();
    BufferedInputStream bis = new BufferedInputStream(c.getInputStream());
    byte[] bytes = new byte[1024];
    for (int read = -1; (read = bis.read(bytes)) != -1;) {
        sb.append(new String(bytes, 0, read));
    }//from ww w.  j  av  a2s. c  om
    bis.close();
    return sb.toString();
}

From source file:net.rptools.maptool.client.WebDownloader.java

/**
 * Read the data at the given URL. This method should not be called on the EDT.
 * // w ww. ja va2  s .  c  o  m
 * @return File pointer to the location of the data, file will be deleted at program end
 */
public String read() throws IOException {
    URLConnection conn = url.openConnection();

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    // Send the request.
    conn.connect();

    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new ByteArrayOutputStream();

        int buflen = 1024 * 30;
        int bytesRead = 0;
        byte[] buf = new byte[buflen];

        for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {
            bytesRead += nRead;
            out.write(buf, 0, nRead);
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    return out != null ? new String(out.toByteArray()) : null;
}

From source file:edu.kit.dama.ui.simon.impl.WebServerProbe.java

@Override
public boolean checkProbe() {
    try {//from   w ww  .  ja v a2 s  .com
        URLConnection con = serverUrl.openConnection();
        con.setConnectTimeout(timeout);
        con.connect();
        String header0 = con.getHeaderField(0);
        return header0 != null && header0.endsWith("200 OK");
    } catch (IOException ex) {
        LOGGER.error("Failed to check Web server probe", ex);
    }
    return false;
}

From source file:ubic.gemma.loader.entrez.pubmed.ExpressionExperimentBibRefFinder.java

/**
 * @param geoSeries// w  w  w  .java  2 s  .c  o  m
 * @return
 */
private int locatePubMedId(String geoSeries) {
    if (!geoSeries.matches("GSE\\d+")) {
        log.warn(geoSeries + " is not a GEO Series Accession");
        return -1;
    }
    URL url = null;

    Pattern pat = Pattern.compile(PUBMEDREF_REGEX);

    try {
        url = new URL(GEO_SERIES_URL_BASE + geoSeries);

        URLConnection conn = url.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            Matcher mat = pat.matcher(line);
            log.debug(line);
            if (mat.find()) {
                String capturedAccession = mat.group(1);
                if (StringUtils.isBlank(capturedAccession))
                    return -1;
                return Integer.parseInt(capturedAccession);
            }
        }
        is.close();
    } catch (MalformedURLException e) {
        log.error(e, e);
        throw new RuntimeException("Invalid URL " + url, e);
    } catch (IOException e) {
        log.error(e, e);
        throw new RuntimeException("Could not get data from remote server", e);
    } catch (NumberFormatException e) {
        log.error(e, e);
        throw new RuntimeException("Could not determine valid pubmed id");
    }

    return -1;

}

From source file:control.services.DownloadPortraitsHttpServiceImpl.java

@Override
public void checkNetworkConnection() throws ConnectException {
    boolean networkAvalaible = false;
    int timeout = 2000;

    try {//from www  .  j  ava2s .  c  o m
        final URL url = new URL(PROTOCOL_HOST + CLASH_HOST);
        final URLConnection conn = url.openConnection();
        conn.connect();
        networkAvalaible = true;

        /*
        InetAddress[] addresses = InetAddress.getAllByName(CLASH_HOST);
        for (InetAddress address : addresses) {
        if (address.isReachable(timeout)) {
            networkAvalaible = true;
        }
        }
        */
    } catch (UnknownHostException e1) {
        LOG.error(e1);
        networkAvalaible = false;
    } catch (IOException e2) {
        LOG.error(e2);
        networkAvalaible = false;
    }

    if (!networkAvalaible) {
        throw new ConnectException();
    }
}

From source file:javarestart.controllers.ApplicationController.java

@RequestMapping(value = "/{applicationName}", params = { "resource" }, method = RequestMethod.GET)
public void loadResource(@RequestParam(value = "resource") String resourceName,
        @PathVariable("applicationName") String applicationName, HttpServletResponse response)
        throws Exception {
    AppResourceProvider resourceProvider = getOrRegisterApp(applicationName);
    URLConnection resource = null;
    try {//from www .ja v  a 2s  .  c  o  m
        resource = resourceProvider.load(resourceName);
        resource.connect();
        response.setContentLength(resource.getContentLength());
        IOUtils.copy(resource.getInputStream(), response.getOutputStream());
        response.flushBuffer();
        logger.info("Class or resource loaded: " + resourceName);
    } catch (ResourceNotFoundException e) {
        logger.warning(e.toString());
        response.sendError(404);
    }
}

From source file:com.pentaho.ctools.cdf.XactionComponent.java

/**
 * ############################### Test Case 3 ###############################
 *
 * Test Case Name:/* w w w. j  av  a2  s. c o m*/
 *    Xacion
 * Description:
 *    We pretend validate the generated graphic (in an image) and if the image
 *    has a valid url.
 * Steps:
 *    1. Check if a graphic was generated
 *    2. Check the http request for the image generated
 */
@Test
public void tc3_GenerateChart_ChartIsDisplayed() {
    // ## Step 1
    WebElement xactionElement = this.elemHelper.FindElement(driver, By.cssSelector("img"));
    assertNotNull(xactionElement);

    String attrSrc = xactionElement.getAttribute("src");
    String attrWidth = xactionElement.getAttribute("width");
    String attrHeight = xactionElement.getAttribute("height");

    assertTrue(attrSrc.startsWith(baseUrl + "getImage?image=tmp_chart_admin-"));
    assertEquals(attrWidth, "500");
    assertEquals(attrHeight, "600");

    // ## Step 2
    try {
        URL url = new URL(attrSrc);
        URLConnection connection = url.openConnection();
        connection.connect();

        assertEquals(HttpStatus.SC_OK, ((HttpURLConnection) connection).getResponseCode());

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}