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:Controladora.ConexionAPI.java

public List<Usuario> sendGetListaUsuarios(String token) {
    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

    List<Usuario> listaauxiliar = new ArrayList<Usuario>();
    Usuario usuario = new Usuario();

    // Instanciamos el objeto
    httpClient = new HttpClient();
    // Invocamos por GET
    String url = "http://localhost:8090/api/usuarios/";
    request = new GetMethod(url);
    // Aadimos los parmetros que deseemos a la peticin 
    request.setRequestHeader("token", token);
    try {/*w  w  w . j a  va  2  s.c o  m*/
        // 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()));

            JSONParser parser = new JSONParser();

            JSONValue jsonvalue = new JSONValue();

            String tkn = null;

            System.out.println("entro AL WHILE");

            listaauxiliar = null;
            line = reader.readLine();
            while (line != null) {
                System.out.println(line);

                System.out.println("uno");
                // JSONObject jso = (JSONObject) parser.parse(line);
                JSONArray jo = (JSONArray) jsonvalue.parse(line);
                //(JSONArray) jso.get("");
                System.out.println("antes de iterar");
                Iterator<String> iterator = jo.iterator();
                System.out.println("depues de iterar");
                while (iterator.hasNext()) {
                    System.out.println("Entro al while iterador");
                    System.out.println(iterator.next());
                }
                System.out.println("SALIO al while iterador");
                /*usuario.setMail((String) jo.get("mail"));
                usuario.setNombre((String) jo.get("nombre"));
                usuario.setUsuario((String) jo.get("usuario"));
                listaauxiliar.add(usuario);
                        
                System.out.println((String) jo.get("mail"));
                System.out.println((String) jo.get("nombre"));
                System.out.println((String) jo.get("usuario"));*/

                line = reader.readLine();
            }
        }
    } catch (Exception ex) {
        System.err.println("Error\t: " + ex.getMessage());

        ex.printStackTrace();
    } finally {
        // Liberamos la conexin. (Tambin libera los stream asociados)
        request.releaseConnection();
    }
    return listaauxiliar;
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

/**
 * Logs into the Nicira API. The cookie is stored in the <code>_authcookie<code> variable.
 * <p>//from   ww  w.  j  a v  a2 s  .c o  m
 * The method returns false if the login failed or the connection could not be made.
 * 
 */
private void login() throws NiciraNvpApiException {
    String url;

    try {
        url = new URL(_protocol, _host, "/ws.v1/login").toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    PostMethod pm = new PostMethod(url);
    pm.addParameter("username", _adminuser);
    pm.addParameter("password", _adminpass);

    try {
        _client.executeMethod(pm);
    } catch (HttpException e) {
        throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
    } catch (IOException e) {
        throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
    } finally {
        pm.releaseConnection();
    }

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        s_logger.error("Nicira NVP API login failed : " + pm.getStatusText());
        throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText());
    }

    // Success; the cookie required for login is kept in _client
}

From source file:com.mirth.connect.client.core.UpdateClient.java

public void sendUsageStatistics() throws ClientException {
    // Only send stats if they haven't been sent in the last 24 hours.
    long now = System.currentTimeMillis();
    Long lastUpdate = client.getUpdateSettings().getLastStatsTime();

    if (lastUpdate != null) {
        long last = lastUpdate;
        // 86400 seconds in a day
        if ((now - last) < (86400 * 1000)) {
            return;
        }/* ww w. j  a  va2  s . c  om*/
    }

    List<UsageData> usageData = null;

    try {
        usageData = getUsageData();
    } catch (Exception e) {
        throw new ClientException(e);
    }

    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_USAGE_STATISTICS);
    NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()),
            new NameValuePair("version", client.getVersion()),
            new NameValuePair("data", serializer.toXML(usageData)) };
    post.setRequestBody(params);

    try {
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }

        // Save the sent time if sending was successful.
        UpdateSettings settings = new UpdateSettings();
        settings.setLastStatsTime(now);
        client.setUpdateSettings(settings);

    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.m2a.bean.M2ACountryIPBlockerBean.java

