Search in sources :

Example 1 with InvalidArgumentException

use of com.pratilipi.common.exception.InvalidArgumentException in project pratilipi by Pratilipi.

the class CommentDataUtil method _validateCommentDataForSave.

private static void _validateCommentDataForSave(CommentData commentData) throws InvalidArgumentException {
    boolean isNew = commentData.getId() == null;
    JsonObject errorMessages = new JsonObject();
    // New comment must have a user id.
    if (isNew && (commentData.getUserId() == null || commentData.getUserId() == 0L))
        errorMessages.addProperty("userId", GenericRequest.ERR_USER_ID_REQUIRED);
    // New comment must have a parent type.
    if (isNew && commentData.getParentType() == null)
        errorMessages.addProperty("parentType", GenericRequest.ERR_COMMENT_PARENT_TYPE_REQUIRED);
    // New comment must have a parent id.
    if (isNew && commentData.getParentId() == null)
        errorMessages.addProperty("parentId", GenericRequest.ERR_COMMENT_PARENT_ID_REQUIRED);
    // New comment must have content.
    if (isNew && commentData.getContent() == null)
        errorMessages.addProperty("content", GenericRequest.ERR_COMMENT_CONTENT_REQUIRED);
    else // Content can not be unset or set to null for old comment
    if (!isNew && commentData.hasContent() && commentData.getContent() == null)
        errorMessages.addProperty("content", GenericRequest.ERR_COMMENT_CONTENT_REQUIRED);
    if (errorMessages.entrySet().size() > 0)
        throw new InvalidArgumentException(errorMessages);
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) JsonObject(com.google.gson.JsonObject)

Example 2 with InvalidArgumentException

use of com.pratilipi.common.exception.InvalidArgumentException in project pratilipi by Pratilipi.

the class GenericApi method dispatchApiResponse.

