Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

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

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:edu.xjtu.qxcamerabridge.LiveviewImageExtractor.java

private static InputStream getLiveviewInputStream(String liveviewURL)
        throws MalformedURLException, IOException {
    URL url = new URL(liveviewURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(2000);//from   w ww  .  ja va 2 s . c  o m
    connection.connect();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return connection.getInputStream();
    }
    return null;
}

From source file:com.atlassian.launchpad.jira.whiteboard.WhiteboardTabPanel.java

@Override
public List<IssueAction> getActions(Issue issue, User remoteUser) {
    List<IssueAction> messages = new ArrayList<IssueAction>();

    //retrieve and validate url from custom field
    CustomField bpLinkField = ComponentAccessor.getCustomFieldManager()
            .getCustomFieldObjectByName(LAUNCHPAD_URL_FIELD_NAME);

    if (bpLinkField == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" custom field not available. Cannot process Gerrit Review comments"));
        return messages;
    }// w  w w  .ja v  a2s .com

    Object bpURLFieldObj = issue.getCustomFieldValue(bpLinkField);
    if (bpURLFieldObj == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" not provided. Please provide the Launchpad URL to view the whiteboard for this issue."));
        return messages;
    }

    String bpURL = bpURLFieldObj.toString().trim();

    if (bpURL.length() == 0) {
        messages.add(
                new GenericMessageAction("To view the Launchpad Blueprint for this issue please provide the "
                        + LAUNCHPAD_URL_FIELD_NAME));
        return messages;
    }

    if (!bpURL.matches(URL_REGEX)) {
        messages.add(new GenericMessageAction(
                "Launchpad URL not properly formatted. Please provide URL that appears as follows:<br/> https://blueprints.launchpad.net/devel/PROJECT NAME/+spec/BLUEPRINT NAME"));
        return messages;
    }

    String apiQuery = bpURL.substring(
            (bpURL.lastIndexOf(BASE_LAUNCHPAD_BLUEPRINT_HOST) + BASE_LAUNCHPAD_BLUEPRINT_HOST.length()));

    String url = BASE_LAUNCHPAD_API_URL + API_VERSION + apiQuery;

    try {
        //establish api connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            // get redirect url from "location" header field
            String newUrl = conn.getHeaderField("Location");

            // open the new connection
            conn = (HttpURLConnection) new URL(newUrl).openConnection();
        }

        //parse returned json
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer json = new StringBuffer();

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

        //generate tab content
        JSONTokener tokener = new JSONTokener(json.toString());
        JSONObject finalResult = new JSONObject(tokener);
        if (finalResult.has(WHITEBOARD) && finalResult.getString(WHITEBOARD).length() > 0) {
            messages.add(new GenericMessageAction(
                    escapeHtml(finalResult.getString(WHITEBOARD)).replaceAll("\n", "<br/>")));
        } else {
            messages.add(new GenericMessageAction("No whiteboard for this blueprint."));
        }

    } catch (JSONException e) {
        // whiteboard JSON key not found
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        //unable to find the requested whiteboard
        messages.add(new GenericMessageAction(
                "Unable to find desired blueprint. Please check that the URL references the correct blueprint."));
        return messages;
    } catch (IOException e) {
        // Exception in attempting to read from Launchpad API
        e.printStackTrace();
    }

    return messages;
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Post.java

