Example usage for java.net HttpURLConnection getContent

List of usage examples for java.net HttpURLConnection getContent

Introduction

In this page you can find the example usage for java.net HttpURLConnection getContent.

Prototype

public Object getContent() throws IOException 

Source Link

Document

Retrieves the contents of this URL connection.

Usage

From source file:blueprint.sdk.google.gcm.GcmSender.java

/**
 * decodes response from GCM/*from   w ww.  j a  v a2s .c  o  m*/
 *
 * @param http HTTP connection
 * @return response from GCM
 * @throws IOException
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
private GcmResponse decodeResponse(HttpURLConnection http) throws IOException {
    GcmResponse result = new GcmResponse();
    result.code = getResponseCode(http);

    if (result.code == HttpURLConnection.HTTP_OK) {
        try {
            Response response = mapper.readValue((InputStream) http.getContent(), Response.class);
            result.multicastId = response.multicast_id;
            result.success = response.success;
            result.failure = response.failure;
            result.canonicalIds = response.canonical_ids;

            // decode 'results'
            for (Map<String, String> item : response.results) {
                GcmResponseDetail detail = new GcmResponseDetail();

                if (item.containsKey("message_id")) {
                    detail.success = true;
                    detail.message = item.get("message_id");
                } else {
                    detail.success = false;
                    detail.message = item.get("error");
                }

                result.results.add(detail);
            }
        } catch (Exception e) {
            result.code = GcmResponse.ERR_JSON_BIND;

            L.warn("Can't bind json", e);
        }
    } else if (result.code == GcmResponse.ERR_NOT_JSON) {
        int contentLength = http.getContentLength();
        String contentType = http.getContentType();

        InputStream ins = (InputStream) http.getContent();
        byte[] buffer = new byte[contentLength];
        ins.read(buffer);

        L.warn("response message is not a json. content-type=" + contentType + ", content="
                + new String(buffer));
    }

    return result;
}

From source file:org.overlord.sramp.governance.services.NotificationResourceTest.java

/**
 * This is an integration test, and only works if artifact 'e67e1b09-1de7-4945-a47f-45646752437a'
  * exists in the repo; check the following urls to find out:
  * /* ww w .jav  a  2  s .c o  m*/
 * http://localhost:8080/s-ramp-server/s-ramp?query=/s-ramp[@uuid%3D'e67e1b09-1de7-4945-a47f-45646752437a']
 * http://localhost:8080/s-ramp-server/s-ramp/user/BpmnDocument/e67e1b09-1de7-4945-a47f-45646752437a
 * 
 * @throws Exception
 */
@Test
@Ignore
public void testNotify() {
    try {
        String notificationUrl = "/dtgov/notify/email/dev/deployed/dev/${uuid}"; //$NON-NLS-1$
        String uuid = "3c7bb7f7-a811-4080-82db-5ece86993a11"; //$NON-NLS-1$
        URL url = new URL(generateURL(notificationUrl.replace("${uuid}", uuid))); //$NON-NLS-1$
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            System.out.println("reply=" + reply); //$NON-NLS-1$
        } else {
            System.err.println("endpoint could not be reached"); //$NON-NLS-1$
            Assert.fail();
        }

    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }

}

From source file:org.overlord.sramp.governance.services.DeploymentResourceTest.java

/**
 * This is an integration test, and only works if artifact 'e67e1b09-1de7-4945-a47f-45646752437a'
  * exists in the repo; check the following urls to find out:
  *//from   w ww . j  a v  a  2 s . c o  m
 * http://localhost:8080/s-ramp-server/s-ramp?query=/s-ramp[@uuid%3D'e67e1b09-1de7-4945-a47f-45646752437a']
 * http://localhost:8080/s-ramp-server/s-ramp/user/BpmnDocument/e67e1b09-1de7-4945-a47f-45646752437a
 *
 * @throws Exception
 */
@Test
@Ignore
public void testDeployCopy() {
    try {
        URL url = new URL(generateURL("/deploy/copy/dev/e67e1b09-1de7-4945-a47f-45646752437a")); //$NON-NLS-1$
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            System.out.println("reply=" + reply); //$NON-NLS-1$
        } else {
            System.err.println("endpoint could not be reached"); //$NON-NLS-1$
            Assert.fail();
        }

    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}

From source file:com.opentransport.rdfmapper.nmbs.NetworkDisturbanceFetcher.java

