use of com.pratilipi.api.shared.GenericRequest in project pratilipi by Pratilipi.
the class GenericApi method executeApi.
final Object executeApi(GenericApi api, Method apiMethod, JsonObject requestPayloadJson, Class<? extends GenericRequest> apiMethodParameterType, HttpServletRequest request) {
try {
GenericRequest apiRequest = new Gson().fromJson(requestPayloadJson, apiMethodParameterType);
if (apiRequest instanceof GenericFileUploadRequest) {
GenericFileUploadRequest gfuRequest = (GenericFileUploadRequest) apiRequest;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream fileItemStream = iterator.next();
if (!fileItemStream.isFormField()) {
gfuRequest.setName(fileItemStream.getName());
gfuRequest.setData(IOUtils.toByteArray(fileItemStream.openStream()));
gfuRequest.setMimeType(fileItemStream.getContentType());
break;
}
}
} catch (IOException | FileUploadException e) {
throw new UnexpectedServerException();
}
}
JsonObject errorMessages = apiRequest.validate();
if (errorMessages.entrySet().size() > 0)
return new InvalidArgumentException(errorMessages);
else
return apiMethod.invoke(api, apiRequest);
} catch (JsonSyntaxException e) {
logger.log(Level.SEVERE, "Invalid JSON in request body.", e);
return new InvalidArgumentException("Invalid JSON in request body.");
} catch (UnexpectedServerException e) {
return e;
} catch (InvocationTargetException e) {
Throwable te = e.getTargetException();
if (te instanceof InvalidArgumentException || te instanceof InsufficientAccessException || te instanceof UnexpectedServerException) {
return te;
} else {
logger.log(Level.SEVERE, "Failed to execute API.", te);
return new UnexpectedServerException();
}
} catch (IllegalAccessException | IllegalArgumentException e) {
logger.log(Level.SEVERE, "Failed to execute API.", e);
return new UnexpectedServerException();
}
}
use of com.pratilipi.api.shared.GenericRequest in project pratilipi by Pratilipi.
the class GenericApi method init.
@SuppressWarnings("unchecked")
@Override
public void init() throws ServletException {
for (Method method : this.getClass().getMethods()) {
if (getMethod == null && method.getAnnotation(Get.class) != null) {
getMethod = method;
getMethodParameterType = (Class<? extends GenericRequest>) method.getParameterTypes()[0];
for (Field field : getMethodParameterType.getDeclaredFields()) if (field.getAnnotation(Sensitive.class) != null)
getRequestSensitiveFieldList.add(field.getName());
} else if (postMethod == null && method.getAnnotation(Post.class) != null) {
postMethod = method;
postMethodParameterType = (Class<? extends GenericRequest>) method.getParameterTypes()[0];
for (Field field : postMethodParameterType.getDeclaredFields()) if (field.getAnnotation(Sensitive.class) != null)
postRequestSensitiveFieldList.add(field.getName());
}
}
}
Aggregations