public Object execute() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Executing execute()");
    }/*  www.ja v  a2  s .c o m*/
    /*
     * Specific command string for this activity
     * Generally this will a Stored Procedure name with ? delimited by comma for arguments
     */
    /*
     * Parameters are to sent to Persistence access layer in the form of Object array
     */
    Object[] parameters = new Object[5];
    /*
     * Data from the form is copied to the DTO set earlier via prepareDto()
     * getDto() returns Object, hence it has to type casted to specific dto class
     */
    M2ACustomerRegistrationDTO bizDto;
    bizDto = (M2ACustomerRegistrationDTO) getDto();

    /*
     * Populate the parameter array by reading data from DTO
     */
    String countryCode = (String) getFormMap().get("customerCountryCode");
    String ipAddress = (String) getFormMap().get("remoteAddr");

    //get licensekey & requesttype from properties
    String sep = pathSeparator();
    String propsPath = System.getProperty("catalina.base") + sep + "deploy" + sep + "M2A.war" + sep + "WEB-INF"
            + sep + "classes" + sep + "com" + sep + "m2a" + sep + "props" + sep + "ipblocker.props";
    File config = new File(propsPath);
    Properties prop = new Properties();
    prop.load(new FileInputStream(config));
    String licenseKey = prop.getProperty("ipblocker.licensekey");
    String url = prop.getProperty("ipblocker.url");
    //String requestType = prop.getProperty("ipblocker.requesttype");        

    /*MinfraudWebServiceStub minfraudWebServiceStub = new MinfraudWebServiceStub();
    Minfraud_soap8 minfraud_soap80 = new Minfraud_soap8();
    minfraud_soap80.setCountry(countryCode);
    minfraud_soap80.setI(ipAddress);
    minfraud_soap80.setLicense_key(licenseKey);
    minfraud_soap80.setRequested_type(requestType);
            
    Minfraud_soap8Response minfraud_soap8Response = minfraudWebServiceStub.minfraud_soap8(minfraud_soap80); 
    String matchStatus = minfraud_soap8Response.getMinfraud_output().getCountryMatch();
    //String matchStatus = "Yes";
    System.out.println("****Match Status : "+matchStatus);            */
    String command = "p_getCountryBlockedIP(?,?,?,?,?)";
    if (log.isDebugEnabled()) {
        log.debug("*** command string value is " + command);
    }
    parameters[0] = ipAddress;
    parameters[1] = countryCode;
    parameters[2] = new Integer(1);
    parameters[3] = "";
    parameters[4] = "";

    ResultList list = new ResultListBase(
            M2AAccess.findCollection(M2ATokens.APPNAME, bizDto, command, parameters));
    String ipCntryCode = "";
    if ((list != null) && (list.get(0) != null)) {
        M2ACustomerRegistrationDTO resultDTO = (M2ACustomerRegistrationDTO) list.get(0);
        ipCntryCode = resultDTO.getCustomerAddressCountryCode();
    }
    String matchStatus = "";
    if (!ipCntryCode.equals("") && countryCode.equals("UK")) {
        throw new Exception("Please register from the country selected on the registration page");
    } else {
        HttpClient httpClient = new HttpClient();
        GetMethod method = null;
        try {
            //String url = "http://geoip3.maxmind.com/a";
            String queryString = "?l=" + licenseKey + "&i=" + ipAddress;
            // Create a method instance.
            method = new GetMethod(url + queryString);
            // Provide custom retry handler is necessary
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            // Execute the method.
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                log.fatal("\nResponse || Method failed: " + method.getStatusLine());
            }
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            matchStatus = new String(responseBody);
            System.out.println(new String(responseBody));
            //matchStatus = "IN";
        } finally {
            // Release the connection.
            if (method != null) {
                method.releaseConnection();
            }
        }
        parameters[0] = ipAddress;
        parameters[1] = countryCode;
        parameters[2] = new Integer(2);
        parameters[3] = matchStatus;
        parameters[4] = "";

        if (!matchStatus.equals(countryCode) && countryCode.equals("UK")) {
            list = new ResultListBase(M2AAccess.findCollection(M2ATokens.APPNAME, bizDto, command, parameters));
            throw new Exception("Please register from the country selected on the registration page");
        }
    }
    // if(!matchStatus.equals("Yes") && countryCode.equals("UK")){

    /**
     * Persistence layer class M2AAccess.findCollection returns collection of dto objects.
     * This execute() method must return ProcessResult and ProcessResult holds collection of
     * data in ResultList class, hence the returned collection has to be wrapped in
     * ResultList class.
     */
    /**
     * Got a collection of DTO from access layer
     * Login result will be only one row ie. one DTO
     * We need to refer the first DTO only in the processResult
     * To refer to the first DTO in processAction we need setSingleForm to true
     */
    ProcessResultBase result = new ProcessResultBase(list);

    result.setSingleForm(true);
    /**
     * set as the Client scope
     */
    if (log.isDebugEnabled()) {
        log.debug("*** Set scope for process ProcessResult to " + M2ATokens.EMPTY);
    }
    result.setScope(M2ATokens.EMPTY);
    return result;
}

From source file:davmail.caldav.TestCaldav.java

public void testGetContacts() throws IOException {
    GetMethod method = new GetMethod("/users/" + session.getEmail() + "/contacts/");
    httpClient.executeMethod(method);//from   ww  w  .ja  v a2  s  .  c  o  m
    assertEquals(HttpStatus.SC_OK, method.getStatusCode());
}

