List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY
int SC_MOVED_PERMANENTLY
To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.
Click Source Link
From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException { PostMethod post = new PostMethod(url); if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) { post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); }//from w ww .ja va 2s.c o m post.setRequestEntity(new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json")); try { httpClient.executeMethod(post); if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); post.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(post); } } if (post.getStatusCode() != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException( "Request failed " + post.getStatusCode() + " " + url.toString()); } Reader reader = new BufferedReader( new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler JSONObject json = new JSONObject(new JSONTokener(reader)); if (json.has("status")) { JSONObject status = json.getJSONObject("status"); if (status.getInt("code") != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException("SOLR side error: " + status.getString("message")); } } return json; } finally { post.releaseConnection(); } }
From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java
/** * @param storeRef/*from w w w .j a v a2 s .com*/ * @param handler * @param params * @return */ public JSONObject execute(StoreRef storeRef, String handler, HashMap<String, String> params) { try { SolrStoreMappingWrapper mapping = extractMapping(storeRef); URLCodec encoder = new URLCodec(); StringBuilder url = new StringBuilder(); Pair<HttpClient, String> httpClientAndBaseUrl = mapping.getHttpClientAndBaseUrl(); HttpClient httpClient = httpClientAndBaseUrl.getFirst(); for (String key : params.keySet()) { String value = params.get(key); if (url.length() == 0) { url.append(httpClientAndBaseUrl.getSecond()); if (!handler.startsWith("/")) { url.append("/"); } url.append(handler); url.append("?"); url.append(encoder.encode(key, "UTF-8")); url.append("="); url.append(encoder.encode(value, "UTF-8")); } else { url.append("&"); url.append(encoder.encode(key, "UTF-8")); url.append("="); url.append(encoder.encode(value, "UTF-8")); } } if (mapping.isSharded()) { url.append("&shards="); url.append(mapping.getShards()); } // PostMethod post = new PostMethod(url.toString()); 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)); return json; } 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:org.alfresco.repo.solr.EmbeddedSolrTest.java
public JSONObject execute(HashMap<String, String> args) { try {/* www. ja v a2s . c o m*/ URLCodec encoder = new URLCodec(); StringBuilder url = new StringBuilder(); for (String key : args.keySet()) { String value = args.get(key); if (url.length() == 0) { url.append(baseUrl); url.append("?"); url.append(encoder.encode(key, "UTF-8")); url.append("="); url.append(encoder.encode(value, "UTF-8")); } else { url.append("&"); url.append(encoder.encode(key, "UTF-8")); url.append("="); url.append(encoder.encode(value, "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)); return json; } 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:org.apache.commons.httpclient.demo.RedirectDemo.java
public static void main(String[] args) { HttpClient client = new HttpClient(); //// w ww . j a v a 2 s . c o m //client.getHostConfiguration().setProxy("90.0.12.21", 808); //client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http"); PostMethod post = new PostMethod("http://90.0.12.20:8088/NationWideAdmin/test/RedirectDemo.jsp"); try { client.executeMethod(post); } catch (IOException ex) { } System.out.println(post.getStatusLine().toString()); post.releaseConnection(); // int statuscode = post.getStatusCode(); /* HttpServletResponse 301 SC_MOVED_PERMANENTLY 302 SC_MOVED_TEMPORARILY 303 SC_SEE_OTHER URL 307 SC_TEMPORARY_REDIRECT SC_MOVED_TEMPORARILY */ System.out.println("" + statuscode); System.out.println("HttpStatus.SC_MOVED_TEMPORARILY" + HttpStatus.SC_MOVED_TEMPORARILY); System.out.println("HttpStatus.SC_MOVED_PERMANENTLY" + HttpStatus.SC_MOVED_PERMANENTLY); System.out.println("HttpStatus.SC_SEE_OTHER" + HttpStatus.SC_SEE_OTHER); System.out.println("HttpStatus.SC_TEMPORARY_REDIRECT" + HttpStatus.SC_TEMPORARY_REDIRECT); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { //URL Header header = post.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } GetMethod redirect = new GetMethod(newuri); try { client.executeMethod(redirect); } catch (IOException ex1) { } System.out.println("Redirect:" + redirect.getStatusLine().toString()); redirect.releaseConnection(); } else { System.out.println("Invalid redirect"); } } }
From source file:org.apache.falcon.logging.v1.TaskLogRetrieverV1.java
private String getHistoryFile(Configuration conf, String jobId) throws IOException { String jtAddress = "scheme://" + conf.get("mapred.job.tracker"); String jtHttpAddr = "scheme://" + conf.get("mapred.job.tracker.http.address"); try {// w w w. j av a 2 s .c o m String host = new URI(jtAddress).getHost(); int port = new URI(jtHttpAddr).getPort(); HttpClient client = new HttpClient(); String jobUrl = "http://" + host + ":" + port + "/jobdetails.jsp"; GetMethod get = new GetMethod(jobUrl); get.setQueryString("jobid=" + jobId); get.setFollowRedirects(false); int status = client.executeMethod(get); String file = null; if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { file = get.getResponseHeader("Location").toString(); file = file.substring(file.lastIndexOf('=') + 1); file = JobHistory.JobInfo.decodeJobHistoryFileName(file); } else { LOG.warn("JobURL {} for id: {} returned {}", jobUrl, jobId, status); } return file; } catch (URISyntaxException e) { throw new IOException("JT Address: " + jtAddress + ", http Address: " + jtHttpAddr, e); } }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** {@inheritDoc} */ public LinkValidationResult validateLink(LinkValidationItem lvi) { if (this.cl == null) { initHttpClient();//ww w . j a v a 2 s . c om } if (this.http.getHttpClientParameters() != null) { for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) { if (entry.getValue() != null) { System.setProperty(entry.getKey().toString(), entry.getValue().toString()); } } } // Some web servers don't allow the default user-agent sent by httpClient System.setProperty(HttpMethodParams.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); this.cl.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); String link = lvi.getLink(); String anchor = ""; int idx = link.indexOf('#'); if (idx != -1) { anchor = link.substring(idx + 1); link = link.substring(0, idx); } try { if (link.startsWith("/")) { if (getBaseURL() == null) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot check link [" + link + "] in page [" + lvi.getSource() + "], as no base URL has been set!"); } return new LinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, false, "No base URL specified"); } link = getBaseURL() + link; } HttpMethod hm = null; try { hm = checkLink(link, 0); } catch (Throwable t) { if (LOG.isDebugEnabled()) { LOG.debug("Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]", t); } return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, t.getClass().getName() + " : " + t.getMessage()); } if (hm == null) { return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, "Cannot retreive HTTP Status"); } if (hm.getStatusCode() == HttpStatus.SC_OK) { // lets check if the anchor is present if (anchor.length() > 0) { String content = hm.getResponseBodyAsString(); if (!Anchors.matchesAnchor(content, anchor)) { return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, false, "Missing anchor '" + anchor + "'"); } } return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, true, hm.getStatusCode(), hm.getStatusText()); } String msg = "Received: [" + hm.getStatusCode() + "] for [" + link + "] in page [" + lvi.getSource() + "]"; // If there's a redirection ... add a warning if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { LOG.warn(msg); return new HTTPLinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, true, hm.getStatusCode(), hm.getStatusText()); } LOG.debug(msg); return new HTTPLinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, hm.getStatusCode(), hm.getStatusText()); } catch (Throwable t) { String msg = "Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]"; if (LOG.isDebugEnabled()) { LOG.debug(msg, t); } else { LOG.error(msg); } return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, t.getMessage()); } finally { System.getProperties().remove(HttpMethodParams.USER_AGENT); if (this.http.getHttpClientParameters() != null) { for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) { if (entry.getValue() != null) { System.getProperties().remove(entry.getKey().toString()); } } } } }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** * Checks the given link./* ww w . j a va 2 s .com*/ * * @param link the link to check. * @param nbRedirect the number of current redirects. * @return HttpMethod * @throws IOException if something goes wrong. */ private HttpMethod checkLink(String link, int nbRedirect) throws IOException { int max = MAX_NB_REDIRECT; if (this.http.getHttpClientParameters() != null && this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS) != null) { try { max = Integer .valueOf(this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS).toString()) .intValue(); } catch (NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("HttpClient parameter '" + HttpClientParams.MAX_REDIRECTS + "' is not a number. Ignoring!"); } } } if (nbRedirect > max) { throw new HttpException("Maximum number of redirections (" + max + ") exceeded"); } HttpMethod hm; if (HEAD_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new HeadMethod(link); } else if (GET_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new GetMethod(link); } else { if (LOG.isErrorEnabled()) { LOG.error("Unsupported method: " + this.http.getMethod() + ", using 'get'."); } hm = new GetMethod(link); } // Default hm.setFollowRedirects(this.http.isFollowRedirects()); try { URL url = new URL(link); cl.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol()); cl.executeMethod(hm); StatusLine sl = hm.getStatusLine(); if (sl == null) { if (LOG.isErrorEnabled()) { LOG.error("Unknown error validating link : " + link); } return null; } if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { Header locationHeader = hm.getResponseHeader("location"); if (locationHeader == null) { LOG.error("Site sent redirect, but did not set Location header"); return hm; } String newLink = locationHeader.getValue(); // Be careful to absolute/relative links if (!newLink.startsWith("http://") && !newLink.startsWith("https://")) { if (newLink.startsWith("/")) { URL oldUrl = new URL(link); newLink = oldUrl.getProtocol() + "://" + oldUrl.getHost() + (oldUrl.getPort() > 0 ? ":" + oldUrl.getPort() : "") + newLink; } else { newLink = link + newLink; } } HttpMethod oldHm = hm; if (LOG.isDebugEnabled()) { LOG.debug("[" + link + "] is redirected to [" + newLink + "]"); } oldHm.releaseConnection(); hm = checkLink(newLink, nbRedirect + 1); // Restore the hm to "Moved permanently" | "Moved temporarily" | "Temporary redirect" // if the new location is found to allow us to report it if (hm.getStatusCode() == HttpStatus.SC_OK && nbRedirect == 0) { return oldHm; } } } finally { hm.releaseConnection(); } return hm; }
From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java
private void put(Resource resource, File source, RequestEntityImplementation requestEntityImplementation, String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { // preemptive true for put client.getParams().setAuthenticationPreemptive(true); //Parent directories need to be created before posting try {//from w w w . jav a2 s . co m mkdirs(PathUtils.dirname(resource.getName())); } catch (IOException e) { fireTransferError(resource, e, TransferEvent.REQUEST_GET); } PutMethod putMethod = new PutMethod(url); firePutStarted(resource, source); try { putMethod.setRequestEntity(requestEntityImplementation); int statusCode; try { statusCode = execute(putMethod); } catch (IOException e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException(e.getMessage(), e); } fireTransferDebug(url + " - Status code: " + statusCode); // Check that we didn't run out of retries. switch (statusCode) { // Success Codes case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 case HttpStatus.SC_ACCEPTED: // 202 case HttpStatus.SC_NO_CONTENT: // 204 break; // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user" case HttpStatus.SC_MOVED_PERMANENTLY: // 301 case HttpStatus.SC_MOVED_TEMPORARILY: // 302 case HttpStatus.SC_SEE_OTHER: // 303 String relocatedUrl = calculateRelocatedUrl(putMethod); fireTransferDebug("relocate to " + relocatedUrl); put(resource, source, requestEntityImplementation, relocatedUrl); return; case SC_NULL: { TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url); fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; } case HttpStatus.SC_FORBIDDEN: fireSessionConnectionRefused(); throw new AuthorizationException("Access denied to: " + url); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException("File: " + url + " does not exist"); //add more entries here default: { TransferFailedException e = new TransferFailedException( "Failed to transfer file: " + url + ". Return code is: " + statusCode); fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; } } firePutCompleted(resource, source); } finally { putMethod.releaseConnection(); } }
From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebSession.java
private HostConfiguration login(HttpClient httpClient, IProgressMonitor monitor) throws JiraException { RedirectTracker tracker = new RedirectTracker(); String url = baseUrl + "/login.jsp"; //$NON-NLS-1$ for (int i = 0; i <= MAX_REDIRECTS; i++) { AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (credentials == null) { // TODO prompt user? credentials = new AuthenticationCredentials("", ""); //$NON-NLS-1$ //$NON-NLS-2$ }// w ww. jav a 2 s . co m PostMethod login = new PostMethod(url); login.setFollowRedirects(false); login.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); login.setRequestHeader("Content-Type", getContentType()); //$NON-NLS-1$ login.addParameter("os_username", credentials.getUserName()); //$NON-NLS-1$ login.addParameter("os_password", credentials.getPassword()); //$NON-NLS-1$ login.addParameter("os_destination", "/success"); //$NON-NLS-1$ //$NON-NLS-2$ tracker.addUrl(url); try { HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); int statusCode = WebUtil.execute(httpClient, hostConfiguration, login, monitor); if (needsReauthentication(httpClient, login, monitor)) { continue; } else if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY && statusCode != HttpStatus.SC_MOVED_PERMANENTLY) { throw new JiraServiceUnavailableException("Unexpected status code during login: " + statusCode); //$NON-NLS-1$ } tracker.addRedirect(url, login, statusCode); this.characterEncoding = login.getResponseCharSet(); Header locationHeader = login.getResponseHeader("location"); //$NON-NLS-1$ if (locationHeader == null) { throw new JiraServiceUnavailableException("Invalid redirect, missing location"); //$NON-NLS-1$ } url = locationHeader.getValue(); tracker.checkForCircle(url); if (!insecureRedirect && isSecure() && url.startsWith("http://")) { //$NON-NLS-1$ tracker.log("Redirect to insecure location during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$ insecureRedirect = true; } if (url.endsWith("/success")) { //$NON-NLS-1$ String newBaseUrl = url.substring(0, url.lastIndexOf("/success")); //$NON-NLS-1$ if (baseUrl.equals(newBaseUrl) || !client.getConfiguration().getFollowRedirects()) { // success addAuthenticationCookie(httpClient, login); return hostConfiguration; } else { // need to login to make sure HttpClient picks up the session cookie baseUrl = newBaseUrl; url = newBaseUrl + "/login.jsp"; //$NON-NLS-1$ } } } catch (IOException e) { throw new JiraServiceUnavailableException(e); } finally { login.releaseConnection(); } } tracker.log( "Exceeded maximum number of allowed redirects during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$ throw new JiraServiceUnavailableException("Exceeded maximum number of allowed redirects during login"); //$NON-NLS-1$ }
From source file:org.executequery.http.spi.DefaultRemoteHttpClient.java
private boolean isRedirection(int responseCode) { return responseCode == HttpStatus.SC_MOVED_PERMANENTLY || responseCode == HttpStatus.SC_MOVED_TEMPORARILY || responseCode == HttpStatus.SC_SEE_OTHER || responseCode == HttpStatus.SC_TEMPORARY_REDIRECT; }