final void dispatchApiResponse(Object apiResponse, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (apiResponse instanceof GenericFileDownloadResponse) {
        GenericFileDownloadResponse gfdResponse = (GenericFileDownloadResponse) apiResponse;
        String eTag = request.getHeader("If-None-Match");
        if (eTag == null)
            logger.log(Level.INFO, "No eTag found !");
        if (eTag != null && eTag.equals(gfdResponse.getETag())) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            response.setContentType(gfdResponse.getMimeType());
            response.setHeader("Cache-Control", "max-age=315360000");
            response.setHeader("ETag", gfdResponse.getETag());
            OutputStream out = response.getOutputStream();
            out.write(gfdResponse.getData());
            out.close();
        }
    } else if (apiResponse instanceof GenericResponse) {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        if (SystemProperty.STAGE.equals(SystemProperty.STAGE_GAMMA)) {
            //				response.setContentType( "application/json" );
            response.addHeader("Access-Control-Allow-Origin", getAccessControlAllowOrigin());
        }
        PrintWriter writer = response.getWriter();
        writer.println(new Gson().toJson(apiResponse));
        writer.close();
    } else if (apiResponse instanceof Throwable) {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        if (SystemProperty.STAGE.equals(SystemProperty.STAGE_GAMMA)) {
            //				response.setContentType( "application/json" );
            response.addHeader("Access-Control-Allow-Origin", getAccessControlAllowOrigin());
        }
        PrintWriter writer = response.getWriter();
        if (apiResponse instanceof InvalidArgumentException) {
            logger.log(Level.INFO, ((Throwable) apiResponse).getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else if (apiResponse instanceof InsufficientAccessException) {
            logger.log(Level.INFO, ((Throwable) apiResponse).getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (apiResponse instanceof UnexpectedServerException)
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        else
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        writer.println(((Throwable) apiResponse).getMessage());
        writer.close();
    }
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) GenericResponse(com.pratilipi.api.shared.GenericResponse) OutputStream(java.io.OutputStream) GenericFileDownloadResponse(com.pratilipi.api.shared.GenericFileDownloadResponse) Gson(com.google.gson.Gson) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) PrintWriter(java.io.PrintWriter)

Example 3 with InvalidArgumentException

use of com.pratilipi.common.exception.InvalidArgumentException 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();
    }
}
Also used : GenericFileUploadRequest(com.pratilipi.api.shared.GenericFileUploadRequest) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) JsonSyntaxException(com.google.gson.JsonSyntaxException) FileItemStream(org.apache.commons.fileupload.FileItemStream) GenericRequest(com.pratilipi.api.shared.GenericRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 4 with InvalidArgumentException

use of com.pratilipi.common.exception.InvalidArgumentException in project pratilipi by Pratilipi.

the class GenericBatchApi method dispatchApiResponse.

final void dispatchApiResponse(Map<String, Object> apiResps, HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    if (SystemProperty.STAGE.equals(SystemProperty.STAGE_GAMMA)) {
        //			response.setContentType( "application/json" );
        response.addHeader("Access-Control-Allow-Origin", super.getAccessControlAllowOrigin());
    }
    boolean bool = true;
    PrintWriter writer = response.getWriter();
    writer.print("{");
    for (Entry<String, Object> apiResp : apiResps.entrySet()) {
        if (bool)
            bool = false;
        else
            writer.print(",");
        writer.print("\"" + apiResp.getKey() + "\":{");
        if (apiResp.getValue() instanceof JsonElement) {
            writer.print("\"status\":" + HttpServletResponse.SC_OK + ",");
            writer.print("\"response\":" + apiResp.getValue());
        } else if (apiResp.getValue() instanceof InvalidArgumentException) {
            logger.log(Level.INFO, ((Throwable) apiResp.getValue()).getMessage());
            writer.print("\"status\":" + HttpServletResponse.SC_BAD_REQUEST + ",");
            writer.print("\"response\":" + ((Throwable) apiResp.getValue()).getMessage());
        } else if (apiResp.getValue() instanceof InsufficientAccessException) {
            logger.log(Level.INFO, ((Throwable) apiResp.getValue()).getMessage());
            writer.print("\"status\":" + HttpServletResponse.SC_UNAUTHORIZED + ",");
            writer.print("\"response\":" + ((Throwable) apiResp.getValue()).getMessage());
        } else if (apiResp.getValue() instanceof UnexpectedServerException) {
            writer.print("\"status\":" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ",");
            writer.print("\"response\":" + ((Throwable) apiResp.getValue()).getMessage());
        } else {
            writer.print("\"status\":" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ",");
            writer.print("\"response\":" + ((Throwable) apiResp.getValue()).getMessage());
        }
        writer.print("}");
    }
    writer.print("}");
    writer.close();
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) PrintWriter(java.io.PrintWriter)

Example 5 with InvalidArgumentException

use of com.pratilipi.common.exception.InvalidArgumentException in project pratilipi by Pratilipi.

the class PratilipiDataUtil method updatePratilipiContent.

public static int updatePratilipiContent(long pratilipiId, int pageNo, PratilipiContentType contentType, Object pageContent, boolean insertNew) throws InvalidArgumentException, InsufficientAccessException, UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    Pratilipi pratilipi = dataAccessor.getPratilipi(pratilipiId);
    if (!hasAccessToUpdatePratilipiContent(pratilipi))
        throw new InsufficientAccessException();
    AuditLog auditLog = dataAccessor.newAuditLog(AccessTokenFilter.getAccessToken(), AccessType.PRATILIPI_UPDATE, pratilipi);
    BlobAccessor blobAccessor = DataAccessorFactory.getBlobAccessor();
    if (contentType == PratilipiContentType.PRATILIPI) {
        BlobEntry blobEntry = blobAccessor.getBlob(CONTENT_FOLDER + "/" + pratilipiId);
        if (blobEntry == null) {
            blobEntry = blobAccessor.newBlob(CONTENT_FOLDER + "/" + pratilipiId);
            blobEntry.setData("&nbsp".getBytes(Charset.forName("UTF-8")));
            blobEntry.setMimeType("text/html");
        }
        String content = new String(blobEntry.getData(), Charset.forName("UTF-8"));
        PratilipiContentUtil pratilipiContentUtil = new PratilipiContentUtil(content);
        content = pratilipiContentUtil.updateContent(pageNo, (String) pageContent, insertNew);
        int pageCount = pratilipiContentUtil.getPageCount();
        if (content.isEmpty()) {
            content = "&nbsp";
            pageCount = 1;
        }
        blobEntry.setData(content.getBytes(Charset.forName("UTF-8")));
        blobAccessor.createOrUpdateBlob(blobEntry);
        pratilipi.setPageCount(pageCount);
        if (insertNew)
            auditLog.setEventComment("Added new page " + pageNo + " in Pratilpi content.");
        else if (!((String) pageContent).isEmpty())
            auditLog.setEventComment("Updated page " + pageNo + " in Pratilpi content.");
        else
            auditLog.setEventComment("Deleted page " + pageNo + " in Pratilpi content.");
    } else if (contentType == PratilipiContentType.IMAGE) {
        BlobEntry blobEntry = (BlobEntry) pageContent;
        blobEntry.setName(IMAGE_CONTENT_FOLDER + "/" + pratilipiId + "/" + pageNo);
        blobAccessor.createOrUpdateBlob(blobEntry);
        if (pageNo > (int) pratilipi.getPageCount())
            pratilipi.setPageCount(pageNo);
        auditLog.setEventComment("Uploaded page " + pageNo + " in Image content.");
    } else {
        throw new InvalidArgumentException(contentType + " content type is not yet supported.");
    }
    pratilipi.setLastUpdated(new Date());
    pratilipi = dataAccessor.createOrUpdatePratilipi(pratilipi, auditLog);
    return pratilipi.getPageCount();
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) DataAccessor(com.pratilipi.data.DataAccessor) BlobEntry(com.pratilipi.data.type.BlobEntry) PratilipiContentUtil(com.pratilipi.common.util.PratilipiContentUtil) BlobAccessor(com.pratilipi.data.BlobAccessor) UserPratilipi(com.pratilipi.data.type.UserPratilipi) Pratilipi(com.pratilipi.data.type.Pratilipi) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) AuditLog(com.pratilipi.data.type.AuditLog) Date(java.util.Date)

Aggregations

InvalidArgumentException (com.pratilipi.common.exception.InvalidArgumentException)37 JsonObject (com.google.gson.JsonObject)21 DataAccessor (com.pratilipi.data.DataAccessor)19 InsufficientAccessException (com.pratilipi.common.exception.InsufficientAccessException)11 UnexpectedServerException (com.pratilipi.common.exception.UnexpectedServerException)9 User (com.pratilipi.data.type.User)9 Gson (com.google.gson.Gson)7 GenericResponse (com.pratilipi.api.shared.GenericResponse)7 AuditLog (com.pratilipi.data.type.AuditLog)7 Author (com.pratilipi.data.type.Author)6 JsonElement (com.google.gson.JsonElement)5 Post (com.pratilipi.api.annotation.Post)5 UserData (com.pratilipi.data.client.UserData)5 Page (com.pratilipi.data.type.Page)5 Pratilipi (com.pratilipi.data.type.Pratilipi)5 Date (java.util.Date)5 HashMap (java.util.HashMap)5 Language (com.pratilipi.common.type.Language)3 UserPratilipi (com.pratilipi.data.type.UserPratilipi)3 PrintWriter (java.io.PrintWriter)3