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:com.bsb.common.vaadin.embed.AbstractEmbedTest.java

protected void checkVaadinIsDeployed(int port, String context) {
    final StringBuilder sb = new StringBuilder();
    sb.append("http://localhost:").append(port);
    if (context.trim().isEmpty() || context.equals("/")) {
        sb.append("/");
    } else {/*w ww .j a  v  a  2  s . co m*/
        sb.append(context);
    }
    final String url = sb.toString();

    final HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(2000);
    final GetMethod method = new GetMethod(url);

    try {
        assertEquals("Wrong return code invoking [" + url + "]", HttpStatus.SC_OK,
                client.executeMethod(method));
    } catch (IOException e) {
        throw new IllegalStateException("Failed to invoke url [" + url + "]", e);
    }
}

From source file:com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation.java

private boolean isSuccess(int status) {
    return (status == HttpStatus.SC_OK || status == HttpStatus.SC_ACCEPTED);
}

From source file:net.sf.ufsc.http.HttpFile.java

/**
 * @see net.sf.ufsc.File#exists()/*from ww w  .j a  v a  2 s  .c o  m*/
 */
public boolean exists() throws java.io.IOException {
    HeadMethod method = new HeadMethod(this.uri.toString());

    int status = this.client.executeMethod(method);

    if (status == HttpStatus.SC_OK) {
        return true;
    } else if (status == HttpStatus.SC_NOT_FOUND) {
        return false;
    } else {
        throw new IOException(method.getStatusText());
    }
}

From source file:net.sf.sail.webapp.dao.sds.impl.SdsCurnitListCommandHttpRestImpl.java

/**
 * @see net.sf.sail.webapp.dao.sds.SdsCommand#generateRequest()
 *//*from  w  w w.j av a2 s.  c  o m*/
public HttpGetRequest generateRequest() {
    final String url = "/curnit";

    return new HttpGetRequest(REQUEST_HEADERS_ACCEPT, EMPTY_STRING_MAP, url, HttpStatus.SC_OK);
}

From source file:com.hp.alm.ali.idea.services.DevMotiveService.java

public Map<Commit, List<EntityRef>> getRelatedEntities(List<Commit> commits) {
    HashMap<Commit, List<EntityRef>> ret = new HashMap<Commit, List<EntityRef>>();

    Integer workspaceId = workspaceConfiguration.getWorkspaceId();
    if (workspaceId == null) {
        return noResponse(ret, commits);
    }/*from  ww  w . j  a  v  a2 s  .c  o  m*/

    Element commitsElem = new Element("commits");
    for (Commit commit : commits) {
        Element commitElem = new Element("commit");
        setAttribute(commitElem, "committer", commit.getCommitterEmail(), commit.getCommitterName());
        setAttribute(commitElem, "author", commit.getAuthorEmail(), commit.getAuthorName());
        commitElem.setAttribute("revision", commit.getRevisionString());
        commitElem.setAttribute("date", CommentField.dateTimeFormat.format(commit.getDate()));
        Element messageElem = new Element("message");
        messageElem.setText(commit.getMessage());
        commitElem.addContent(messageElem);
        commitsElem.addContent(commitElem);
    }
    String commitRequest = XMLOutputterFactory.getXMLOutputter().outputString(new Document(commitsElem));

    MyResultInfo result = new MyResultInfo();
    int code = restService.post(commitRequest, result, "workspace/{0}/ali/linked-items/commits", workspaceId);

    if (code != HttpStatus.SC_OK) {
        return noResponse(ret, commits);
    }

    Iterator<CommitInfo> commitInfoIterator = CommitInfoList.create(result.getBodyAsStream()).iterator();
    for (Commit commit : commits) {
        CommitInfo next = commitInfoIterator.next();
        LinkedList<EntityRef> list;
        if (next.getId() != null) {
            list = new LinkedList<EntityRef>();
            for (int id : next.getDefects()) {
                list.add(new EntityRef("defect", id));
            }
            for (int id : next.getRequirements()) {
                list.add(new EntityRef("requirement", id));
            }
        } else {
            list = null;
        }
        ret.put(commit, list);
    }

    return ret;
}