private void scrapeNetworkDisturbanceWebsite(String language, String _url) {
    Document doc;/*from   w  w w .j  av a 2s.co m*/
    int i = 0;
    //English Version
    try {
        URL url = new URL(_url);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        // Convert to a JSON object to print data
        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
        JsonArray disturbances = root.getAsJsonObject().getAsJsonArray("him");

        for (JsonElement el : disturbances) {
            JsonObject obj = (JsonObject) el;

            String header = obj.get("header").getAsString();
            String description = obj.get("text").getAsString();
            String urls = ""; // todo check JsonNull

            String begin = obj.get("begin").getAsString(); // dd.MM.yyyy HH:mm
            String end = obj.get("end").getAsString(); // dd.MM.yyyy HH:mm
            SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm");
            df.setTimeZone(TimeZone.getTimeZone("Europe/Brussels"));

            Date date;
            long startEpoch, endEpoch;
            try {
                date = df.parse(begin);
                startEpoch = date.getTime() / 1000;
                date = df.parse(end);
                endEpoch = date.getTime() / 1000;
            } catch (ParseException ex) {
                // When time range is missing, take 12 hours before and after
                startEpoch = new Date().getTime() - 43200;
                endEpoch = new Date().getTime() + 43200;

                Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }

            int startStationId, endStationId, impactStationId;
            if (obj.has("startstation_extId")) {
                startStationId = obj.get("startstation_extId").getAsInt();
            } else {
                startStationId = -1;
            }
            if (obj.has("endstation_extId")) {
                endStationId = obj.get("endstation_extId").getAsInt();
            } else {
                endStationId = -1;
            }
            if (obj.has("impactstation_extId")) {
                impactStationId = obj.get("impactstation_extId").getAsInt();
            } else {
                impactStationId = -1;
            }

            String id = obj.get("id").getAsString();

            NetworkDisturbance disturbance = new NetworkDisturbance(header, description, urls, language,
                    startEpoch, endEpoch, startStationId, endStationId, impactStationId, id);

            networkDisturbances.add(disturbance);
        }

    } catch (IOException ex) {
        Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
        errorWriter.writeError(ex.toString());
    }

}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

private String connect(String strURL) throws Exception {
    URL url = new URL(strURL);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    m_consumer.sign(request);//from   ww  w  .  jav a 2  s .  c  o  m

    request.connect();

    if (request.getResponseCode() == 200) {

        String strResponse = "";
        InputStreamReader in = new InputStreamReader((InputStream) request.getContent());
        BufferedReader buff = new BufferedReader(in);

        for (String strLine = ""; strLine != null; strLine = buff.readLine()) {
            strResponse += strLine + "\n";
        }
        in.close();

        return strResponse;
    } else {
        throw new Exception(
                "Mendeley Server returned " + request.getResponseCode() + ": " + request.getResponseMessage());
    }

}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

private String getRemoteData(URL url, Map<String, String> parameters)
        throws ClientDoesNotHavePermissionException {
    try {// w ww  . ja v  a2s  . c o m
        parameters.put(ExternalDatabaseDefinitions.PARAMETER_CLIENT, client);
        HttpURLConnection connection = setupConnection(url, parameters);
        connection.connect();
        String response = parseResponse(connection.getContent());
        connection.disconnect();
        return response;
    } catch (IOException ignore) {
        return null;
    }
}

From source file:de.rallye.test.GroupsTest.java

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override/* w w  w.j a  v  a  2  s.c o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            assertEquals("Should be right Realm", "RallyeNewUser", realm);
            return new PasswordAuthentication(String.valueOf(1), "test".toCharArray());
        }
    });
    URL url = new URL("http://127.0.0.1:10111/groups/1");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    //      conn.setFixedLengthStreamingMode(post.length);
    conn.getOutputStream().write(MockDataAdapter.validLogin.getBytes());

    int code = conn.getResponseCode();

    Authenticator.setDefault(null);

    try {
        assertEquals("Code should be 200", 200, code);
    } catch (AssertionError e) {
        System.err.println("This is the content:");
        List<String> contents = IOUtils.readLines((InputStream) conn.getContent());
        for (String line : contents)
            System.err.println(line);
        throw e;
    }

}

From source file:de.mpg.escidoc.services.syndication.feed.Feed.java

/**
 * Search for the items for feed entries population. 
 * The HTTP request to the SearchAndExport WEB interface is used 
 * @param query is CQL query./* w  w w.  j  a va2 s .  com*/
 * @param maximumRecords is the limit of the search 
 * @param sortKeys 
 * @return item list XML
 * @throws SyndicationException
 */
private String performSearch(String query, String maximumRecords, String sortKeys) throws SyndicationException {
    URL url;
    try {
        url = new URL(paramHash.get("${baseUrl}") + "/search/SearchAndExport?" + "cqlQuery="
                + URLEncoder.encode(query, "UTF-8") + "&maximumRecords="
                + URLEncoder.encode(maximumRecords, "UTF-8") + "&sortKeys="
                + URLEncoder.encode(sortKeys, "UTF-8") + "&exportFormat=ESCIDOC_XML_V13"
                + "&sortOrder=descending" + "&language=all");
    } catch (Exception e) {
        throw new SyndicationException("Wrong URL:", e);
    }

    Object content;
    URLConnection uconn;

    try {
        uconn = ProxyHelper.openConnection(url);
        if (!(uconn instanceof HttpURLConnection))
            throw new IllegalArgumentException("URL protocol must be HTTP.");
        HttpURLConnection conn = (HttpURLConnection) uconn;

        InputStream stream = conn.getErrorStream();
        if (stream != null) {
            conn.disconnect();
            throw new SyndicationException(Utils.getInputStreamAsString(stream));
        } else if ((content = conn.getContent()) != null && content instanceof InputStream)
            content = Utils.getInputStreamAsString((InputStream) content);
        else {
            conn.disconnect();
            throw new SyndicationException("Cannot retrieve content from the HTTP response");
        }
        conn.disconnect();

        return (String) content;
    } catch (Exception e) {
        throw new SyndicationException(e);
    }

}

