Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:edu.si.services.fits.itest.UCT_FITS_IT.java

@Test
public void fitsVersionTest() throws IOException {
    log.debug("FITS_URI = {}", FITS_URI);

    HttpGet request = new HttpGet(FITS_URI + "/version");
    final String fitsVersion;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        fitsVersion = EntityUtils.toString(response.getEntity());
    }/*w w w  . j  ava2s.  co m*/
    logger.info("Found FITS Version:{}", fitsVersion);
    String expectedVersion = "1.2.0";
    assertEquals(expectedVersion, fitsVersion.trim());
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryServlet.java

/**
 * Perform an HTTP GET, which corresponds to the basic CRUD operation "read"
 * according to the generic interaction semantics of HTTP REST.
 * <p>/*from   www. jav a2  s  . c  o  m*/
 * <ul>
 * <li>BODY ignored for READ</li> 
 * <li>no RANGE retrieves the entire graph</li> 
 * <li>RANGE(&lt;query language&gt;[&lt;query&gt;]) performs a query</li>
 * </ul>
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String range = request.getHeader(HTTP_RANGE);
    boolean includeInferred = Boolean.valueOf(request.getHeader(X_INCLUDE_INFERRED));

    if (log.isInfoEnabled()) {
        log.info("doGet: " + range);
    }

    try {

        // set the content type and the _encoding_
        response.setContentType(RDF_XML);

        // obtain the writer -- it will use the specified encoding.
        PrintWriter out = response.getWriter();
        String query = null;
        QueryLanguage ql = null;
        int status = 0;
        if (range == null || range.length() == 0) {
            // proper semantics are to provide the entire graph, per above
            status = HttpStatus.SC_OK;
        } else {
            // sparql[select ...]
            final int i = range.indexOf('[');
            ql = QueryLanguage.valueOf(range.substring(0, i));
            if (ql == null) {
                throw new RuntimeException("unrecognized query language: " + range);
            }
            query = range.substring(i + 1, range.length() - 1);
            /*
             MetadataRepositoryHelper.doQuery(graph, query, ql,
             includeInferred);
             */
            status = HttpStatus.SC_PARTIAL_CONTENT;
        }

        String results = read(query, ql, includeInferred);
        out.print(results);
        out.flush();
        response.setStatus(status);

    } catch (Exception ex) {
        ex.printStackTrace();
        response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }

}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a POST towards the gateway/*from  ww  w  . ja  v  a 2  s.  com*/
 * @author ctranoris
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) {

    boolean status = false;
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("User-Agent", userAgent);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    //HttpMethodParams.
    RequestEntity requestEntity = null;
    try {
        requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    post.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(post);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + post.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = post.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

        status = true;
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        post.releaseConnection();
    }

    return status;

}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public HTTPResult readData1(URL url) throws Exception {

    if (!isSetup())
        setup();/* ww  w. j  av a  2s .c o  m*/

    GetMethod method = new GetMethod(url.toString());
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        log.debug("HTTP StatusCode not HttpStatus.SC_OK:(" + statusCode + "):" + method.getStatusLine());
    }

    BufferedInputStream stream = new BufferedInputStream(method.getResponseBodyAsStream());

    StringBuffer data = new StringBuffer();

    // Saves the page data in a string buffer... 
    int buffer;

    while ((buffer = stream.read()) != -1) {
        data.append((char) buffer);
    }

    stream.close();

    return new HTTPResult(url, statusCode == HttpStatus.SC_OK ? data : null, method.getStatusLine());
}

From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(Object object, Map<String, String> paramMap) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;// w  ww  .  ja v  a  2 s. c  o  m
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(paramMap.get("SERVER_URL"));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));
        meth.setRequestBody(object.toString());
        System.out.println(object.toString());

        /**
         * "type"="ruleSync",XML? "syncType"="***"
         * 1??2??3? "ruleName"="***"
         * XML?XML???XML
         */
        meth.addRequestHeader("type", paramMap.get("type"));
        meth.addRequestHeader("syncType", paramMap.get("syncType"));
        meth.addRequestHeader("ruleName", URLEncoder.encode(paramMap.get("ruleName"), "UTF-8"));
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(
            LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);/*from   w  ww .  j a va  2s  .  c o  m*/
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost",
            ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken);
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:edu.unc.lib.dl.admin.controller.MODSController.java

