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

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

Introduction

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

Prototype

int SC_MOVED_TEMPORARILY

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

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:org.xmlblackbox.test.infrastructure.xml.HTTPUploader.java

public void uploadFile(MemoryData memory, HTTPUploader httpClient)
        throws TestException, HttpException, IOException {
    int ris;/*w w w  .  j  a  va 2s  .c  o  m*/
    HttpClient hClient = new HttpClient();

    Properties prop = memory.getOrCreateRepository(getRepositoryName());
    logger.info("prop " + prop);

    /**
     * Effettua la login
     */
    String usernameStr = (String) httpClient.getParameters().get("username");
    String passwordStr = (String) httpClient.getParameters().get("password");

    Properties fileProperties = memory.getOrCreateRepository(Repository.FILE_PROPERTIES);

    logger.info("Login al " + urlLogin);
    PostMethod postMethodLogin = new PostMethod(urlLogin);
    NameValuePair username = new NameValuePair();
    username.setName("userId");
    username.setValue(usernameStr);
    logger.info("username " + usernameStr);
    NameValuePair password = new NameValuePair();
    password.setName("password");
    password.setValue(passwordStr);
    logger.info("password " + passwordStr);

    if (usernameStr != null) {
        postMethodLogin.addParameter(username);
    }
    if (passwordStr != null) {
        postMethodLogin.addParameter(password);
    }
    ris = hClient.executeMethod(postMethodLogin);
    logger.debug("ris Login password " + passwordStr + " " + ris);

    if (ris != HttpStatus.SC_MOVED_TEMPORARILY) {
        throw new TestException("Error during login for uploading the file");
    }

    XmlObject[] domandeXml = null;

    File fileXML = new File(httpClient.getFileToUpload());
    PostMethod postm = new PostMethod(urlUpload);

    logger.debug("fileXML.getName() " + fileXML.getName());
    logger.debug("fileXML " + fileXML);
    logger.debug("postm.getParams()  " + postm.getParams());
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_NAME\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_NAME"));
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_VALUE\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_VALUE"));

    try {
        Part[] parts = {
                new StringPart(httpClient.getParameters().get("OPERATION_UPLOAD_NAME"),
                        httpClient.getParameters().get("OPERATION_UPLOAD_VALUE")),
                new FilePart("file", fileXML.getName(), fileXML) };

        postm.setRequestEntity(new MultipartRequestEntity(parts, postm.getParams()));
        logger.debug("parts " + parts);
    } catch (FileNotFoundException e2) {
        logger.error("FileNotFoundException ", e2);
        throw new TestException(e2, "FileNotFoundException ");
    }

    hClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);

    try {
        ris = hClient.executeMethod(postm);
        logger.info("ris Upload password " + passwordStr + " " + ris);
        logger.debug("ris Upload password " + passwordStr + " " + ris);
        if (ris == HttpStatus.SC_OK) {
            //logger.info("Upload completo, risposta=" + postm.getResponseBodyAsString());

            InputStream in = postm.getResponseBodyAsStream();
            //OutputStream out = new FileOutputStream(new File(prop.getProperty("FILE_RISPOSTA_SERVLET")));
            OutputStream out = new FileOutputStream(new File(httpClient.getFileOutput()));
            OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");

            BufferedReader bufferedReader = new BufferedReader(reader);

            // Transfer bytes from in to out
            //byte[] buf = new byte[1024];
            //int len;
            String linea = null;
            while ((linea = bufferedReader.readLine()) != null) {
                writer.write(linea);
            }
            writer.close();
            reader.close();
            in.close();
            out.close();

        } else {
            logger.error("Upload failed, response =" + HttpStatus.getStatusText(ris));
            logger.error("Exception : Server response not correct ");
            throw new TestException("Exception : Server response not correct ");
        }
    } catch (HttpException e) {
        logger.error("Exception : Server response not correct ", e);
        throw new TestException(e, "");
    } catch (IOException e) {
        logger.error("Exception : Server response not correct ", e);

        throw new TestException(e, "");
    } finally {
        postm.releaseConnection();
    }
}

