Example usage for javax.net.ssl HttpsURLConnection getInputStream

List of usage examples for javax.net.ssl HttpsURLConnection getInputStream

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * // ww w. j  a v a2 s. c  o m
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {/*from   w  w  w.j a  v  a  2  s.co  m*/
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
    Log.d("mtm", "downloading json for " + domain + " from " + url);
    try {//from   ww w.ja  v  a 2  s .  co  m
        List<String> results = new ArrayList<>();
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder builder = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            builder.append(inputLine);
        }
        JSONObject jsonObject = new JSONObject(builder.toString());
        in.close();
        int expires = jsonObject.getInt("expires");
        if (expires <= 0) {
            return new ArrayList<>();
        }
        if (maxTtl >= 0) {
            expires = Math.min(maxTtl, expires);
        }
        String redirect;
        try {
            redirect = jsonObject.getString("url");
        } catch (JSONException e) {
            redirect = null;
        }
        if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
            return getPoshFingerprintsFromServer(domain, redirect, expires, false);
        }
        JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
        for (int i = 0; i < fingerprints.length(); i++) {
            JSONObject fingerprint = fingerprints.getJSONObject(i);
            String sha256 = fingerprint.getString("sha-256");
            if (sha256 != null) {
                results.add(sha256);
            }
        }
        writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
        return results;
    } catch (Exception e) {
        Log.d("mtm", "error fetching posh " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:com.nadmm.airports.notams.NotamService.java

private void fetchNotams(String icaoCode, File notamFile) throws IOException {
    String params = String.format(NOTAM_PARAM, icaoCode);

    HttpsURLConnection conn = (HttpsURLConnection) NOTAM_URL.openConnection();
    conn.setRequestProperty("Connection", "close");
    conn.setDoInput(true);//from  ww w  . j  av  a  2 s. co  m
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(30 * 1000);
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US)");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(params.length()));

    // Write out the form parameters as the request body
    OutputStream faa = conn.getOutputStream();
    faa.write(params.getBytes("UTF-8"));
    faa.close();

    int response = conn.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        // Request was successful, parse the html to extract notams
        InputStream in = conn.getInputStream();
        ArrayList<String> notams = parseNotamsFromHtml(in);
        in.close();

        // Write the NOTAMS to the cache file
        BufferedOutputStream cache = new BufferedOutputStream(new FileOutputStream(notamFile));
        for (String notam : notams) {
            cache.write(notam.getBytes());
            cache.write('\n');
        }
        cache.close();
    }
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callGet(String stringUrl) {
    try {//from w  w w .  ja v  a2  s  .  com

        // Setup connection
        URL url = new URL(stringUrl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        //conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        // printHttpsCert(conn);
        conn.connect();
        int code = conn.getResponseCode();

        if (code >= 200 && code < 300) {
            String result = IOUtils.toString(conn.getInputStream());
            conn.disconnect();
            return new String[] { code + "", result };
        } else {
            conn.disconnect();
            return new String[] { code + "", "Server returned " + code + " response code" };
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callGet " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callGet " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);/*from   www .  ja  v  a2s  .co m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());
}

From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java

@Test
@Ignore// w  ww .ja  v a2  s. com
public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception {

    useTestWorkspace("brouder_sylvie");
    login("george.washington", "1234");

    /*
     * upload the test workflow
     */
    MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE,
            new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE));
    MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload(
            "/workflows/import").accept(MediaType.ALL).session(httpSession);
    mockMultipartHttpServletRequestBuilder.file(mockMultipartFile);

    ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder);

    resultActions.andExpect(status().isCreated());

    String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString());
    Map<String, Object> workflow = Helper.deserialize(content, Map.class);
    assertNotNull("workflow is null", workflow);
    Integer workflowId = (Integer) workflow.get("id");

    /*
     * create a project and an experiment to associate the job for the workflow with
     * while doing that, make sure we save all the IDs associated to post it with the job
     */
    MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects")
            .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    Map<String, Object> map = Helper.deserialize(content, Map.class);
    Integer projectId = (Integer) map.get("id");

    mockHttpServletRequestBuilder = post("/experiments")
            .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId
                    + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    map = Helper.deserialize(content, Map.class);
    Integer experimentId = (Integer) map.get("id");

    /*
     * create a job associated with the project, experiment and workflow we just created
     */
    mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString())
            .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString())
            .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isOk());

    /*
     * forwarded to job/submit/jobId
     */
    String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl();
    mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * redirected to jobs/task/jobId
     */
    String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();
    mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * we're at UT1 in the workflow
     */
    String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1);
    TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task");
    String taskId = task.getId();

    String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28";
    String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654";

    // For buttton 1
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    //uriBuilder.queryParam("redirect_uri", "code");
    uriBuilder.queryParam("client_id", username);

    URL url = new URL(uriBuilder.build(true).toUriString());
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    String res = IOUtils.toString(connection.getInputStream());
    Map<String, Object> responseMap = Helper.deserialize(res, Map.class);
    String code = (String) responseMap.get("code");

    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    String uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // For Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    uriBuilder.queryParam("client_id", username);

    url = new URL(uriBuilder.build(true).toUriString());
    connection = (HttpsURLConnection) url.openConnection();
    userpass = username + ":" + password;
    basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    res = IOUtils.toString(connection.getInputStream());
    responseMap = Helper.deserialize(res, Map.class);
    code = (String) responseMap.get("code");

    // For button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // Getting accessToken only from one button
    String accessToken = "";
    String[] urlParts = redirectedUrl.split("&");
    for (String urlPart : urlParts) {
        if (urlPart.contains("accessToken")) {
            String[] accessTokenPair = urlPart.split("=");
            accessToken = accessTokenPair[1];
            break;
        }
    }

    //Button 1
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);
    uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //For getting Storage Files (an abstract button called browsefile3)
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("multiple", true);
    uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    //FileSelect
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam("fileId", 1);
    uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/");

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri, "UTF-8");
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1";

    MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder(
            multipartBoundary);
    multiPartFileContentBuilder.addField("autoGenerated", "true");
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    multiPartFileContentBuilder.addField("isIframe", "true");
    multiPartFileContentBuilder.addField("experimentId", "");
    multiPartFileContentBuilder.addField("projectId", "");
    multiPartFileContentBuilder
            .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", "");
    String taskContent = multiPartFileContentBuilder.build();

    // /rest/objectus post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/")
            .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "")
            .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR";
    multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary);
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    taskContent = multiPartFileContentBuilder.build();

    // /jobs/task post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task")
            .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    deleteDatasetEntries(templateId);
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private JSONObject request(EnumSet<Subscription> subscriptions) throws IOException, JSONException {
    // fetchCookies();

    // TODO: fetch peice by piece
    URL url = new URL("https://www.animenfo.com/radio/index.php?t=" + (new Date()).getTime());
    // URL url = new URL("http://192.168.0.2:12345/");
    String body = "{\"ajaxcombine\":true,\"pages\":[{\"uid\":\"nowplaying\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"playing\"}}"
            + ",{\"uid\":\"queue\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"queue\"}},{\"uid\":\"recent\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"recent\"}}]}";
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Accept-Encoding", "gzip, deflate");
    con.setRequestProperty("Content-Type", "application/json");
    if (!phpSessID.equals(""))
        con.setRequestProperty("Cookie", "PHPSESSID=" + phpSessID);
    con.setRequestProperty("Host", "www.animenfo.com");
    con.setRequestProperty("Referer", "https://www.animenfo.com/radio/nowplaying.php");
    con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.1.0");
    // con.setUseCaches (false);
    con.setDoInput(true);/*ww w . ja  v  a  2 s .  c o m*/
    con.setDoOutput(true);

    //Send request

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    InputStream is = con.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        response.append(line);
    }
    rd.close();

    // updateCookies(con);
    return new JSONObject(response.toString());

}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Downloads the string that's in the url with any certificate.
 *///from   w ww.  j a  v a2s .c om