From source file:net.maritimecloud.identityregistry.utils.KeycloakServiceAccountUtil.java

/**
 * Get IDP info by parsing info from wellKnownUrl json
 * //  w  ww .j a v a  2s  . c  o m
 * @param wellKnownUrl The url to parse
 * @return
 */
private IdentityProviderRepresentation getIdpFromWellKnownUrl(String wellKnownUrl) {
    // Get IDP info by parsing info from wellKnownUrl json
    URL url;
    try {
        url = new URL(wellKnownUrl);
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    HttpURLConnection request;
    try {
        request = (HttpURLConnection) url.openConnection();
        request.connect();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    Map<String, Object> idpData;
    try {
        //idpData = this.jsonMapper.readValue(new InputStreamReader((InputStream) request.getContent()), Map.class);
        idpData = JsonSerialization.readValue((InputStream) request.getContent(), Map.class);
        /*} catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;*/
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    // Extract the endpoints from the json
    String authEndpoint = (String) idpData.get("authorization_endpoint");
    String tokenEndpoint = (String) idpData.get("token_endpoint");
    String userInfoEndpoint = (String) idpData.get("userinfo_endpoint");
    String endSessionEndpoint = (String) idpData.get("end_session_endpoint");
    String issuer = (String) idpData.get("issuer");

    // Insert data into IDP data structure
    IdentityProviderRepresentation idp = new IdentityProviderRepresentation();
    idp.setEnabled(true);
    idp.setProviderId("keycloak-oidc"); // can be "keycloak-oidc","oidc" or "saml"
    idp.setTrustEmail(false);
    idp.setStoreToken(false);
    idp.setAddReadTokenRoleOnCreate(false);
    idp.setAuthenticateByDefault(false);
    idp.setFirstBrokerLoginFlowAlias("first broker login");
    Map<String, String> IDPConf = new HashMap<String, String>();
    IDPConf.put("userInfoUrl", userInfoEndpoint);
    IDPConf.put("validateSignature", "true");
    IDPConf.put("tokenUrl", tokenEndpoint);
    IDPConf.put("authorizationUrl", authEndpoint);
    IDPConf.put("logoutUrl", endSessionEndpoint);
    IDPConf.put("issuer", issuer);
    idp.setConfig(IDPConf);
    return idp;
}

From source file:org.kie.smoke.wb.rest.KieRemoteRestSmokeIntegrationTest.java

@Test
public void testUrlsGetDeployments() throws Exception {
    // test with normal RestRequestHelper
    String user = TestConstants.MARY_USER;
    String password = TestConstants.MARY_PASSWORD;

    JaxbDeploymentUnitList depList = get(deploymentUrl, "rest/deployment/", mediaType, 200, user, password,
            JaxbDeploymentUnitList.class);

    assertNotNull("Null answer!", depList);
    assertNotNull("Null deployment list!", depList.getDeploymentUnitList());
    assertTrue("Empty deployment list!", depList.getDeploymentUnitList().size() > 0);

    String deploymentId = depList.getDeploymentUnitList().get(0).getIdentifier();
    JaxbDeploymentUnit dep = get(deploymentUrl, "rest/deployment/" + deploymentId, mediaType, 200, user,
            password, JaxbDeploymentUnit.class);

    assertNotNull("Null answer!", dep);
    assertNotNull("Null deployment list!", dep);
    assertEquals("Empty status!", JaxbDeploymentUnit.JaxbDeploymentStatus.DEPLOYED, dep.getStatus());

    // test with HttpURLConnection
    URL url = new URL(deploymentUrl, deploymentUrl.getPath() + "rest/deployment/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    String authString = user + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    connection.setRequestMethod("GET");

    logger.debug(">> [GET] " + url.toExternalForm());
    connection.connect();/*from w w  w.j av a 2 s  .c  o  m*/
    int respCode = connection.getResponseCode();
    if (200 != respCode) {
        logger.warn(connection.getContent().toString());
    }
    assertEquals(200, respCode);

    JaxbSerializationProvider jaxbSerializer = ClientJaxbSerializationProvider.newInstance();
    String xmlStrObj = getConnectionContent(connection.getContent());
    depList = (JaxbDeploymentUnitList) jaxbSerializer.deserialize(xmlStrObj);

    assertNotNull("Null answer!", depList);
    assertNotNull("Null deployment list!", depList.getDeploymentUnitList());
    assertTrue("Empty deployment list!", depList.getDeploymentUnitList().size() > 0);
}