From source file:Controladora.ConexionAPI.java

public String sendPost(String nombre, String pass) {
    httpClient = null; // Objeto a travs del cual realizamos las peticiones
    request = null; // Objeto para realizar las peticiines HTTP GET o POST
    status = 0; // Cdigo de la respuesta HTTP
    reader = null; // Se usa para leer la respuesta a la peticin
    line = null; // Se usa para leer cada una de las lineas de texto de la respuesta
    String token = null;//from  w w  w . j ava  2  s .c  o  m
    String tkn = null;

    // Instanciamos el objeto
    httpClient = new HttpClient();
    // Invocamos por POST
    String url = "http://localhost:8090/login";
    request = new PostMethod(url);
    // Aadimos los parmetros que deseemos a la peticin 
    ((PostMethod) request).addParameter("usuario", nombre);
    ((PostMethod) request).addParameter("password", pass);
    try {
        // Leemos el cdigo de la respuesta HTTP que nos devuelve el servidor
        status = httpClient.executeMethod(request);
        // Vemos si la peticin se ha realizado satisfactoriamente
        if (status != HttpStatus.SC_OK) {
            System.out.println("Error\t" + request.getStatusCode() + "\t" + request.getStatusText() + "\t"
                    + request.getStatusLine());
        } else {
            // Leemos el contenido de la respuesta y realizamos el tratamiento de la misma.
            // En nuestro caso, simplemente mostramos el resultado por la salida estndar
            reader = new BufferedReader(
                    new InputStreamReader(request.getResponseBodyAsStream(), request.getResponseCharSet()));
            line = reader.readLine();
            while (line != null) {
                token = line;
                line = reader.readLine();
            }
            JSONParser parser = new JSONParser();
            JSONObject jo = (JSONObject) parser.parse(token);
            tkn = (String) jo.get("token");
        }
    } catch (Exception ex) {
        System.out.println("Error\t: " + ex.getMessage());
        /*      
              ex.printStackTrace();*/
    } finally {
        // Liberamos la conexin. (Tambin libera los stream asociados)
        request.releaseConnection();
    }
    return tkn;
}

From source file:com.interaction.example.odata.multicompany.ODataMulticompanyITCase.java

@Test
public void testGetServiceDocumentUri() throws Exception {
    ODataConsumer consumer = ODataJerseyConsumer.newBuilder(baseUri).build();
    // get the service document for the company specific service document
    String serviceRootUri = consumer.getServiceRootUri();
    assertNotNull(serviceRootUri);//ww  w .  j av a  2 s .c o m
    GetMethod method = new GetMethod(serviceRootUri);
    String response = null;
    try {
        method.setDoAuthentication(true); //Require authentication
        client.executeMethod(method);
        assertEquals(200, method.getStatusCode());

        if (method.getStatusCode() == HttpStatus.SC_OK) {
            // read as string
            response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        method.releaseConnection();
    }
    // assert the Users entity set exists in service document
    assertTrue(response.contains("<collection href=\"Flights\">"));
}

From source file:buildhappy.tools.DownloadFile.java

/**
 * URL/*  w  ww.  j av a 2  s.  c  om*/
 */
public String downloadFile(String url) {
    String filePath = null;
    //1.?HttpClient??
    HttpClient client = new HttpClient();
    //5s
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //2.?GetMethod?
    GetMethod getMethod = new GetMethod(url);
    //get5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    //??
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    //3.http get 
    try {
        int statusCode = client.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed:" + getMethod.getStatusLine());
            filePath = null;
        }
        //4.?HTTP?
        InputStream in = getMethod.getResponseBodyAsStream();
        BufferedInputStream buffIn = new BufferedInputStream(in);
        //byte[] responseBody = null;
        String responseBody = null;
        StringBuffer strBuff = new StringBuffer();
        byte[] b = new byte[1024];
        int readByte = 0;
        while ((readByte = buffIn.read(b)) != -1) {
            strBuff.append(new String(b));
        }
        responseBody = strBuff.toString();
        //buffIn.read(responseBody, off, len)
        //byte[] responseBody = getMethod.getResponseBody();
        //?url????
        filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
        System.out.println(filePath + "--size:" + responseBody.length());
        saveToLocal(responseBody.getBytes(), filePath);
    } catch (HttpException e) {
        System.out.println("check your http address");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //
        getMethod.releaseConnection();
    }
    return filePath;
}