private String downloadWithoutCA(String url_string) {
    String string = "";
    try {

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        class DefaultTrustManager implements X509TrustManager {

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL url = new URL(url_string);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
        System.out.println("String ignoring certificate = " + string);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        string = formatErrorMessage(R.string.malformed_url);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        e.printStackTrace();
        string = formatErrorMessage(R.string.certificate_error);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return string;
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * Polls the underlying service to return a list of places within the specified
 * radius of the specified Location.//from w  w  w.j a v a  2s. c o m
 *
 * @param location Location
 * @param radius   Radius
 */
protected void refreshPlaces(Location location, int radius, String page_token) {
    if (location == null) {
        Log.e(TAG, "Null location in refreshPlaces");
        return;
    }
    // Log to see if we'll be prefetching the details page of each new place.
    if (mobileData) {
        Log.d(TAG, "Not prefetching due to being on mobile");
    } else if (lowBattery) {
        Log.d(TAG, "Not prefetching due to low battery");
    }

    long currentTime = System.currentTimeMillis();
    URL url;

    String placeTypes = prefs.getString(PlacesConstants.SP_KEY_API_PLACE_TYPES,
            PlacesConstants.SP_KEY_API_PLACE_TYPES_DEFAULT);
    Log.v(TAG, "Doing places search with types: " + placeTypes);

    try {
        // Should be at most 6 decimal places for max cache usage, but 5 is fine too
        // https://developers.google.com/maps/documentation/business/articles/usage_limits

        String locationStr = String.format("%.5f,%.5f", location.getLatitude(), location.getLongitude());

        String baseURI = PlacesConstants.PLACES_LIST_BASE_URI;

        String placesFeed;
        if (page_token != null && page_token.length() > 0) {
            // Other params are actually ignored here.
            placesFeed = baseURI + PlacesConstants.getPlacesAPIKey(this, true) + "&pagetoken=" + page_token;
        } else {
            placesFeed = baseURI + "&types=" + placeTypes + "&location=" + locationStr + "&radius=" + radius
                    + PlacesConstants.getPlacesAPIKey(this, true);
        }
        url = new URL(placesFeed);

        Log.w(TAG, "HTTP request: " + url);

        // Open the connection
        URLConnection connection = url.openConnection();
        HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();

        /*
                    if (connection.getUseCaches()) {
        Log.v(TAG, "Using HTTPS cache");
                    }
                    else {
        Log.v(TAG, "HTTPS cache is disabled");
                    }
        */

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Use the XML Pull Parser to extract each nearby location.
            // TODO Replace the XML parsing to extract your own place list.
            InputStream in = httpConnection.getInputStream();

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();

            int placesAddedThisRequest = 0;

            String next_page_token = "";

            xpp.setInput(in, null);
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("next_page_token")) {
                    next_page_token = xpp.nextText();
                } else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("result")) {
                    eventType = xpp.next();
                    String id = "";
                    String name = "";
                    String vicinity = "";
                    String types = "";
                    String locationLat = "";
                    String locationLng = "";
                    String viewport = "";
                    String icon = "";
                    String reference = "";
                    while (!(eventType == XmlPullParser.END_TAG && xpp.getName().equals("result"))) {
                        if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("name"))
                            name = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("vicinity"))
                            vicinity = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("type"))
                            types = types.equals("") ? xpp.nextText() : types + " " + xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lat"))
                            locationLat = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lng"))
                            locationLng = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("icon"))
                            icon = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("reference"))
                            reference = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("id"))
                            id = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG
                                && xpp.getName().equals("next_page_token"))
                            next_page_token = xpp.nextText();
                        eventType = xpp.next();
                    }

                    Location placeLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
                    placeLocation.setLatitude(Double.valueOf(locationLat));
                    placeLocation.setLongitude(Double.valueOf(locationLng));

                    Log.v(TAG, "Found place: " + " location: " + location + " id: " + id + " name: " + name
                            + " vicinity: " + vicinity + " types: " + types + " ref: " + reference);

                    if (!next_page_token.equals("")) {
                        Log.e(TAG, "WARNING: unhandled next_page_token from Places search " + next_page_token);
                    }

                    // Add each new place to the Places Content Provider
                    addPlace(location, id, name, vicinity, types, placeLocation, viewport, icon, reference,
                            currentTime);
                    placesAddedThisRequest++;
                }
                eventType = xpp.next();
            }

            if (placesAddedThisRequest > 0) {
                Log.i(TAG, "Found " + placesAddedThisRequest + " places this request.");

                if (!next_page_token.equals("")) {
                    // TODO: we should check for INVALID_RESULT and retry after a shorter wait
                    // Currently, if this wait is too long, we waste time, but if it's too short, we don't get the next page.
                    Log.d(TAG, "Sleeping before fetching next page. Sleep interval (ms): "
                            + PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    SystemClock.sleep(PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    Log.i(TAG, "Fetching next page of places results.");
                    refreshPlaces(location, radius, next_page_token);
                }
            } else {
                Log.w(TAG, "Found 0 places this request.");
            }

            // Remove places from the PlacesDetailsContentProvider that aren't from this update.
            String where = PlaceDetailsContentProvider.KEY_LAST_UPDATE_TIME + " < " + currentTime;
            contentResolver.delete(PlacesContentProvider.CONTENT_URI, where, null);

            // Save the last update time and place to the Shared Preferences.
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, (float) location.getLatitude());
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, (float) location.getLongitude());
            prefsEditor.putLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, System.currentTimeMillis());
            sharedPreferenceSaver.savePreferences(prefsEditor, false);
            //prefsEditor.apply();
            //prefsEditor.commit();
        } else
            Log.e(TAG, responseCode + ": " + httpConnection.getResponseMessage());

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage());
    } finally {
    }
}