From source file:org.ybygjy.httpclient.FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/org.ybygjy.web.servlet.HttpClientServlet");

    client.executeMethod(authget);/*www.  ja v a  2 s.  com*/
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/org.ybygjy.web.servlet.HttpClientServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is 
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // Usually a successful form-based login results in a redicrect to 
    // another url
    int statuscode = authpost.getStatusCode();
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = authpost.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

/**
 * Get response body through non-standard POST method.
 * Please refer to <url>http://stackoverflow.com/questions/1473255/is-jakarta-httpclient-sutitable-for-the-following-task/1473305#1473305</url>
 *
 * @param uri For example, http://X/%5bvUpJYKw4QvGRMBmhATUxRwv4JrU9aDnwNEuangVyy6OuHxi2YiY=%5dImage?
 * @param formData For example, [SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51
 * @return the response body. null if fail.
 *//* ww  w.j av  a  2 s. c o  m*/
public static String getPOSTResponseBodyAsStringBasedOnProxyAuthOption(String uri, String formData) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final PostMethod method = new PostMethod(uri);
    final RequestEntity entity;
    try {
        entity = new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8");
    } catch (UnsupportedEncodingException exp) {
        log.error(null, exp);
        return null;
    }
    method.setRequestEntity(entity);
    method.setContentChunked(false);

    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (false/*jStockOptions.isProxyAuthEnabled()*/) {
            /* WARNING : This chunck of code block is not tested! */
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                /* WARNING : Correct method to redirect? Shall we use POST? How about form data? */
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

public static String getResponseBodyAsStringBasedOnProxyAuthOption(String request) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    if (!mytest)//from w w w.j a va 2s. co m
        org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final HttpMethod method = new GetMethod(request);
    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (true/*!mytest&&jStockOptions.isProxyAuthEnabled()*/) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

public static InputStreamAndMethod getResponseBodyAsStreamBasedOnProxyAuthOption(String request) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final GetMethod method = new GetMethod(request);
    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    InputStreamAndMethod inputStreamAndMethod = null;
    InputStream respond = null;//from   w  w  w.j av a 2 s . co m
    HttpMethod methodToClosed = method;

    try {
        if (false/*jStockOptions.isProxyAuthEnabled()*/) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                GetMethod RedirectMethod = new GetMethod(header.getValue());
                methodToClosed = RedirectMethod;
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422                    
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsStream();
                } catch (HttpException exp) {
                    log.error(null, exp);
                } catch (IOException exp) {
                    log.error(null, exp);
                }
            } else {
                methodToClosed = method;
                respond = method.getResponseBodyAsStream();
            } // if statuscode = Redirect
        } else {
            methodToClosed = method;
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsStream();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
    } catch (IOException exp) {
        log.error(null, exp);
    } finally {
        inputStreamAndMethod = new InputStreamAndMethod(respond, methodToClosed);
    }

    return inputStreamAndMethod;
}

From source file:org.yccheok.jstock.gui.Utils.java

/**
 * Get response body through non-standard POST method.
 * Please refer to <url>http://stackoverflow.com/questions/1473255/is-jakarta-httpclient-sutitable-for-the-following-task/1473305#1473305</url>
 *
 * @param uri For example, http://X/%5bvUpJYKw4QvGRMBmhATUxRwv4JrU9aDnwNEuangVyy6OuHxi2YiY=%5dImage?
 * @param formData For example, [SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51
 * @return the response body. null if fail.
 *///from   w  w w.j a  v  a2 s. co  m