From source file:com.sun.portal.rssportlet.FeedHelper.java

/**
 * Get the ROME SyndFeed object for the specified feed. The object may come
 * from a cache; the data in the feed may not be read at the time
 * this method is called.//from   ww  w .j av a2s .c om
 *
 * The <code>RssPortletBean</code> object is used to identify the feed
 * of interest, and the timeout value to be used when managing this
 * feed's cached value.
 *
 * @param bean an <code>RssPortletBean</code> object that describes
 * the feed of interest, and the cache timeout value for the feed.
 * @return a ROME <code>SyndFeed</code> object encapsulating the
 * feed specified by the URL.
 */
public SyndFeed getFeed(SettingsBean bean, String selectedFeed) throws IOException, FeedException {
    SyndFeed feed = null;
    FeedElement feedElement = (FeedElement) feeds.get(selectedFeed);

    if (feedElement != null && !feedElement.isExpired()) {
        feed = feedElement.getFeed();
    } else {
        GetMethod httpget = null;
        try {
            SyndFeedInput input = new SyndFeedInput();

            HttpClient httpclient = new HttpClient();
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
            // SO_TIMEOUT -- timeout for blocking reads
            httpclient.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT);

            httpget = new GetMethod(selectedFeed);

            //httpget.getParams().setParameter("http.socket.timeout", new Integer(20000));
            // Internally the parameter collections will be linked together
            // by performing the following operations: 
            // hostconfig.getParams().setDefaults(httpclient.getParams());
            // httpget.getParams().setDefaults(hostconfig.getParams());
            //httpclient.executeMethod(hostconfig, httpget);
            // Execute the method.

            int statusCode = httpclient.executeMethod(httpget);
            if (statusCode != HttpStatus.SC_OK) {
                log.info("Method failed: " + httpget.getStatusLine());
            }
            // Read the response body.
            InputSource src = new InputSource(httpget.getResponseBodyAsStream());
            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            feed = input.build(src);
            //
            // only cache the feed if the cache timeout is not equal to 0
            // a cache timeout of 0 means "don't cache"
            //
            int timeout = bean.getCacheTimeout();
            if (timeout != 0) {
                putFeed(selectedFeed, feed, timeout);
            }
        } catch (MalformedURLException mfurlex) {
            log.info("MalformedURLException: " + mfurlex.getMessage());
            mfurlex.printStackTrace();
            throw new IOException("MalformedURLException: " + mfurlex.getMessage());
        } catch (HttpException httpex) {
            log.info("Fatal protocol violation: " + httpex.getMessage());
            httpex.printStackTrace();
            throw new IOException("Fatal protocol violation: " + httpex.getMessage());
        } catch (IllegalArgumentException iae) {
            log.info("IllegalArgumentException: " + iae.getMessage());
            iae.printStackTrace();
            throw new IOException("IllegalArgumentException: " + iae.getMessage());
        } catch (IOException ioe) {
            log.info("Fatal transport error: " + ioe.getMessage());
            ioe.printStackTrace();
            throw new IOException("Fatal transport error: " + ioe.getMessage());
        } catch (ParsingFeedException parsingfeedex) {
            log.info("ParsingFeedException: " + parsingfeedex.getMessage());
            parsingfeedex.printStackTrace();
            throw new FeedException("ParsingFeedException: " + parsingfeedex.getMessage());
        } catch (FeedException feedex) {
            log.info("FeedException: " + feedex.getMessage());
            feedex.printStackTrace();
            throw new FeedException("FeedException: " + feedex.getMessage());
        } catch (Exception ex) {
            log.info("Exception ERROR: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            // Release the connection.
            httpget.releaseConnection();
        }
    }
    return feed;
}

From source file:com.zb.app.biz.service.WeixinTest.java