@Override
public BufferedReader execute() {
    String jSon = null;//from   w w  w .  ja  va2s. c  om
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.github.mhendred.face4j.ResponderImpl.java

/** 
 * @see {@link Responder#doPost(URI, List)}
 *//*w w w.j a v  a 2  s  .co m*/
public String doPost(final URI uri, final List<NameValuePair> params)
        throws FaceClientException, FaceServerException {
    try {
        URL url = uri.toURL();

        StringBuilder strparams = new StringBuilder();
        for (Iterator iterator = params.iterator(); iterator.hasNext();) {
            NameValuePair nameValuePair = (NameValuePair) iterator.next();
            strparams.append(nameValuePair.getName());
            strparams.append("=");
            strparams.append(nameValuePair.getValue());
            strparams.append("&");
        }

        strparams.deleteCharAt(strparams.length() - 1);
        byte[] postData = strparams.toString().getBytes();
        String urlpath = url.toString();
        url = new URL(urlpath + "?" + strparams.toString());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /*connection.setRequestProperty("X-Custom-Header", "xxx");
        connection.setRequestProperty("Content-Type", "application/json");*/

        // POST the http body data
        //          connection.setDoOutput(true);
        //connection.setRequestMethod("GET");

        /*connection.setRequestProperty( "Content-Length",Integer.toString( postData.length ));
        DataOutputStream  writer = new DataOutputStream(connection.getOutputStream());
        writer.write(postData);
        writer.close();*/

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // OK
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();

            return res.toString();

        } else {
            int resp = connection.getResponseCode();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();
            return line;
        }

    }

    catch (IOException ioe) {
        throw new FaceClientException(ioe);
    }
}

From source file:edu.asu.msse.dssoni.moviedescrpitionapp.JsonRPCClientViaThread.java

private String post(URL url, Map<String, String> headers, String data) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }/*  w  w w .  j av  a 2s .  c  om*/
    }
    connection.addRequestProperty("Accept-Encoding", "gzip");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();
    OutputStream out = null;
    try {
        out = connection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new Exception("Unexpected status from post: " + statusCode);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
    String responseEncoding = connection.getHeaderField("Content-Encoding");
    responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream in = connection.getInputStream();
    try {
        in = connection.getInputStream();
        if ("gzip".equalsIgnoreCase(responseEncoding)) {
            in = new GZIPInputStream(in);
        }
        in = new BufferedInputStream(in);
        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) > 0) {
            bos.write(buff, 0, n);
        }
        bos.flush();
        bos.close();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    android.util.Log.d(this.getClass().getSimpleName(),
            "json rpc request via http returned string " + bos.toString());
    return bos.toString();
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

private static void verifyResponseCode(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("Invalid http response code from responder: " + connection.getResponseCode());
    }//from  w  w  w .  j a  v a 2s  .  com
}

From source file:hudson.model.DirectoryBrowserSupportSEC904Test.java

@Test
@Issue("SECURITY-904")
public void symlink_outsideWorkspace_areNotAllowed() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();

    File secretsFolder = new File(j.jenkins.getRootDir(), "secrets");
    File secretTarget = new File(secretsFolder, "goal.txt");
    String secretContent = "secret";
    FileUtils.write(secretTarget, secretContent);

    /*/*from   ww w.  j  a v a  2s  . c  o  m*/
     *  secrets/
     *      goal.txt
     *  workspace/
     *      intermediateFolder/
     *          public2.key
     *          otherFolder/
     *              to_secret3 -> ../../../../secrets/
     *          to_secret2 -> ../../../secrets/
     *          to_secret_goal2 -> ../../../secrets/goal.txt
     *      public1.key
     *      to_secret1 -> ../../secrets/
     *      to_secret_goal1 -> ../../secrets/goal.txt
     *
     */
    if (Functions.isWindows()) {
        // no need to test mklink /H since we cannot create an hard link to a non-existing file
        // and so you need to have access to the master file system directly which is already a problem

        String script = loadContentFromResource("outsideWorkspaceStructure.bat");
        p.getBuildersList().add(new BatchFile(script));
    } else {
        String script = loadContentFromResource("outsideWorkspaceStructure.sh");
        p.getBuildersList().add(new Shell(script));
    }

    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    JenkinsRule.WebClient wc = j.createWebClient();
    wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
    { // workspace root must be reachable (regular case)
        Page page = wc.goTo(p.getUrl() + "ws/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent,
                allOf(containsString("public1.key"), containsString("intermediateFolder"),
                        containsString("to_secrets1"), containsString("to_secrets_goal1"),
                        not(containsString("to_secrets2")), not(containsString("to_secrets_goal2"))));
    }
    { // to_secrets1 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/to_secrets1/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets_goal1 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/to_secrets_goal1/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // intermediateFolder must be reachable (regular case)
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent,
                allOf(not(containsString("to_secrets1")), not(containsString("to_secrets_goal1")),
                        containsString("to_secrets2"), containsString("to_secrets_goal2")));
    }
    { // to_secrets2 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // using symbolic in the intermediate path
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2/master.key", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets_goal2 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets_goal2/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }

    // pattern search feature
    { // the pattern allow us to search inside the files / folders, 
      // without the patch the master.key from inside the outside symlinks would have been linked
        Page page = wc.goTo(p.getUrl() + "ws/**/*.key", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent, allOf(not(containsString("master.key")), containsString("public1.key"),
                containsString("public2.key")));
    }

    // zip feature
    { // all the outside folders / files are not included in the zip
        Page zipPage = wc.goTo(p.getUrl() + "ws/*zip*/ws.zip", null);
        assertThat(zipPage.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));

        List<String> entryNames = getListOfEntriesInDownloadedZip((UnexpectedPage) zipPage);
        assertThat(entryNames, containsInAnyOrder(p.getName() + "/intermediateFolder/public2.key",
                p.getName() + "/public1.key"));
    }
    { // all the outside folders / files are not included in the zip
        Page zipPage = wc.goTo(p.getUrl() + "ws/intermediateFolder/*zip*/intermediateFolder.zip", null);
        assertThat(zipPage.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));

        List<String> entryNames = getListOfEntriesInDownloadedZip((UnexpectedPage) zipPage);
        assertThat(entryNames, contains("intermediateFolder/public2.key"));
    }
}