/**
 * Retrieves the MD_DESCRIPTIVE datastream, containing MODS, for this item if one is present. If it is not present,
 * then returns a blank MODS document./*from  ww w  .  ja  va 2s .  co  m*/
 *
 * @param idPrefix
 * @param id
 * @return
 */
@RequestMapping(value = "{pid}/mods", method = RequestMethod.GET)
public @ResponseBody String getMods(@PathVariable("pid") String pid) {
    String mods = null;
    String dataUrl = swordUrl + "em/" + pid + "/" + ContentModelHelper.Datastream.MD_DESCRIPTIVE;

    HttpClient client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
    client.getParams().setAuthenticationPreemptive(true);
    GetMethod method = new GetMethod(dataUrl);

    // Pass the users groups along with the request
    AccessGroupSet groups = GroupsThreadStore.getGroups();
    method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, groups.joinAccessGroups(";"));

    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            try {
                mods = method.getResponseBodyAsString();
            } catch (IOException e) {
                log.info("Problem uploading MODS for " + pid + ": " + e.getMessage());
            } finally {
                method.releaseConnection();
            }
        } else {
            if (method.getStatusCode() == HttpStatus.SC_BAD_REQUEST
                    || method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                // Ensure that the object actually exists
                PID existingPID = tripleStoreQueryService.verify(new PID(pid));
                if (existingPID != null) {
                    // MODS doesn't exist, so pass back an empty record.
                    mods = "<mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></mods:mods>";
                } else {
                    throw new Exception(
                            "Unable to retrieve MODS.  Object " + pid + " does not exist in the repository.");
                }
            } else {
                throw new Exception("Failure to retrieve fedora content due to response of: "
                        + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
            }
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    }
    return mods;
}

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

/**
 * Pega o cdigo css//  w w  w. j av  a 2 s.  co  m
 * @param url
 * @return
 * @throws Exception 
 */
public String getCssContent(String url) throws Exception {
    metodo = new GetMethod(url);
    metodo.setRequestHeader("user-agent", "Mozilla/5.0");
    metodo.setFollowRedirects(true);
    int status = httpClient.executeMethod(metodo);
    String location = getLocation(metodo);
    //Verificar os possveis erros
    if (status != HttpStatus.SC_OK) {
        //No foi aceito, ocorreu um erro 500 404
        if (status == HttpStatus.SC_NOT_FOUND) {
        }
        throw new Exception("Erro de http " + status + " para url='" + url + "'");
        //return "";
    }
    //Verifica redirecionamento
    if (location != "") {
        //System.out.print(url+" to "+location+"\n");
    }
    String conteudoHTML = metodo.getResponseBodyAsString();

    return conteudoHTML;
}

From source file:de.fips.plugin.tinyaudioplayer.http.SoundCloudPlaylistProvider.java

@VisibleForTesting
String getSoundCloudPageFor(final URI queryURI) {
    val cachedPage = pageCache.get(queryURI);
    if (cachedPage != null) {
        return cachedPage;
    }/* w  w  w .  jav a 2s  .c  o m*/
    val client = new HttpClient();
    try {
        if (proxyConfiguration != null)
            proxyConfiguration.setupProxyFor(client.getHostConfiguration(), queryURI);

        @Cleanup("releaseConnection")
        val method = new GetMethod(queryURI.toString());
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            @Cleanup
            val response = method.getResponseBodyAsStream();
            val page = As.string(response);
            pageCache.put(queryURI, page);
            return page;
        }
    } catch (IOException ignore) {
        // to bad then
    }
    return "";
}

From source file:com.zb.app.external.wechat.service.WeixinService.java

public void upload(File file, String type) {
    StringBuilder sb = new StringBuilder(400);
    sb.append("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=");
    sb.append(getAccessToken());// w  ww  .ja  v a2  s  .  c  o  m
    sb.append("&type=").append(type);

    PostMethod postMethod = new PostMethod(sb.toString());
    try {
        // FilePart?
        FilePart fp = new FilePart("filedata", file);
        Part[] parts = { fp };
        // MIMEhttpclientMulitPartRequestEntity
        MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
        postMethod.setRequestEntity(mre);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.error(postMethod.getResponseBodyAsString());
        } else {
            logger.error("fail");
        }
        byte[] responseBody = postMethod.getResponseBody();
        String result = new String(responseBody, "utf-8");
        logger.error("result : " + result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        postMethod.releaseConnection();
    }
}