public static String getPOSTResponseBodyAsStringBasedOnProxyAuthOption(String uri, String formData) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final PostMethod method = new PostMethod(uri);
    final RequestEntity entity;
    try {
        entity = new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8");
    } catch (UnsupportedEncodingException exp) {
        log.error(null, exp);
        return null;
    }
    method.setRequestEntity(entity);
    method.setContentChunked(false);

    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    String respond = null;
    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            /* WARNING : This chunck of code block is not tested! */
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                /* WARNING : Correct method to redirect? Shall we use POST? How about form data? */
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.Utils.java

private static String _getResponseBodyAsStringBasedOnProxyAuthOption(HttpClient client, String request) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(client);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(client);

    final HttpMethod method = new GetMethod(request);
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    String respond = null;//from w w  w  .  j av  a2  s.c  o  m
    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            method.setFollowRedirects(false);
            client.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    client.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            client.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.Utils.java

public static InputStreamAndMethod getResponseBodyAsStreamBasedOnProxyAuthOption(String request) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final GetMethod method = new GetMethod(request);
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    InputStreamAndMethod inputStreamAndMethod = null;
    InputStream respond = null;//from www .  j av  a2  s.  co  m
    HttpMethod methodToClosed = method;

    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                GetMethod RedirectMethod = new GetMethod(header.getValue());
                methodToClosed = RedirectMethod;
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422                    
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsStream();
                } catch (HttpException exp) {
                    log.error(null, exp);
                } catch (IOException exp) {
                    log.error(null, exp);
                }
            } else {
                methodToClosed = method;
                respond = method.getResponseBodyAsStream();
            } // if statuscode = Redirect
        } else {
            methodToClosed = method;
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsStream();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
    } catch (IOException exp) {
        log.error(null, exp);
    } finally {
        inputStreamAndMethod = new InputStreamAndMethod(respond, methodToClosed);
    }

    return inputStreamAndMethod;
}

From source file:org.zaizi.alfresco.redlink.service.search.solr.SensefySolrQueryHTTPClient.java