public String getFakeid(String openid) {
    if (isLogin) {
        GetMethod get = new GetMethod("https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token="
                + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0");
        get.setRequestHeader("Cookie", this.cookiestr);
        get.setRequestHeader("Host", "mp.weixin.qq.com");
        get.setRequestHeader("Referer",
                "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token=" + token
                        + "&lang=zh_CN");
        get.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        try {/*from  w  w w. j  a  va2  s  .c  om*/
            int code = httpClient.executeMethod(get);
            System.out.println(code);
            if (HttpStatus.SC_OK == code) {
                System.out.println("Fake Success");
                String str = get.getResponseBodyAsString();
                System.out.println(str.length());
                // String userjson = StringUtils.substringBetween(str,
                // "<script id=\"json-friendList\" type=\"json/text\">", "</script>");
                String userjson = StringUtils.substringBetween(str, "\"contacts\":", "})");
                System.out.println(userjson);
                JSONParser parser = new JSONParser();
                try {
                    JSONArray array = (JSONArray) parser.parse(userjson);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = (JSONObject) array.get(i);
                        String fakeid = obj.get("id").toString();
                        if (compareFakeid(fakeid, openid)) {
                            return fakeid;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        login();
        return getFakeid(openid);
    }
    return null;
}

From source file:fr.esiea.esieaddress.service.login.facebook.FacebookAuthenticationService.java

private String getAccessToken(String code) {
    /**//from   w  ww.  java  2s. c  o m
     * TODO Sheety code change it
     */
    if (!code.isEmpty()) {
        //If we received a valid code, we can continue to the next step
        //Next we want to get the access_token from Facebook using the code we got,
        //use the following url for that, in this url,
        //client_id-our app id(same as above),  redirect_uri-same as above, client_secret-same as                //above, code-the code we just got

        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        // Create a method instance.
        String url = postUrlBase.concat("&code=" + code);
        GetMethod method = new GetMethod(url);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("Method failed: " + method.getStatusLine());
            }
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            // Deal with the response.Use caution: ensure correct character encoding and is
            // not binary data
            String responseBodyString = new String(responseBody);
            LOGGER.info("token : " + responseBodyString);
            if (responseBodyString.contains("access_token")) {
                //success
                String[] mainResponseArray = responseBodyString.split("&");
                //like //{"access_token= AAADD1QFhDlwBADrKkn87ZABAz6ZCBQZ//DZD ","expires=5178320"}
                String accesstoken = "";
                for (String string : mainResponseArray) {
                    if (string.contains("access_token")) {
                        return string.replace("access_token=", "").trim();
                    }
                }

            }
        } catch (IOException e) {
            LOGGER.error("Fatal transport error", e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
    }
    //failed
    return "";

}

From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java

public void testGetACList() {
    Map<String, String> paramMap = null;
    String sessionId = null;/*  w  ww .ja  v  a2s  .c om*/

    try {
        paramMap = login();
        sessionId = paramMap.get(ACHttpConstant.SESSION_ID_KEY);

        assertNotNull(RESPONSE_ERROR, sessionId);
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }

    StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT)
            .append(ACHttpPropertiesConstant.HTTP_AC_REQUEST_URL);
    postMethod = new PostMethod(sb.toString());

    postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                ACHttpBodyUtil.buildGetACListByAlbumRequestBody(sessionId, "Honnix", "2008", "Shadow of Light"),
                null, ACHttpPropertiesConstant.HTTP_CHARSET);

        postMethod.setRequestEntity(requestEntity);

        int statusCode = client.executeMethod(postMethod);

        assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

        String response = postMethod.getResponseBodyAsString();

        assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP));

        byte[] byteArray = new byte[3];

        byteArray[0] = 97;
        byteArray[1] = 98;
        byteArray[2] = 99;
        assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray)));
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                ACHttpBodyUtil.buildGetACListByDiscIdRequestBody(sessionId, "aac6400f48249cc9763771cc626a3571"),
                null, ACHttpPropertiesConstant.HTTP_CHARSET);
        postMethod = new PostMethod(sb.toString());

        postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);
        postMethod.setRequestEntity(requestEntity);

        int statusCode = client.executeMethod(postMethod);

        assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

        String response = postMethod.getResponseBodyAsString();

        assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP));

        byte[] byteArray = new byte[3];

        byteArray[0] = 97;
        byteArray[1] = 98;
        byteArray[2] = 99;
        assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray)));
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }
}

From source file:com.sdm.core.resource.RestResource.java

@Override
public IBaseResponse getPaging(String filter, int pageId, int pageSize, String sortString) {
    DefaultResponse response = this.validateCache();
    // Cache validation
    if (response != null) {
        return response;
    }// w w  w  .  jav a 2  s .c  o  m

    try {
        //Change Filter Text To Unicode For Searching...
        if (MyanmarFontManager.isMyanmar(filter) && MyanmarFontManager.isZawgyi(filter)) {
            filter = MyanmarFontManager.toUnicode(filter);
        }

        long total = getDAO().getTotal(filter);
        List<T> data = (List<T>) getDAO().paging(filter, pageId, pageSize, sortString);

        if (data == null) {
            throw new NullPointerException("There is no data for your query string.");
        }

        PaginationModel<T> content = new PaginationModel<T>(data, total, pageId, pageSize);

        // Generate HAL Links
        content.genreateLinks(this.getClass());

        response = new DefaultResponse<>(HttpStatus.SC_OK, ResponseType.SUCCESS, content);

        response.setHeaders(this.buildCache());
        return response;
    } catch (Exception e) {
        getLogger().error(e);
        throw e;
    }
}