use of io.appium.espressoserver.lib.handlers.RequestHandler in project appium-espresso-driver by appium.
the class Router method route.
@SuppressWarnings("unchecked")
public BaseResponse route(IHTTPSession session) {
String uri = session.getUri();
Method method = session.getMethod();
// Look for a route that matches this URL
RouteDefinition matchingRoute = routeMap.findMatchingRoute(method, uri);
// If no route found, return a 404 Error Response
if (matchingRoute == null) {
return new ErrorResponse(NanoHTTPD.Response.Status.NOT_FOUND, String.format("No such route %s", uri));
}
// Get the handler, parameter class and URI parameters
RequestHandler handler = matchingRoute.getHandler();
Class<? extends AppiumParams> paramClass = matchingRoute.getParamClass();
Map<String, String> uriParams = matchingRoute.getUriParams(uri);
// Parse the appium params
String postJson;
try {
postJson = parseBody(session);
} catch (IOException e) {
return new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, e.getMessage());
} catch (NanoHTTPD.ResponseException e) {
return new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, e.getMessage());
}
AppiumParams appiumParams;
if (postJson == null) {
appiumParams = new AppiumParams();
} else {
appiumParams = paramClass.cast((new Gson()).fromJson(postJson, paramClass));
}
appiumParams.setSessionId(uriParams.get("sessionId"));
appiumParams.setElementId(uriParams.get("elementId"));
// Validate the sessionId
if (appiumParams.getSessionId() != null && !appiumParams.getSessionId().equals(Session.getGlobalSession().getId())) {
return new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, "Invalid session ID " + appiumParams.getSessionId());
}
// Create the result
try {
Object handlerResult = handler.handle(appiumParams);
String sessionId = appiumParams.getSessionId();
// If it's a new session, pull out the newly created Session ID
if (handlerResult != null && handlerResult.getClass() == Session.class) {
sessionId = ((Session) handlerResult).getId();
}
AppiumResponse appiumResponse = new AppiumResponse<>(AppiumStatus.SUCCESS, handlerResult, sessionId);
System.out.println("Finished processing " + method + " request for '" + uri + "'");
return appiumResponse;
} catch (NoSuchElementException e) {
return new AppiumResponse<>(AppiumStatus.NO_SUCH_ELEMENT, e.getMessage());
} catch (SessionNotCreatedException e) {
return new AppiumResponse<>(AppiumStatus.SESSION_NOT_CREATED_EXCEPTION, e.getMessage());
} catch (InvalidStrategyException e) {
return new AppiumResponse<>(AppiumStatus.INVALID_SELECTOR, e.getMessage());
} catch (MissingCommandsException e) {
return new ErrorResponse(NanoHTTPD.Response.Status.NOT_FOUND, e.getMessage());
} catch (NotYetImplementedException e) {
return new ErrorResponse(NanoHTTPD.Response.Status.NOT_IMPLEMENTED, e.getMessage());
} catch (AppiumException e) {
return new AppiumResponse<>(AppiumStatus.UNKNOWN_ERROR, e.getMessage());
}
}
Aggregations