public ResultSet executeQuery(SearchParameters searchParameters)// , String language)
{
    if (repositoryState.isBootstrapping()) {
        throw new AlfrescoRuntimeException(
                "SOLR queries can not be executed while the repository is bootstrapping");
    }/*www  . j a v  a  2  s.  c  om*/

    try {
        if (searchParameters.getStores().size() == 0) {
            throw new AlfrescoRuntimeException("No store for query");
        }

        URLCodec encoder = new URLCodec();
        StringBuilder url = new StringBuilder();
        url.append(sensefySearchEndpoint);

        // Send the query
        url.append("?query=");
        url.append(encoder.encode(searchParameters.getQuery(), "UTF-8"));
        // url.append("?wt=").append(encoder.encode("json", "UTF-8"));
        url.append("&fields=").append(encoder.encode("DBID,score", "UTF-8"));

        // Emulate old limiting behaviour and metadata
        final LimitBy limitBy;
        int maxResults = -1;
        if (searchParameters.getMaxItems() >= 0) {
            maxResults = searchParameters.getMaxItems();
            limitBy = LimitBy.FINAL_SIZE;
        } else if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE && searchParameters.getLimit() >= 0) {
            maxResults = searchParameters.getLimit();
            limitBy = LimitBy.FINAL_SIZE;
        } else {
            maxResults = searchParameters.getMaxPermissionChecks();
            if (maxResults < 0) {
                maxResults = maximumResultsFromUnlimitedQuery;
            }
            limitBy = LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS;
        }
        url.append("&rows=").append(String.valueOf(maxResults));

        // url.append("&df=").append(encoder.encode(searchParameters.getDefaultFieldName(), "UTF-8"));
        url.append("&start=").append(encoder.encode("" + searchParameters.getSkipCount(), "UTF-8"));

        // Locale locale = I18NUtil.getLocale();
        // if (searchParameters.getLocales().size() > 0)
        // {
        // locale = searchParameters.getLocales().get(0);
        // }
        // url.append("&locale=");
        // url.append(encoder.encode(locale.toString(), "UTF-8"));

        StringBuffer sortBuffer = new StringBuffer();
        for (SortDefinition sortDefinition : searchParameters.getSortDefinitions()) {
            if (sortBuffer.length() == 0) {
                sortBuffer.append("&sort=");
            } else {
                sortBuffer.append(encoder.encode(", ", "UTF-8"));
            }
            sortBuffer.append(encoder.encode(sortDefinition.getField(), "UTF-8"))
                    .append(encoder.encode(" ", "UTF-8"));
            if (sortDefinition.isAscending()) {
                sortBuffer.append(encoder.encode("asc", "UTF-8"));
            } else {
                sortBuffer.append(encoder.encode("desc", "UTF-8"));
            }

        }
        url.append(sortBuffer);

        if (searchParameters.getFieldFacets().size() > 0) {
            for (FieldFacet facet : searchParameters.getFieldFacets()) {
                url.append("&facet=").append(encoder.encode(facet.getField(), "UTF-8"));
            }
        }
        // end of field factes

        // add current username doing the request for permissions
        url.append("&userName=").append(encoder.encode(AuthenticationUtil.getRunAsUser(), "UTF-8"));

        GetMethod get = new GetMethod(url.toString());

        try {
            httpClient.executeMethod(get);

            if (get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = get.getResponseHeader("location");
                if (locationHeader != null) {
                    String redirectLocation = locationHeader.getValue();
                    get.setURI(new URI(redirectLocation, true));
                    httpClient.executeMethod(get);
                }
            }

            if (get.getStatusCode() != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException(
                        "Request failed " + get.getStatusCode() + " " + url.toString());
            }

            Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
            JSONObject json = new JSONObject(new JSONTokener(reader));
            SensefySolrJSONResultSet results = new SensefySolrJSONResultSet(json, searchParameters, nodeService,
                    nodeDAO, limitBy, maxResults);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Sent :" + url);
                s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
            }

            return results;
        } finally {
            get.releaseConnection();
        }
    } catch (UnsupportedEncodingException e) {
        throw new LuceneQueryParserException("", e);
    } catch (HttpException e) {
        throw new LuceneQueryParserException("", e);
    } catch (IOException e) {
        throw new LuceneQueryParserException("", e);
    } catch (JSONException e) {
        throw new LuceneQueryParserException("", e);
    }
}

From source file:ru.org.linux.topic.AddTopicControllerWebTest.java

@Test
public void testPostSuccess() throws IOException {
    String auth = WebHelper.doLogin(resource, TEST_USER, TEST_PASSWORD);

    MultivaluedMap<String, String> formData = new MultivaluedMapImpl();

    formData.add("section", Integer.toString(Section.SECTION_FORUM));
    formData.add("group", Integer.toString(TEST_GROUP));
    formData.add("csrf", "csrf");
    formData.add("title", TEST_TITLE);

    ClientResponse cr = resource.path("add.jsp")
            .cookie(new Cookie(WebHelper.AUTH_COOKIE, auth, "/", "127.0.0.1", 1))
            .cookie(new Cookie(CSRFProtectionService.CSRF_COOKIE, "csrf")).post(ClientResponse.class, formData);

    Document doc = Jsoup.parse(cr.getEntityInputStream(), "UTF-8", resource.getURI().toString());

    assertTrue(doc.select(".error").text(), doc.select("#messageForm").isEmpty());

    assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, cr.getStatus());

    ClientResponse tempPage = resource // TODO remove temp redirect from Controller
            .uri(cr.getLocation()).get(ClientResponse.class);

    assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, tempPage.getStatus());

    ClientResponse page = resource.uri(tempPage.getLocation()).get(ClientResponse.class);

    assertEquals(HttpStatus.SC_OK, page.getStatus());

    Document finalDoc = Jsoup.parse(page.getEntityInputStream(), "UTF-8", resource.getURI().toString());

    assertEquals(TEST_TITLE, finalDoc.select("h1[itemprop=headline] a").text());
}