List of usage examples for io.netty.handler.codec.http HttpResponseStatus TEMPORARY_REDIRECT
HttpResponseStatus TEMPORARY_REDIRECT
To view the source code for io.netty.handler.codec.http HttpResponseStatus TEMPORARY_REDIRECT.
Click Source Link
From source file:com.mesosphere.mesos.rx.java.MesosClient.java
License:Apache License
@NotNull // @VisibleForTesting static URI getUriFromRedirectResponse(final @NotNull URI mesosUri, @NotNull final HttpClientResponse<ByteBuf> redirectResponse) { if (redirectResponse.getStatus().equals(HttpResponseStatus.TEMPORARY_REDIRECT)) { final String location = redirectResponse.getHeaders().get("Location"); final URI newUri = resolveRelativeUri(mesosUri, location); LOGGER.info("Using new Mesos URI: {}", newUri); return newUri; } else {/*from w w w . j a va2s.c om*/ LOGGER.info("Continuing with Mesos URI as-is"); return mesosUri; } }
From source file:com.mesosphere.mesos.rx.java.MesosClientTest.java
License:Apache License
@Test public void testGetUriFromRedirectResponse() throws Exception { final URI mesosUri = URI.create("http://127.1.0.1:5050/api/v1/scheduler"); final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT); nettyResponse.headers().add("Location", "//127.1.0.2:5050"); final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(nettyResponse, UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)); final URI uri = MesosClient.getUriFromRedirectResponse(mesosUri, response); assertThat(uri).isEqualTo(URI.create("http://127.1.0.2:5050/api/v1/scheduler")); }
From source file:com.stremebase.examples.todomvc.HttpRouter.java
License:Apache License
private static HttpResponse createResponse(HttpRequest req, Router<Integer> router) { RouteResult<Integer> routeResult = router.route(req.getMethod(), req.getUri()); Integer request = routeResult.target(); String data = ""; String mimeType = ""; if (request == CSS) { data = Todo.getCss();/*www. j a v a 2 s.c o m*/ mimeType = "text/css"; } else if (request == ICON) { mimeType = "image/x-icon"; } else if (request == GET) { data = Todo.get(); mimeType = "text/html"; } else if (request == FILTER) { data = Todo.filter(routeResult.pathParams().get("filtertype")); mimeType = "text/html"; } else if (req.getMethod().equals(HttpMethod.POST)) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req); Attribute attribute; String item_text = null; InterfaceHttpData httpData = decoder.getBodyHttpData("item-text"); if (httpData != null) { attribute = (Attribute) httpData; try { item_text = attribute.getValue(); } catch (IOException e) { e.printStackTrace(); } } String item_id = null; httpData = decoder.getBodyHttpData("item-id"); if (httpData != null) { attribute = (Attribute) httpData; try { item_id = attribute.getValue(); } catch (IOException e) { e.printStackTrace(); } } if (request == POST) { if (item_id == null) data = Todo.create(item_text); else data = Todo.save(Long.valueOf(item_id), item_text); } else if (request == DELETE) { data = Todo.delete(Long.valueOf(item_id)); } else if (request == DELETECOMPLETED) { data = Todo.clearCompleted(); } else if (request == TOGGLESTATUS) data = Todo.toggleStatus(Long.valueOf(item_id)); mimeType = "text/html"; decoder.destroy(); } FullHttpResponse res; if (request == NOTFOUND) { res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT); res.headers().add(HttpHeaders.Names.LOCATION, "/"); return res; } if (request == ICON) res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(Todo.favicon)); else res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(data, CharsetUtil.UTF_8)); res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeType); res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, res.content().readableBytes()); if (request == CSS || request == ICON) setDateAndCacheHeaders(res); return res; }
From source file:io.reactivex.netty.protocol.http.client.RedirectOperatorTest.java
License:Apache License
@Test public void testMaxRedirects() throws Exception { Setup setup = new Setup().setup(HttpResponseStatus.TEMPORARY_REDIRECT); Assert.assertEquals("Unexpected redirect count.", 2, setup.getHandler().getRedirectsRequested()); Assert.assertEquals("Unexpected onComplete calls to redirect subscriber.", 0, setup.getSubscriber().getOnCompletes()); Assert.assertEquals("Unexpected onNext calls to redirect subscriber.", 0, setup.getSubscriber().getOnNexts()); Assert.assertEquals("Unexpected onError calls to redirect subscriber.", 1, setup.getSubscriber().getOnErrors()); }
From source file:jj.http.server.HttpServerResponseImpl.java
License:Apache License
/** * Sends a 307 Temporary Redirect to the given resource, using the fully qualified * asset URL and disallowing the redirect to be cached. Ends the response. * @param resource/*from w w w . ja v a 2 s.com*/ * @return */ @Override public HttpServerResponse sendTemporaryRedirect(final Resource resource) { assertNotCommitted(); return status(HttpResponseStatus.TEMPORARY_REDIRECT) .header(HttpHeaders.Names.LOCATION, makeAbsoluteURL(resource)) .header(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.NO_STORE).end(); }
From source file:mousio.etcd4j.transport.EtcdResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Received " + response.status().code() + " for " + this.request.getMethod().name() + " " + this.request.getUri()); }/*from w ww .j ava 2 s . com*/ if (response.status().equals(HttpResponseStatus.MOVED_PERMANENTLY) || response.status().equals(HttpResponseStatus.TEMPORARY_REDIRECT)) { if (response.headers().contains(HTTP_HEADER_LOCATION)) { this.request.setUrl(response.headers().get(HTTP_HEADER_LOCATION)); this.client.connect(this.request); // Closing the connection which handled the previous request. ctx.close(); if (logger.isDebugEnabled()) { logger.debug("redirect for " + this.request.getHttpRequest().uri() + " to " + response.headers().get(HTTP_HEADER_LOCATION)); } } else { this.promise.setFailure(new Exception("Missing Location header on redirect")); } } if (response.status().equals(HttpResponseStatus.UNAUTHORIZED)) { this.promise .setFailure(new EtcdAuthenticationException(response.content().toString(CharsetUtil.UTF_8))); } else { if (!response.content().isReadable()) { // If connection was accepted maybe response has to be waited for if (response.status().equals(HttpResponseStatus.OK) || response.status().equals(HttpResponseStatus.ACCEPTED) || response.status().equals(HttpResponseStatus.CREATED)) { this.client.connect(this.request); return; } this.promise .setFailure(new IOException("Content was not readable. HTTP Status: " + response.status())); } try { this.promise .setSuccess(request.getResponseDecoder().decode(response.headers(), response.content())); } // Catches both parsed EtcdExceptions and parsing exceptions catch (Exception e) { this.promise.setFailure(e); } } }
From source file:org.apache.flink.runtime.webmonitor.handlers.HandlerRedirectUtils.java
License:Apache License
public static HttpResponse getRedirectResponse(String redirectAddress, String path) throws Exception { checkNotNull(redirectAddress, "Redirect address"); checkNotNull(path, "Path"); String newLocation = String.format("http://%s%s", redirectAddress, path); HttpResponse redirectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT); redirectResponse.headers().set(HttpHeaders.Names.LOCATION, newLocation); redirectResponse.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8"); redirectResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); return redirectResponse; }
From source file:org.apache.flink.runtime.webmonitor.WebRuntimeMonitorITCase.java
License:Apache License
/** * Tests that the monitor associated with the following job manager redirects to the leader. *//*from ww w .j a v a 2 s . com*/ @Test public void testRedirectToLeader() throws Exception { final Deadline deadline = TestTimeout.fromNow(); ActorSystem[] jobManagerSystem = new ActorSystem[2]; WebRuntimeMonitor[] webMonitor = new WebRuntimeMonitor[2]; List<LeaderRetrievalService> leaderRetrievalServices = new ArrayList<>(); try (TestingServer zooKeeper = new TestingServer()) { final Configuration config = ZooKeeperTestUtils.createZooKeeperRecoveryModeConfig( zooKeeper.getConnectString(), temporaryFolder.getRoot().getPath()); File logDir = temporaryFolder.newFolder(); Path logFile = Files.createFile(new File(logDir, "jobmanager.log").toPath()); Files.createFile(new File(logDir, "jobmanager.out").toPath()); config.setInteger(ConfigConstants.JOB_MANAGER_WEB_PORT_KEY, 0); config.setString(ConfigConstants.JOB_MANAGER_WEB_LOG_PATH_KEY, logFile.toString()); for (int i = 0; i < jobManagerSystem.length; i++) { jobManagerSystem[i] = AkkaUtils.createActorSystem(new Configuration(), new Some<>(new Tuple2<String, Object>("localhost", 0))); } for (int i = 0; i < webMonitor.length; i++) { LeaderRetrievalService lrs = ZooKeeperUtils.createLeaderRetrievalService(config); leaderRetrievalServices.add(lrs); webMonitor[i] = new WebRuntimeMonitor(config, lrs, jobManagerSystem[i]); } ActorRef[] jobManager = new ActorRef[2]; String[] jobManagerAddress = new String[2]; for (int i = 0; i < jobManager.length; i++) { Configuration jmConfig = config.clone(); jmConfig.setInteger(ConfigConstants.JOB_MANAGER_WEB_PORT_KEY, webMonitor[i].getServerPort()); jobManager[i] = JobManager.startJobManagerActors(jmConfig, jobManagerSystem[i], JobManager.class, MemoryArchivist.class)._1(); jobManagerAddress[i] = AkkaUtils.getAkkaURL(jobManagerSystem[i], jobManager[i]); webMonitor[i].start(jobManagerAddress[i]); } LeaderRetrievalService lrs = ZooKeeperUtils.createLeaderRetrievalService(config); leaderRetrievalServices.add(lrs); TestingListener leaderListener = new TestingListener(); lrs.start(leaderListener); leaderListener.waitForNewLeader(deadline.timeLeft().toMillis()); String leaderAddress = leaderListener.getAddress(); int leaderIndex = leaderAddress.equals(jobManagerAddress[0]) ? 0 : 1; int followerIndex = (leaderIndex + 1) % 2; ActorSystem leadingSystem = jobManagerSystem[leaderIndex]; ActorSystem followerSystem = jobManagerSystem[followerIndex]; WebMonitor leadingWebMonitor = webMonitor[leaderIndex]; WebMonitor followerWebMonitor = webMonitor[followerIndex]; // For test stability reason we have to wait until we are sure that both leader // listeners have been notified. JobManagerRetriever leadingRetriever = Whitebox.getInternalState(leadingWebMonitor, "retriever"); JobManagerRetriever followerRetriever = Whitebox.getInternalState(followerWebMonitor, "retriever"); // Wait for the initial notifications waitForLeaderNotification(leadingSystem, jobManager[leaderIndex], leadingRetriever, deadline); waitForLeaderNotification(leadingSystem, jobManager[leaderIndex], followerRetriever, deadline); try (HttpTestClient leaderClient = new HttpTestClient("localhost", leadingWebMonitor.getServerPort()); HttpTestClient followingClient = new HttpTestClient("localhost", followerWebMonitor.getServerPort())) { String expected = new Scanner(new File(MAIN_RESOURCES_PATH + "/index.html")).useDelimiter("\\A") .next(); // Request the file from the leaading web server leaderClient.sendGetRequest("index.html", deadline.timeLeft()); HttpTestClient.SimpleHttpResponse response = leaderClient.getNextResponse(deadline.timeLeft()); assertEquals(HttpResponseStatus.OK, response.getStatus()); assertEquals(response.getType(), MimeTypes.getMimeTypeForExtension("html")); assertEquals(expected, response.getContent()); // Request the file from the following web server followingClient.sendGetRequest("index.html", deadline.timeLeft()); response = followingClient.getNextResponse(deadline.timeLeft()); assertEquals(HttpResponseStatus.TEMPORARY_REDIRECT, response.getStatus()); assertTrue(response.getLocation().contains("" + leadingWebMonitor.getServerPort())); // Kill the leader leadingSystem.shutdown(); // Wait for the notification of the follower waitForLeaderNotification(followerSystem, jobManager[followerIndex], followerRetriever, deadline); // Same request to the new leader followingClient.sendGetRequest("index.html", deadline.timeLeft()); response = followingClient.getNextResponse(deadline.timeLeft()); assertEquals(HttpResponseStatus.OK, response.getStatus()); assertEquals(response.getType(), MimeTypes.getMimeTypeForExtension("html")); assertEquals(expected, response.getContent()); // Simple overview request followingClient.sendGetRequest("/overview", deadline.timeLeft()); response = followingClient.getNextResponse(deadline.timeLeft()); assertEquals(HttpResponseStatus.OK, response.getStatus()); assertEquals(response.getType(), MimeTypes.getMimeTypeForExtension("json")); assertTrue(response.getContent().contains("\"taskmanagers\":1") || response.getContent().contains("\"taskmanagers\":0")); } } finally { for (ActorSystem system : jobManagerSystem) { if (system != null) { system.shutdown(); } } for (WebMonitor monitor : webMonitor) { monitor.stop(); } for (LeaderRetrievalService lrs : leaderRetrievalServices) { lrs.stop(); } } }
From source file:org.nosceon.titanite.Response.java
License:Apache License
public static Response temporaryRedirect(String location) { return new Response(HttpResponseStatus.TEMPORARY_REDIRECT).location(location); }
From source file:org.nosceon.titanite.Response.java
License:Apache License
public static Response temporaryRedirect(URI location) { return new Response(HttpResponseStatus.TEMPORARY_REDIRECT).location(location); }