From source file:com.arjuna.qa.junit.TestAll.java

private void testCallServlet(String serverUrl, String outfile) {
    boolean result = true;
    try {//from   w ww.  j  a  v  a  2  s .c o m
        // run tests by calling a servlet
        Header runParam = new Header("run", "run");
        HttpMethodBase request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK,
                new Header[] { runParam }, HttpUtils.POST);

        String response = null;
        int index = 0;
        do {
            System.err.println("_____________ " + (index++) + "th round");
            // we have to give some time to the tests to finish
            Thread.sleep(timeout);

            // tries to get results
            request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK, HttpUtils.GET);

            response = request.getResponseBodyAsString();
        } while (response != null && response.indexOf("finished") == -1 && index < LOOP_RETRY_MAX);

        if (response != null && response.indexOf("finished") == -1) {
            System.err.println("======================================================");
            System.err.println("====================  TIMED OUT  =====================");
            System.err.println("======================================================");
            result = false;
        } else {
            System.err.println("======================================================");
            System.err.println("====================   RESULT    =====================");
            System.err.println("======================================================");
            System.err.println(response);
            // writes response to the outfile
            BufferedWriter writer = new BufferedWriter(new FileWriter(outfile));
            writer.write(response);
            writer.close();
        }
    } catch (Exception e) {
        System.err.println("======================================================");
        System.err.println("====================  EXCEPTION  =====================");
        System.err.println("======================================================");
        e.printStackTrace();
        result = false;
    }
    assertTrue(result);
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Patch.java

@Override
public BufferedReader execute() {
    String jSon = null;/*  w w  w .  j  a v  a  2  s  .  com*/
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();

        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:biz.gabrys.lesscss.extended.compiler.source.HttpSource.java

private HttpURLConnection makeConnection(final boolean fetchResponseBody) {
    HttpURLConnection connection;
    int responseCode;
    URL resourceUrl = url;/*w  w w.j av a 2 s  . co  m*/
    boolean redirected = false;
    while (true) {
        try {
            connection = (HttpURLConnection) resourceUrl.openConnection();
            connection.setRequestMethod(fetchResponseBody ? "GET" : "HEAD");
            responseCode = connection.getResponseCode();
        } catch (final IOException e) {
            throw new SourceException(e);
        }

        if (!REDIRECT_CODES.contains(responseCode)) {
            break;
        }
        redirected = true;
        final String location = connection.getHeaderField("Location");
        try {
            resourceUrl = new URL(location);
        } catch (final MalformedURLException e) {
            throw new SourceException(String.format("Invalid Location header: %s", location), e);
        }
    }
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new SourceException(createDownloadErrorMessage(resourceUrl, redirected, responseCode));
    }
    return connection;
}