From source file:com.ephesoft.dcma.util.WebServiceCaller.java

/**
 * Api to simply hit webservice. It will return true or false if Webservice hit was successful or unsuccessful respectively
 * /*from   w  ww .j av a 2s .  c om*/
 * @param serviceURL
 * @return
 */
private static boolean hitWebservice(final String serviceURL) {
    LOGGER.debug("Giving a hit at webservice URL.");
    boolean isActive = false;
    if (!EphesoftStringUtil.isNullOrEmpty(serviceURL)) {

        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        PostMethod method = new PostMethod(serviceURL);

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

            if (statusCode == HttpStatus.SC_OK) {
                isActive = true;
            } else {
                LOGGER.info(EphesoftStringUtil.concatenate("Execute Method failed: ", method.getStatusLine()));
            }
        } catch (HttpException httpException) {
            LOGGER.error(
                    EphesoftStringUtil.concatenate("Fatal protocol violation: ", httpException.getMessage()));
        } catch (IOException ioException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Fatal transport error: ", ioException.getMessage()));
        } finally {
            // Release the connection.
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return isActive;
}

From source file:ch.algotrader.starter.GoogleDailyDownloader.java

private void retrieve(HttpClient httpclient, String symbol, String startDate, String endDate, String exchange)
        throws IOException, HttpException, FileNotFoundException, ParseException {

    GetMethod fileGet = new GetMethod("https://www.google.com/finance/historical?q=" + exchange + ":" + symbol
            + "&output=csv&startdate=" + startDate + (endDate == null ? "" : "&endDate=" + endDate));

    fileGet.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {/*from   ww  w  .jav a2  s .  c o m*/
        int status = httpclient.executeMethod(fileGet);

        if (status == HttpStatus.SC_OK) {

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(fileGet.getResponseBodyAsStream()));

            File parent = new File("files" + File.separator + "google");
            if (!parent.exists()) {
                FileUtils.forceMkdir(parent);
            }

            Writer writer = new OutputStreamWriter(new FileOutputStream(new File(parent, symbol + ".csv")));

            try {

                reader.readLine();

                String line;
                List<String> lines = new ArrayList<String>();
                while ((line = reader.readLine()) != null) {

                    String tokens[] = line.split(",");

                    Date dateTime = fileFormat.parse(tokens[0]);

                    StringBuffer buffer = new StringBuffer();
                    buffer.append(
                            DateTimePatterns.LOCAL_DATE_TIME.format(DateTimeLegacy.toLocalDateTime(dateTime)));
                    buffer.append(",");
                    buffer.append(tokens[1].equals("-") ? "" : tokens[1]);
                    buffer.append(",");
                    buffer.append(tokens[2].equals("-") ? "" : tokens[2]);
                    buffer.append(",");
                    buffer.append(tokens[3].equals("-") ? "" : tokens[3]);
                    buffer.append(",");
                    buffer.append(tokens[4].equals("-") ? "" : tokens[4]);
                    buffer.append(",");
                    buffer.append(tokens[5]);
                    buffer.append("\n");

                    lines.add(buffer.toString());
                }

                writer.write("dateTime,open,high,low,close,vol\n");

                // write in reverse order
                for (int i = lines.size() - 1; i > 0; i--) {
                    writer.append(lines.get(i));
                }

            } finally {
                reader.close();
                writer.close();
            }
        }
    } finally {
        fileGet.releaseConnection();
    }
}