public static NanoHTTPD.IHTTPSession createHttpSession(NanoHTTPD.Method method, @Nullable Map<String, String> params) { NanoHTTPD.IHTTPSession res = mock(NanoHTTPD.IHTTPSession.class); when(res.getMethod()).thenReturn(method); if (params != null) { when(res.getParms()).thenReturn(params); } return res; } }
@Override public Response serve(IHTTPSession session) { if (!allowedMethods.contains(session.getMethod())) { return methodNotAllowed(); } HttpHandler httpHandler = routes.get(session.getUri()); if (httpHandler != null) { return httpHandler.process(); } else { return notFound(); } }
Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) try { session.parseBody(content);
@Override public Response serve(IHTTPSession session) { BaseResponse response; final Map<String, String> files = new LinkedHashMap<>(); try { session.parseBody(files); response = router.route(session.getUri(), session.getMethod(), files); } catch (RuntimeException | IOException | ResponseException e) { response = new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, Log.getStackTraceString(e)); } if (response instanceof AppiumResponse) { AppiumResponse appiumResponse = (AppiumResponse) response; if (appiumResponse.getStatus() == AppiumStatus.SUCCESS) { logger.info(String.format("Responding to server with value: %s", abbreviate(String.valueOf(appiumResponse.getValue()), 300))); } else { logger.info(String.format("Responding to server with error: %s", appiumResponse.getValue())); } } try { return buildFixedLengthResponse(response); } catch (RuntimeException e) { return buildFixedLengthResponse( new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, Log.getStackTraceString(e))); } }
@Override public Response serve(IHTTPSession session) { OrchidRoute matchingRoute = null; String route = "/" + OrchidUtils.normalizePath(session.getUri()); switch(session.getMethod()) { case GET: matchingRoute = findRoute(route, getRoutes); break; case POST: matchingRoute = findRoute(route, postRoutes); break; case PUT: matchingRoute = findRoute(route, putRoutes); break; case DELETE: matchingRoute = findRoute(route, deleteRoutes); break; } if(matchingRoute != null) { return matchingRoute.call(new OrchidRequest(session, matchingRoute)).getResponse(); } else { return fileController.findFile(OrchidUtils.normalizePath(route)); } } }
@Override public Response serve(IHTTPSession session) { try { session.parseBody(new HashMap<String, String>()); Map<String, String> params = session.getParms(); String urlRequested = session.getUri(); String action = params.get("action"); log.debug(session.getMethod().name()+": "+urlRequested+" : "+action); if (action.equals("getInfo")) { return getInfo(); } else if (action.equals("addUser")) { return addUser(params.get("userName"), params.get("blob"), params.get("clientKey")); } return new Response(Response.Status.NOT_FOUND, "", ""); }catch(Exception ex) { return new Response(Response.Status.INTERNAL_ERROR, "text/html", ex.getMessage()); } }
private Response respond(IHTTPSession session, String responseString) { // First let's handle CORS OPTION query Response response; if (Method.OPTIONS.equals(session.getMethod())) { response = new NanoHTTPD.Response(Response.Status.OK, MIME_PLAINTEXT, null, 0); } else { response = newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, responseString); } response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type"); response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS"); response.addHeader("Access-Control-Max-Age", "" + (42 * 60 * 60)); return response; }
@Override public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { if (session.getMethod() != NanoHTTPD.Method.POST) { return newFixedLengthResponse(METHOD_NOT_ALLOWED, MIME_PLAINTEXT, null); } String levelStr = session.getParms().get(PARAM_LEVEL); if (levelStr == null || levelStr.isEmpty()) { return newFixedLengthResponse(BAD_REQUEST, MIME_PLAINTEXT, format("Parameter '%s' is missing", PARAM_LEVEL)); } try { LoggerLevel level = LoggerLevel.valueOf(levelStr); logging.changeLevel(level); return newFixedLengthResponse(OK, MIME_PLAINTEXT, null); } catch (IllegalArgumentException e) { Loggers.get(ChangeLogLevelHttpAction.class).debug("Value '{}' for parameter '" + PARAM_LEVEL + "' is invalid: {}", levelStr, e); return newFixedLengthResponse(BAD_REQUEST, MIME_PLAINTEXT, format("Value '%s' for parameter '%s' is invalid", levelStr, PARAM_LEVEL)); } } }
private Response respond(IHTTPSession session) { Method method = session.getMethod(); String uri = session.getUri(); logger.debug("Serving {} {} request.", method, uri); if (Method.GET.equals(method) && "/version".equalsIgnoreCase(uri)) { return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, diagnosticsApi.getVersion()); } else if (Method.POST.equals(method) && "/reload".equalsIgnoreCase(uri)) { diagnosticsApi.reload(); return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, "Configuration reloaded\r\n"); } else { return newFixedLengthResponse(Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Requested URI " + uri + " not found\r\n"); } }
@Override public Response serve(IHTTPSession session) { Method method = session.getMethod(); String uri = session.getUri(); M3UServer.LOG.info(method + " '" + uri + "' "); if(session.getUri().contains("normal")) return new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, m3u8_normal); else if(session.getUri().contains("high")) return new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, m3u8_high); else if(session.getUri().contains("super")) return new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, m3u8_high); else return new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, ""); } }
@Override public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { if (session.getMethod() != NanoHTTPD.Method.GET) { return newFixedLengthResponse(METHOD_NOT_ALLOWED, MIME_PLAINTEXT, null); } ProtobufSystemInfo.SystemInfo.Builder infoBuilder = ProtobufSystemInfo.SystemInfo.newBuilder(); for (SystemInfoSection sectionProvider : sectionProviders) { ProtobufSystemInfo.Section section = sectionProvider.toProtobuf(); infoBuilder.addSections(section); } byte[] bytes = infoBuilder.build().toByteArray(); return newFixedLengthResponse(OK, PROTOBUF_MIME_TYPE, new ByteArrayInputStream(bytes), bytes.length); } }
private Response respond(Map<String, String> headers, IHTTPSession session, String uri) { // First let's handle CORS OPTION query Response r; if (cors != null && Method.OPTIONS.equals(session.getMethod())) { r = new NanoHTTPD.Response(Response.Status.OK, MIME_PLAINTEXT, null, 0); } else { r = defaultRespond(headers, session, uri); } if (cors != null) { r = addCORSHeaders(headers, r, cors); } return r; }
@Override public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { if (session.getMethod() != NanoHTTPD.Method.POST) { return newFixedLengthResponse(METHOD_NOT_ALLOWED, MIME_PLAINTEXT, null); } enabledCeWorkerController.refresh(); return newFixedLengthResponse(OK, MIME_PLAINTEXT, null); } }
boolean isError = false; String uri = session.getUri(); Method method = session.getMethod(); boolean isGet = Method.GET.equals(method); boolean isDelete = Method.DELETE.equals(method);
@Override public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { if (session.getMethod() != NanoHTTPD.Method.POST) { return newFixedLengthResponse(METHOD_NOT_ALLOWED, MIME_PLAINTEXT, null); } String levelStr = session.getParms().get(PARAM_LEVEL); if (levelStr == null || levelStr.isEmpty()) { return newFixedLengthResponse(BAD_REQUEST, MIME_PLAINTEXT, format("Parameter '%s' is missing", PARAM_LEVEL)); } try { LoggerLevel level = LoggerLevel.valueOf(levelStr); logging.changeLevel(level); return newFixedLengthResponse(OK, MIME_PLAINTEXT, null); } catch (IllegalArgumentException e) { Loggers.get(ChangeLogLevelHttpAction.class).debug("Value '{}' for parameter '" + PARAM_LEVEL + "' is invalid: {}", levelStr, e); return newFixedLengthResponse(BAD_REQUEST, MIME_PLAINTEXT, format("Value '%s' for parameter '%s' is invalid", levelStr, PARAM_LEVEL)); } } }
@Override public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { if (session.getMethod() != NanoHTTPD.Method.GET) { return newFixedLengthResponse(METHOD_NOT_ALLOWED, MIME_PLAINTEXT, null); } ProtobufSystemInfo.SystemInfo.Builder infoBuilder = ProtobufSystemInfo.SystemInfo.newBuilder(); for (SystemInfoSection sectionProvider : sectionProviders) { ProtobufSystemInfo.Section section = sectionProvider.toProtobuf(); infoBuilder.addSections(section); } byte[] bytes = infoBuilder.build().toByteArray(); return newFixedLengthResponse(OK, PROTOBUF_MIME_TYPE, new ByteArrayInputStream(bytes), bytes.length); } }
@Test public void shouldRouteToIsConnectedToServerV1Handler() throws Exception { when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET); when(session.getUri()).thenReturn("/health/v1/isConnectedToServer"); when(agentHealthHolder.hasLostContact()).thenReturn(false); NanoHTTPD.Response response = this.agentStatusHttpd.serve(session); assertThat(response.getStatus(), is(NanoHTTPD.Response.Status.OK)); assertThat(response.getMimeType(), is("text/plain; charset=utf-8")); assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8), is("OK!")); }
@Test public void shouldRouteToIsConnectedToServerHandler() throws Exception { when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET); when(session.getUri()).thenReturn("/health/latest/isConnectedToServer"); when(agentHealthHolder.hasLostContact()).thenReturn(false); NanoHTTPD.Response response = this.agentStatusHttpd.serve(session); assertThat(response.getStatus(), is(NanoHTTPD.Response.Status.OK)); assertThat(response.getMimeType(), is("text/plain; charset=utf-8")); assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8), is("OK!")); }
@Test public void shouldReturnNotFoundForBadUrl() throws Exception { when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET); when(session.getUri()).thenReturn("/foo"); NanoHTTPD.Response response = this.agentStatusHttpd.serve(session); assertThat(response.getStatus(), is(NanoHTTPD.Response.Status.NOT_FOUND)); assertThat(response.getMimeType(), is("text/plain; charset=utf-8")); assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8), is("The page you requested was not found")); }
@Test public void shouldReturnMethodNotAllowedOnNonGetNonHeadRequests() throws Exception { when(session.getMethod()).thenReturn(NanoHTTPD.Method.POST); NanoHTTPD.Response response = this.agentStatusHttpd.serve(session); assertThat(response.getStatus(), is(NanoHTTPD.Response.Status.METHOD_NOT_ALLOWED)); assertThat(response.getMimeType(), is("text/plain; charset=utf-8")); assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8), is("This method is not allowed. Please use GET or HEAD.")); }