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:org.jboss.as.test.integration.web.tx.TxControlUnitTestCase.java

private void testURL(URL baseURL, boolean include, boolean commit) throws Exception {
    URL url = new URL(baseURL + TxControlServlet.URL_PATTERN + "?include=" + include + "&commit=" + commit);
    HttpGet httpget = new HttpGet(url.toURI());
    DefaultHttpClient httpclient = new DefaultHttpClient();

    log.info("executing request" + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    assertEquals("Wrong response code: " + statusCode, HttpURLConnection.HTTP_OK, statusCode);

    if (include) {
        Header outerStatus = response.getFirstHeader(TxControlServlet.OUTER_STATUS_HEADER);
        Assert.assertNotNull(TxControlServlet.OUTER_STATUS_HEADER + " is null", outerStatus);
        Header innerStatus = response.getFirstHeader(TxControlServlet.INNER_STATUS_HEADER);
        Assert.assertNotNull(TxControlServlet.INNER_STATUS_HEADER + " is null", innerStatus);
        assertEquals("Wrong inner transaction status: " + innerStatus.getValue(), STATUS_ACTIVE,
                innerStatus.getValue());
        assertEquals("Wrong inner transaction status: " + outerStatus.getValue(), STATUS_ACTIVE,
                outerStatus.getValue());
    } // else TxControlServlet is using RequestDispatcher.forward and can't write to the response

    // Unfortunately, there's no simple mechanism to test that in the commit=false case the server cleaned up
    // the uncommitted tx. The cleanup (TransactionRollbackSetupAction) rolls back the tx and logs, but this
    // does not result in any behavior visible to the client.
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Creates an input stream to read the file content from.  Is only called
 * if {@link #doGetType} returns {@link FileType#FILE}.
 * <p>/*  w ww .ja v a 2s  .com*/
 * It is guaranteed that there are no open output streams for this file
 * when this method is called.
 * <p>
 * The returned stream does not have to be buffered.
 */
@Override
protected InputStream doGetInputStream() throws Exception {
    final GetMethod getMethod = new GetMethod();
    setupMethod(getMethod);
    final int status = getAbstractFileSystem().getClient().executeMethod(getMethod);
    if (status == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new FileNotFoundException(getName());
    }
    if (status != HttpURLConnection.HTTP_OK) {
        throw new FileSystemException("vfs.provider.http/get.error", getName(), Integer.valueOf(status));
    }

    return new HttpInputStream(getMethod);
}

From source file:nz.skytv.example.SwaggerApplication.java

@ApiOperation(value = "Update a book", notes = "Update a book.", response = Book.class, tags = { "book",
        "updates" })
@ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Book updated successfully"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "Transient Entity") })
@RequestMapping(value = { "/rest/book" }, method = RequestMethod.PATCH)
void updateBook(@ApiParam(value = "Book entity", required = true) @RequestBody @Valid final Book book) {
    LOG.debug("update {}", book);
}

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

public InputStream halfExecute() {
    String uri = null;//  w  ww.  ja  va 2s  .  com

    //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
        httpURLConnection.addRequestProperty("Cache-Control", "max-stale=120");
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(true);
        httpURLConnection.setDefaultUseCaches(true);

        if (isAuthorizationEnabled()) {
            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());

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

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

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

From source file:com.boxupp.utilities.PuppetUtilities.java

public StatusBean downloadModule(JsonNode moduleData) {
    Gson searchModuleData = new GsonBuilder().setDateFormat("yyyy'-'MM'-'dd HH':'mm':'ss").create();
    SearchModuleBean searchModuleBean = searchModuleData.fromJson(moduleData.toString(),
            SearchModuleBean.class);
    String fileURL = CommonProperties.getInstance().getPuppetForgeDownloadAPIPath()
            + searchModuleBean.getCurrent_release().getFile_uri();
    StatusBean statusBean = new StatusBean();
    URL url = null;/*from  ww  w . jav a  2 s  .  c om*/
    int responseCode = 0;
    HttpURLConnection httpConn = null;
    String fileSeparator = OSProperties.getInstance().getOSFileSeparator();
    String moduleDirPath = constructModuleDirectory() + fileSeparator;
    checkIfDirExists(new File(constructManifestsDirectory()));
    checkIfDirExists(new File(moduleDirPath));
    try {
        url = new URL(fileURL);
        httpConn = (HttpURLConnection) url.openConnection();
        responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 9, disposition.length());
                }
            } else {
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
            }
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = moduleDirPath + fileName;
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            extrectFile(saveFilePath, moduleDirPath, searchModuleBean.getModuleName());
            File file = new File(saveFilePath);
            file.delete();

        } else {
            logger.error("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
        statusBean.setStatusCode(0);
        statusBean.setStatusMessage(" Module Downloaded successfully ");
    } catch (IOException e) {
        logger.error("Error in loading module :" + e.getMessage());
        statusBean.setStatusCode(1);
        statusBean.setStatusMessage("Error in loading module :" + e.getMessage());
    }
    statusBean = PuppetModuleDAOManager.getInstance().create(moduleData);
    return statusBean;
}

From source file:org.duracloud.common.web.RestHttpHelperTest.java

private void verifyResponse(HttpResponse response) {
    assertNotNull(response);
    assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
}

From source file:net.sf.ehcache.server.util.WebTestUtil.java

/**
 * Checks the response code is OK i.e. 200
 *
 * @param response/* ww  w  .j a va2 s.c o m*/
 */
public static void assertResponseOk(WebResponse response) {
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

public static String useLuxidWS(String input, String token, String outputFormat, String annotationPlan)
        throws Exception {
    String s = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd="
            + "\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> "
            + "<SOAP-ENV:Body> <ns1:annotateString xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:sessionKey>" + token + "</ns1:sessionKey> <ns1:plan>" + annotationPlan
            + "</ns1:plan> <ns1:data>";

    s += input;// "This is a great providing test";

    s += "</ns1:data> <ns1:consumer>" + outputFormat + "</ns1:consumer> </ns1:annotateString> </SOAP-ENV:Body> "
            + "</SOAP-ENV:Envelope>";

    URL url = new URL("http://193.104.205.28//LuxidWS/services/Annotation");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*www.  j  av  a2s . co m*/

    conn.getOutputStream().write(s.getBytes());

    StringBuilder res = new StringBuilder();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = conn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        StringEscapeUtils.escapeHtml("");
        while ((line = rd.readLine()) != null) {
            res.append(line);
        }
        rd.close();
    }
    //      res = URLDecoder.decode(res, "UTF-8");
    return StringEscapeUtils.unescapeHtml(res.toString().replace("&amp;lt", "<"));
}

From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java

private void doSsoRedirect(final URL baseUrl, final HttpContext httpContext, String redirectUrl,
        final String otp) throws IOException {
    HttpResponse redirectResponse;// w  w  w. j a  v  a2  s.  c om
    final HttpGet redirect2Jenkins = new HttpGet(redirectUrl);
    log.debug("Login SUCCEDED: redirecting back to Jenkins using " + redirect2Jenkins.getURI());
    try {
        redirectResponse = httpClient.execute(redirect2Jenkins, httpContext);
        final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

        if (!host.getHostName().toLowerCase().equals(baseUrl.getHost().toLowerCase())) {
            redirectUrl = getSsoErrorHandler(host).doTwoStepAuthentication(httpClient, httpContext,
                    redirectResponse, otp);
            doSsoRedirect(baseUrl, httpContext, redirectUrl, null);
        }

        if (redirectResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Redirection back to Jenkins failed with HTTP Status Code: "
                    + redirectResponse.getStatusLine());
        }
    } finally {
        redirect2Jenkins.releaseConnection();
    }
}

From source file:fm.last.moji.impl.FileUploadOutputStream.java

private void flushAndClose() throws IOException {
    try {//from   w w  w .  ja v  a 2  s  .  c  o m
        delegate.flush();
        size = delegate.getByteCount();
        log.debug("Bytes written: {}", size);
        int code = httpConnection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != code && HttpURLConnection.HTTP_CREATED != code) {
            String message = httpConnection.getResponseMessage();
            throw new IOException(
                    "HTTP Error during flush: " + code + ", " + message + ", peer: '{" + httpConnection + "}'");
        }
    } finally {
        try {
            delegate.close();
        } catch (Exception e) {
            log.warn("Error closing stream", e);
        }
        try {
            httpConnection.disconnect();
        } catch (Exception e) {
            log.warn("Error closing connection", e);
        }
    }
}