List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY
int SC_MOVED_TEMPORARILY
To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.
Click Source Link
From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java
/** * @param storeRef/*from w w w .j ava 2s. c o m*/ * @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 {//from w ww.java 2s . co 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(); ///*from w w w.j a va 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 {/*from ww w . j a v 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.hadoop.mapreduce.v2.app.webapp.TestAMWebApp.java
@Test public void testMRWebAppRedirection() throws Exception { String[] schemePrefix = { WebAppUtils.HTTP_PREFIX, WebAppUtils.HTTPS_PREFIX }; for (String scheme : schemePrefix) { MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) { @Override/*from ww w . ja va 2s. c om*/ protected ClientService createClientService(AppContext context) { return new MRClientService(context); } }; Configuration conf = new Configuration(); conf.set(YarnConfiguration.PROXY_ADDRESS, "9.9.9.9"); conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, scheme.equals(WebAppUtils.HTTPS_PREFIX) ? Policy.HTTPS_ONLY.name() : Policy.HTTP_ONLY.name()); webProxyBase = "/proxy/" + app.getAppID(); conf.set("hadoop.http.filter.initializers", TestAMFilterInitializer.class.getName()); Job job = app.submit(conf); String hostPort = NetUtils .getHostPortString(((MRClientService) app.getClientService()).getWebApp().getListenerAddress()); URL httpUrl = new URL("http://" + hostPort + "/mapreduce"); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); String expectedURL = scheme + conf.get(YarnConfiguration.PROXY_ADDRESS) + ProxyUriUtils.getPath(app.getAppID(), "/mapreduce"); Assert.assertEquals(expectedURL, conn.getHeaderField(HttpHeaders.LOCATION)); Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, conn.getResponseCode()); app.waitForState(job, JobState.SUCCEEDED); app.verifyCompleted(); } }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** {@inheritDoc} */ public LinkValidationResult validateLink(LinkValidationItem lvi) { if (this.cl == null) { initHttpClient();/*from w w w. j a v a 2s .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./*from ww w. jav a2s . co m*/ * * @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.plugin.jira.AbstractJiraDownloader.java
/** * Downloads the given link using the configured HttpClient, possibly following redirects. * * @param cl the HttpClient/* w w w.j a v a 2s . c o m*/ * @param link the URL to JIRA */ private void download(final HttpClient cl, final String link) { try { GetMethod gm = new GetMethod(link); getLog().info("Downloading from JIRA at: " + link); gm.setFollowRedirects(true); cl.executeMethod(gm); StatusLine sl = gm.getStatusLine(); if (sl == null) { getLog().error("Unknown error validating link: " + link); return; } // if we get a redirect, do so if (gm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = gm.getResponseHeader("Location"); if (locationHeader == null) { getLog().warn("Site sent redirect, but did not set Location header"); } else { String newLink = locationHeader.getValue(); getLog().debug("Following redirect to " + newLink); download(cl, newLink); } } if (gm.getStatusCode() == HttpStatus.SC_OK) { final InputStream responseBodyStream = gm.getResponseBodyAsStream(); if (!output.getParentFile().exists()) { output.getParentFile().mkdirs(); } // write the response to file OutputStream out = null; try { out = new FileOutputStream(output); IOUtil.copy(responseBodyStream, out); } finally { IOUtil.close(out); IOUtil.close(responseBodyStream); } getLog().debug("Downloading from JIRA was successful"); } else { getLog().warn("Downloading from JIRA failed. Received: [" + gm.getStatusCode() + "]"); } } catch (HttpException e) { if (getLog().isDebugEnabled()) { getLog().error("Error downloading issues from JIRA:", e); } else { getLog().error("Error downloading issues from JIRA url: " + e.getLocalizedMessage()); } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().error("Error downloading issues from JIRA:", e); } else { getLog().error("Error downloading issues from JIRA. Cause is " + e.getLocalizedMessage()); } } }
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 www. j a v a 2 s .c o 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.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
protected void removeConfiguration(final HttpClient client, final String targetURL, String pid) throws MojoExecutionException { final String postUrl = targetURL + "/configMgr/" + pid; final PostMethod post = new PostMethod(postUrl); post.addParameter("apply", "true"); post.addParameter("delete", "true"); try {/* w w w. j a va 2 s. co m*/ final int status = client.executeMethod(post); // we get a moved temporarily back from the configMgr plugin if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) { getLog().debug("Configuration removed."); } else { getLog().error("Removing configuration failed, cause: " + HttpStatus.getStatusText(status)); } } catch (HttpException ex) { throw new MojoExecutionException( "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoExecutionException( "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex); } finally { post.releaseConnection(); } }