public ServerResponse invoke(HttpRequest request, HttpResponse response, Object target) { request.setAttribute(ResourceMethod.class.getName(), this); incrementMethodCount(request.getHttpMethod()); UriInfoImpl uriInfo = (UriInfoImpl) request.getUri(); uriInfo.pushCurrentResource(target); try { ServerResponse jaxrsResponse = invokeOnTarget(request, response, target); if (jaxrsResponse != null && jaxrsResponse.getEntity() != null) { // if the content type isn't set, then set it to be either most desired type from the Accept // header // or the first media type in the @Produces annotation // See RESTEASY-144 Object type = jaxrsResponse.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE); if (type == null) jaxrsResponse .getMetadata() .putSingle( HttpHeaderNames.CONTENT_TYPE, resolveContentType(request, jaxrsResponse.getEntity())); } return jaxrsResponse; } finally { uriInfo.popCurrentResource(); } }
/** * Converts a generic {@link HttpEntity} object into a {@link ServerResponse} object by reading * the content supplied in the raw server response, and creating a {@link JSONObject} that * contains the same data. This data is then attached as the post data of the {@link * ServerResponse} object returned. * * @param entity A generic {@link HttpEntity} returned as a result of a HTTP response. * @param statusCode An {@link Integer} value containing the HTTP response code. * @param tag A {@link String} value containing the tag value to be applied to the resultant * {@link ServerResponse} object. * @param log A {@link Boolean} value indicating whether or not to log the raw content lines via * the debug interface. * @param linkData A {@link BranchLinkData} object containing the data dictionary associated with * the link subject of the original server request. * @return A {@link ServerResponse} object representing the {@link HttpEntity} response in Branch * SDK terms. * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP/1.1: Status * Codes</a> */ private ServerResponse processEntityForJSON( HttpEntity entity, int statusCode, String tag, boolean log, BranchLinkData linkData) { ServerResponse result = new ServerResponse(tag, statusCode, linkData); try { if (entity != null) { InputStream instream = entity.getContent(); BufferedReader rd = new BufferedReader(new InputStreamReader(instream)); String line = rd.readLine(); if (log) PrefHelper.Debug("BranchSDK", "returned " + line); if (line != null) { try { JSONObject jsonObj = new JSONObject(line); result.setPost(jsonObj); } catch (JSONException ex) { try { JSONArray jsonArray = new JSONArray(line); result.setPost(jsonArray); } catch (JSONException ex2) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "JSON exception: " + ex2.getMessage()); } } } } } catch (IOException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage()); } return result; }
protected ServerResponse prepareResponse(ServerResponse serverResponse) { serverResponse.setAnnotations(method.getAnnotations()); serverResponse.setWriterInterceptors(writerInterceptors); serverResponse.setResponseFilters(responseFilters); serverResponse.setResourceMethod(method); serverResponse.setResourceClass(resourceClass); return serverResponse; }
protected ServerResponse invokeOnTarget( HttpRequest request, HttpResponse response, Object target) { if (validator != null) { violationsContainer = new ViolationsContainer<Object>(validator.validate(target)); request.setAttribute(ViolationsContainer.class.getName(), violationsContainer); request.setAttribute(GeneralValidator.class.getName(), validator); } PostMatchContainerRequestContext requestContext = new PostMatchContainerRequestContext(request, this); for (ContainerRequestFilter filter : requestFilters) { try { filter.filter(requestContext); } catch (IOException e) { throw new RuntimeException(e); } ServerResponse serverResponse = (ServerResponse) requestContext.getResponseAbortedWith(); if (serverResponse != null) { return prepareResponse(serverResponse); } } Object rtn = null; try { rtn = methodInjector.invoke(request, response, target); } catch (WebApplicationException wae) { prepareResponse(ServerResponse.convertToServerResponse(wae.getResponse())); throw wae; } if (violationsContainer != null && violationsContainer.size() > 0) { throw new ResteasyViolationExceptionExtension(violationsContainer); } if (request.isSuspended()) { AbstractAsynchronousResponse asyncResponse = (AbstractAsynchronousResponse) request.getAsynchronousResponse(); if (asyncResponse == null) return null; asyncResponse.setAnnotations(method.getAnnotations()); asyncResponse.setWriterInterceptors(writerInterceptors); asyncResponse.setResponseFilters(responseFilters); return null; } if (rtn == null || method.getReturnType().equals(void.class)) { return prepareResponse((ServerResponse) Response.noContent().build()); } if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) { return prepareResponse(ServerResponse.convertToServerResponse((Response) rtn)); } Response.ResponseBuilder builder = Response.ok(rtn); builder.type(resolveContentType(request, rtn)); ServerResponse jaxrsResponse = (ServerResponse) builder.build(); jaxrsResponse.setGenericType(genericReturnType); return prepareResponse(jaxrsResponse); }
/** * Convert the given {@linkplain RouterFunction routing function} into a {@link HttpHandler}, * using the given strategies. * * <p>The returned {@code HttpHandler} can be adapted to run in * * <ul> * <li>Servlet 3.1+ using the {@link * org.springframework.http.server.reactive.ServletHttpHandlerAdapter}, * <li>Reactor using the {@link * org.springframework.http.server.reactive.ReactorHttpHandlerAdapter}, * <li>RxNetty using the {@link * org.springframework.http.server.reactive.RxNettyHttpHandlerAdapter}, or * <li>Undertow using the {@link * org.springframework.http.server.reactive.UndertowHttpHandlerAdapter}. * </ul> * * @param routerFunction the routing function to convert * @param strategies the strategies to use * @return an http handler that handles HTTP request using the given routing function */ public static HttpHandler toHttpHandler( RouterFunction<?> routerFunction, HandlerStrategies strategies) { Assert.notNull(routerFunction, "RouterFunction must not be null"); Assert.notNull(strategies, "HandlerStrategies must not be null"); return new HttpWebHandlerAdapter( exchange -> { ServerRequest request = new DefaultServerRequest(exchange, strategies); addAttributes(exchange, request); HandlerFunction<?> handlerFunction = routerFunction.route(request).orElse(notFound()); ServerResponse<?> response = handlerFunction.handle(request); return response.writeTo(exchange, strategies); }); }
@Override public void onRequestSucceeded(ServerResponse resp, Branch branch) { try { prefHelper_.setDeviceFingerPrintID( resp.getObject().getString(Defines.Jsonkey.DeviceFingerprintID.getKey())); prefHelper_.setUserURL(resp.getObject().getString(Defines.Jsonkey.Link.getKey())); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (resp.getObject().has(Defines.Jsonkey.Data.getKey())) { JSONObject dataObj = new JSONObject(resp.getObject().getString(Defines.Jsonkey.Data.getKey())); // If Clicked on a branch link if (dataObj.has(Defines.Jsonkey.Clicked_Branch_Link.getKey()) && dataObj.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) { // Check if there is any install params. Install param will be empty on until click a // branch link // or When a user logout if (prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) { // if clicked on link then check for is Referrable state if (prefHelper_.getIsReferrable() == 1) { String params = resp.getObject().getString(Defines.Jsonkey.Data.getKey()); prefHelper_.setInstallParams(params); } } } } if (resp.getObject().has(Defines.Jsonkey.LinkClickID.getKey())) { prefHelper_.setLinkClickID( resp.getObject().getString(Defines.Jsonkey.LinkClickID.getKey())); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (resp.getObject().has(Defines.Jsonkey.Data.getKey())) { String params = resp.getObject().getString(Defines.Jsonkey.Data.getKey()); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } if (callback_ != null) { callback_.onInitFinished(branch.getLatestReferringParams(), null); } } catch (Exception ex) { ex.printStackTrace(); } }
protected void writeJaxrsResponse( HttpRequest request, HttpResponse response, Response jaxrsResponse) throws WriterException { ServerResponse serverResponse = (ServerResponse) jaxrsResponse; Object type = jaxrsResponse.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE); if (type == null && jaxrsResponse.getEntity() != null) { ResourceMethod method = (ResourceMethod) request.getAttribute(ResourceMethod.class.getName()); if (method != null) { jaxrsResponse .getMetadata() .putSingle( HttpHeaderNames.CONTENT_TYPE, method.resolveContentType(request, jaxrsResponse.getEntity())); } else { MediaType contentType = resolveContentTypeByAccept( request.getHttpHeaders().getAcceptableMediaTypes(), jaxrsResponse.getEntity()); jaxrsResponse.getMetadata().putSingle(HttpHeaderNames.CONTENT_TYPE, contentType); } } serverResponse.writeTo(request, response, providerFactory); }
/** * Handles login queries and saves informations received from the server in the application's * private data * * @return {@link ServerResponse} */ public ServerResponse login() { ServerResponse res; JSONObject jObject = null; /** Server request */ String request = mHost + logQuery + mID + "/"; String signature = md5("login" + mID + mCode); res = get(request + signature + "/"); jObject = (JSONObject) res.getRespone(); if (jObject == null) return res; /** Parse response */ ArrayList<Map<String, String>> courses = new ArrayList<Map<String, String>>(); try { SharedPreferences.Editor editor = mPreferences.edit(); JSONArray jsonCourses = jObject.getJSONArray("courses"); for (int i = 0; i < jsonCourses.length(); i++) { Map<String, String> course = new HashMap<String, String>(); course.put("id", jsonCourses.getJSONObject(i).getString("id")); course.put("name", jsonCourses.getJSONObject(i).getString("abbr")); courses.add(course); } if (!courses.isEmpty()) { editor.putString("course", courses.get(0).get("name")); editor.putString("courseId", courses.get(0).get("id")); } editor.commit(); } catch (JSONException e) { e.printStackTrace(); return new ServerResponse(null, sInvalidResponse); } /** Successful login */ return new ServerResponse(courses, null); }
/** * The main RESTful POST method. The others call this one with pre-populated parameters. * * @param body A {@link JSONObject} containing the main data body/payload of the request. * @param url A {@link String} URL to request from. * @param tag A {@link String} tag for logging/analytics purposes. * @param timeout An {@link Integer} value containing the number of milliseconds to wait before * considering a server request to have timed out. * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for * this request or not. * @param linkData A {@link BranchLinkData} object containing the data dictionary associated with * the link subject of the original server request. * @return A {@link ServerResponse} object representing the {@link HttpEntity} response in Branch * SDK terms. */ private ServerResponse make_restful_post( JSONObject body, String url, String tag, int timeout, int retryNumber, boolean log, BranchLinkData linkData) { try { JSONObject bodyCopy = new JSONObject(); Iterator<?> keys = body.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { bodyCopy.put(key, body.get(key)); } catch (JSONException e) { e.printStackTrace(); } } if (!addCommonParams(bodyCopy, retryNumber)) { return new ServerResponse(tag, NO_BRANCH_KEY_STATUS); } if (log) { PrefHelper.Debug("BranchSDK", "posting to " + url); PrefHelper.Debug("BranchSDK", "Post value = " + bodyCopy.toString(4)); } HttpPost request = new HttpPost(url); request.setEntity(new ByteArrayEntity(bodyCopy.toString().getBytes("UTF8"))); request.setHeader("Content-type", "application/json"); HttpResponse response = getGenericHttpClient(timeout).execute(request); if (response.getStatusLine().getStatusCode() >= 500 && retryNumber < prefHelper_.getRetryCount()) { try { Thread.sleep(prefHelper_.getRetryInterval()); } catch (InterruptedException e) { e.printStackTrace(); } retryNumber++; return make_restful_post(bodyCopy, url, tag, timeout, retryNumber, log, linkData); } else { ServerResponse serverResponse = processEntityForJSON( response.getEntity(), response.getStatusLine().getStatusCode(), tag, log, linkData); serverResponse.setRequestObject(body); return serverResponse; } } catch (SocketException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (UnknownHostException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (Exception ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Exception: " + ex.getMessage()); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { if (ex instanceof NetworkOnMainThreadException) Log.i( "BranchSDK", "Branch Error: Don't call our synchronous methods on the main thread!!!"); } return new ServerResponse(tag, 500); } }
/** * <strong>Central entry point to Spring's functional web framework.</strong> Exposes routing * functionality, such as to {@linkplain #route(RequestPredicate, HandlerFunction) create} a {@code * RouterFunction} given a {@code RequestPredicate} and {@code HandlerFunction}, and to do further * {@linkplain #subroute(RequestPredicate, RouterFunction) subrouting} on an existing routing * function. * * <p>Additionally, this class can {@linkplain #toHttpHandler(RouterFunction) transform} a {@code * RouterFunction} into an {@code HttpHandler}, which can be run in Servlet 3.1+, Reactor, RxNetty, * or Undertow. And it can {@linkplain #toHandlerMapping(RouterFunction, HandlerStrategies) * transform} a {@code RouterFunction} into an {@code HandlerMapping}, which can be run in a {@code * DispatcherHandler}. * * @author Arjen Poutsma * @since 5.0 */ public abstract class RouterFunctions { /** Name of the {@link ServerWebExchange} attribute that contains the {@link ServerRequest}. */ public static final String REQUEST_ATTRIBUTE = RouterFunctions.class.getName() + ".request"; /** * Name of the {@link ServerWebExchange} attribute that contains the URI templates map, mapping * variable names to values. */ public static final String URI_TEMPLATE_VARIABLES_ATTRIBUTE = RouterFunctions.class.getName() + ".uriTemplateVariables"; private static final HandlerFunction<Void> NOT_FOUND_HANDLER = request -> ServerResponse.notFound().build(); /** * Route to the given handler function if the given request predicate applies. * * @param predicate the predicate to test * @param handlerFunction the handler function to route to * @param <T> the type of the handler function * @return a routing function that routes to {@code handlerFunction} if {@code predicate} * evaluates to {@code true} * @see RequestPredicates */ public static <T> RouterFunction<T> route( RequestPredicate predicate, HandlerFunction<T> handlerFunction) { Assert.notNull(predicate, "'predicate' must not be null"); Assert.notNull(handlerFunction, "'handlerFunction' must not be null"); return request -> predicate.test(request) ? Optional.of(handlerFunction) : Optional.empty(); } /** * Route to the given routing function if the given request predicate applies. * * @param predicate the predicate to test * @param routerFunction the routing function to route to * @param <T> the type of the handler function * @return a routing function that routes to {@code routerFunction} if {@code predicate} evaluates * to {@code true} * @see RequestPredicates */ public static <T> RouterFunction<T> subroute( RequestPredicate predicate, RouterFunction<T> routerFunction) { Assert.notNull(predicate, "'predicate' must not be null"); Assert.notNull(routerFunction, "'routerFunction' must not be null"); return request -> { if (predicate.test(request)) { ServerRequest subRequest = predicate.subRequest(request); return routerFunction.route(subRequest); } else { return Optional.empty(); } }; } /** * Convert the given {@linkplain RouterFunction routing function} into a {@link HttpHandler}. This * conversion uses {@linkplain HandlerStrategies#builder() default strategies}. * * <p>The returned {@code HttpHandler} can be adapted to run in * * <ul> * <li>Servlet 3.1+ using the {@link * org.springframework.http.server.reactive.ServletHttpHandlerAdapter}, * <li>Reactor using the {@link * org.springframework.http.server.reactive.ReactorHttpHandlerAdapter}, * <li>RxNetty using the {@link * org.springframework.http.server.reactive.RxNettyHttpHandlerAdapter}, or * <li>Undertow using the {@link * org.springframework.http.server.reactive.UndertowHttpHandlerAdapter}. * </ul> * * @param routerFunction the routing function to convert * @return an http handler that handles HTTP request using the given routing function */ public static HttpHandler toHttpHandler(RouterFunction<?> routerFunction) { return toHttpHandler(routerFunction, HandlerStrategies.withDefaults()); } /** * Convert the given {@linkplain RouterFunction routing function} into a {@link HttpHandler}, * using the given strategies. * * <p>The returned {@code HttpHandler} can be adapted to run in * * <ul> * <li>Servlet 3.1+ using the {@link * org.springframework.http.server.reactive.ServletHttpHandlerAdapter}, * <li>Reactor using the {@link * org.springframework.http.server.reactive.ReactorHttpHandlerAdapter}, * <li>RxNetty using the {@link * org.springframework.http.server.reactive.RxNettyHttpHandlerAdapter}, or * <li>Undertow using the {@link * org.springframework.http.server.reactive.UndertowHttpHandlerAdapter}. * </ul> * * @param routerFunction the routing function to convert * @param strategies the strategies to use * @return an http handler that handles HTTP request using the given routing function */ public static HttpHandler toHttpHandler( RouterFunction<?> routerFunction, HandlerStrategies strategies) { Assert.notNull(routerFunction, "RouterFunction must not be null"); Assert.notNull(strategies, "HandlerStrategies must not be null"); return new HttpWebHandlerAdapter( exchange -> { ServerRequest request = new DefaultServerRequest(exchange, strategies); addAttributes(exchange, request); HandlerFunction<?> handlerFunction = routerFunction.route(request).orElse(notFound()); ServerResponse<?> response = handlerFunction.handle(request); return response.writeTo(exchange, strategies); }); } /** * Convert the given {@code RouterFunction} into a {@code HandlerMapping}. This conversion uses * {@linkplain HandlerStrategies#builder() default strategies}. * * <p>The returned {@code HandlerMapping} can be run in a {@link * org.springframework.web.reactive.DispatcherHandler}. * * @param routerFunction the routing function to convert * @return an handler mapping that maps HTTP request to a handler using the given routing function * @see org.springframework.web.reactive.function.support.HandlerFunctionAdapter * @see org.springframework.web.reactive.function.support.ServerResponseResultHandler */ public static HandlerMapping toHandlerMapping(RouterFunction<?> routerFunction) { return toHandlerMapping(routerFunction, HandlerStrategies.withDefaults()); } /** * Convert the given {@linkplain RouterFunction routing function} into a {@link HandlerMapping}, * using the given strategies. * * <p>The returned {@code HandlerMapping} can be run in a {@link * org.springframework.web.reactive.DispatcherHandler}. * * @param routerFunction the routing function to convert * @param strategies the strategies to use * @return an handler mapping that maps HTTP request to a handler using the given routing function * @see org.springframework.web.reactive.function.support.HandlerFunctionAdapter * @see org.springframework.web.reactive.function.support.ServerResponseResultHandler */ public static HandlerMapping toHandlerMapping( RouterFunction<?> routerFunction, HandlerStrategies strategies) { Assert.notNull(routerFunction, "RouterFunction must not be null"); Assert.notNull(strategies, "HandlerStrategies must not be null"); return exchange -> { ServerRequest request = new DefaultServerRequest(exchange, strategies); addAttributes(exchange, request); Optional<? extends HandlerFunction<?>> route = routerFunction.route(request); return Mono.justOrEmpty(route); }; } private static void addAttributes(ServerWebExchange exchange, ServerRequest request) { Map<String, Object> attributes = exchange.getAttributes(); attributes.put(REQUEST_ATTRIBUTE, request); } @SuppressWarnings("unchecked") private static <T> HandlerFunction<T> notFound() { return (HandlerFunction<T>) NOT_FOUND_HANDLER; } @SuppressWarnings("unchecked") static <T> HandlerFunction<T> cast(HandlerFunction<?> handlerFunction) { return (HandlerFunction<T>) handlerFunction; } }