Search in sources :

Example 11 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException 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 12 with UnexpectedServerException

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

the class PratilipiDocUtil method updatePratilipiContent.

public static void updatePratilipiContent(Long pratilipiId) throws UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    BlobAccessor blobAccessor = DataAccessorFactory.getBlobAccessor();
    DocAccessor docAccessor = DataAccessorFactory.getDocAccessor();
    PratilipiContentDoc pcDoc = DataAccessorFactory.getDocAccessor().newPratilipiContentDoc();
    Pratilipi pratilipi = dataAccessor.getPratilipi(pratilipiId);
    if (!pratilipi.isOldContent()) {
        return;
    } else if (pratilipi.getContentType() == PratilipiContentType.PRATILIPI) {
        BlobEntry blobEntry = blobAccessor.getBlob("pratilipi-content/pratilipi/" + pratilipiId);
        if (blobEntry == null)
            return;
        String contentHtml = new String(blobEntry.getData(), Charset.forName("UTF-8"));
        List<Object[]> pageletList = _createPageletList(pratilipi, Jsoup.parse(contentHtml).body());
        if (pageletList.size() > 0) {
            PratilipiContentDoc.Chapter chapter = null;
            if (pageletList.get(0)[0] != PratilipiContentDoc.PageletType.HEAD)
                chapter = pcDoc.addChapter(pratilipi.getTitle() == null ? pratilipi.getTitleEn() : pratilipi.getTitle());
            for (Object[] pagelet : pageletList) {
                if (pagelet[0] == PratilipiContentDoc.PageletType.HEAD) {
                    chapter = pcDoc.addChapter((String) pagelet[1]);
                } else {
                    PratilipiContentDoc.Page page = chapter.getPage(1);
                    if (page == null)
                        page = chapter.addPage();
                    page.addPagelet((PratilipiContentDoc.PageletType) pagelet[0], pagelet[1], (PratilipiContentDoc.AlignmentType) pagelet[2]);
                }
            }
        }
    } else if (pratilipi.getContentType() == PratilipiContentType.IMAGE) {
        for (int i = 1; i <= pratilipi.getPageCount(); i++) {
            BlobEntry blobEntry = blobAccessor.getBlob("pratilipi/" + pratilipiId + "/images/" + i);
            if (pratilipi.getId() == 5639838220943360L && i <= 5)
                // Skipping first 5 pages as per Shally's request
                continue;
            else if (pratilipi.getId() == 5749258686824448L && i <= 4)
                // Skipping first 4 pages as per Shally's request
                continue;
            else if (pratilipi.getId() == 5486454792781824L && i <= 1)
                // Skipping first page as per Shally's request
                continue;
            else if (blobEntry == null && pratilipi.getId() == 5768181499035648L)
                // Skipping missing pages as per Dileepan's request
                continue;
            JsonObject imgData = new JsonObject();
            imgData.addProperty("name", i + "");
            imgData.addProperty("height", ImageUtil.getHeight(blobEntry));
            imgData.addProperty("width", ImageUtil.getWidth(blobEntry));
            pcDoc.addChapter(null).addPage().addPagelet(PratilipiContentDoc.PageletType.IMAGE, imgData);
        }
    } else {
        throw new UnexpectedServerException("ContentType " + pratilipi.getContentType() + " is not supported !");
    }
    docAccessor.save(pratilipiId, pcDoc);
}
Also used : DataAccessor(com.pratilipi.data.DataAccessor) DocAccessor(com.pratilipi.data.DocAccessor) BlobEntry(com.pratilipi.data.type.BlobEntry) Chapter(com.pratilipi.data.type.PratilipiContentDoc.Chapter) JsonObject(com.google.gson.JsonObject) Page(com.pratilipi.data.type.Page) AlignmentType(com.pratilipi.data.type.PratilipiContentDoc.AlignmentType) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) PageletType(com.pratilipi.data.type.PratilipiContentDoc.PageletType) BlobAccessor(com.pratilipi.data.BlobAccessor) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) JsonObject(com.google.gson.JsonObject) UserPratilipi(com.pratilipi.data.type.UserPratilipi) Pratilipi(com.pratilipi.data.type.Pratilipi) PratilipiContentDoc(com.pratilipi.data.type.PratilipiContentDoc)

Example 13 with UnexpectedServerException

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

the class PratilipiDocUtil method updatePratilipiGoogleAnalyticsPageViews.

public static List<Long> updatePratilipiGoogleAnalyticsPageViews(int year, int month, int day) throws UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    BlobAccessor blobAccessor = DataAccessorFactory.getBlobAccessor();
    Gson gson = new Gson();
    String dateStr = year + (month < 10 ? "-0" + month : "-" + month) + (day < 10 ? "-0" + day : "-" + day);
    String fileName = "pratilipi-google-analytics/page-views/" + dateStr;
    BlobEntry blobEntry = blobAccessor.getBlob(fileName);
    if (blobEntry == null) {
        try {
            blobEntry = blobAccessor.newBlob(fileName, "{}".getBytes("UTF-8"), "application/json");
        } catch (UnsupportedEncodingException e) {
            logger.log(Level.SEVERE, e.getMessage());
            throw new UnexpectedServerException();
        }
    }
    @SuppressWarnings("serial") Map<String, Integer> oldPageViewsMap = gson.fromJson(new String(blobEntry.getData(), Charset.forName("UTF-8")), new TypeToken<Map<String, Integer>>() {
    }.getType());
    Map<String, Integer> newPageViewsMap = GoogleAnalyticsApi.getPageViews(dateStr);
    Map<String, Integer> diffPageViewsMap = new HashMap<>();
    for (Entry<String, Integer> entry : newPageViewsMap.entrySet()) if (!entry.getValue().equals(oldPageViewsMap.get(entry.getKey())))
        diffPageViewsMap.put(entry.getKey(), entry.getValue());
    Map<Long, Integer> pageViewsMap = new HashMap<>();
    Map<Long, Integer> readPageViewsMap = new HashMap<>();
    for (Entry<String, Integer> entry : diffPageViewsMap.entrySet()) {
        String uri = entry.getKey();
        if (!uri.startsWith("/read?id=")) {
            if (uri.indexOf('?') != -1)
                uri = uri.substring(0, uri.indexOf('?'));
            Page page = dataAccessor.getPage(uri);
            if (page != null && page.getType() == PageType.PRATILIPI) {
                Long pratilpiId = page.getPrimaryContentId();
                if (pageViewsMap.get(pratilpiId) == null)
                    pageViewsMap.put(pratilpiId, entry.getValue());
                else
                    pageViewsMap.put(pratilpiId, pageViewsMap.get(pratilpiId) + entry.getValue());
            }
        } else {
            // Reader
            String patilipiIdStr = uri.indexOf('&') == -1 ? uri.substring("/read?id=".length()) : uri.substring("/read?id=".length(), uri.indexOf('&'));
            try {
                Long pratilpiId = Long.parseLong(patilipiIdStr);
                if (readPageViewsMap.get(pratilpiId) == null)
                    readPageViewsMap.put(pratilpiId, entry.getValue());
                else
                    readPageViewsMap.put(pratilpiId, readPageViewsMap.get(pratilpiId) + entry.getValue());
            } catch (NumberFormatException e) {
                logger.log(Level.SEVERE, "Exception while processing reader uri " + uri, e);
            }
        }
    }
    for (Entry<Long, Integer> entry : pageViewsMap.entrySet()) {
        if (readPageViewsMap.get(entry.getKey()) == null) {
            updatePratilipiGoogleAnalyticsPageViews(entry.getKey(), year, month, day, entry.getValue(), 0);
        } else {
            updatePratilipiGoogleAnalyticsPageViews(entry.getKey(), year, month, day, entry.getValue(), readPageViewsMap.get(entry.getKey()));
            readPageViewsMap.remove(entry.getKey());
        }
    }
    for (Entry<Long, Integer> entry : readPageViewsMap.entrySet()) updatePratilipiGoogleAnalyticsPageViews(entry.getKey(), year, month, day, 0, entry.getValue());
    if (diffPageViewsMap.size() > 0) {
        try {
            blobEntry.setData(gson.toJson(newPageViewsMap).getBytes("UTF-8"));
            blobAccessor.createOrUpdateBlob(blobEntry);
        } catch (UnsupportedEncodingException e) {
            logger.log(Level.SEVERE, e.getMessage());
            throw new UnexpectedServerException();
        }
    }
    ArrayList<Long> updatedPratilipiIdList = new ArrayList<>(pageViewsMap.size() + readPageViewsMap.size());
    updatedPratilipiIdList.addAll(pageViewsMap.keySet());
    updatedPratilipiIdList.addAll(readPageViewsMap.keySet());
    return updatedPratilipiIdList;
}
Also used : HashMap(java.util.HashMap) DataAccessor(com.pratilipi.data.DataAccessor) BlobEntry(com.pratilipi.data.type.BlobEntry) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Page(com.pratilipi.data.type.Page) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) TypeToken(com.google.common.reflect.TypeToken) BlobAccessor(com.pratilipi.data.BlobAccessor)

Example 14 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException 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 15 with UnexpectedServerException

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

the class AppPropertyApi method updateTopAuthorDate.

@Post
public PostResponse updateTopAuthorDate(PostRequest request) throws InsufficientAccessException, UnexpectedServerException {
    AccessToken accessToken = AccessTokenFilter.getAccessToken();
    if (accessToken.getUserId() != 5073076857339904L)
        throw new InsufficientAccessException();
    Logger.getLogger(AuthorListByReadCountApi.class.getSimpleName()).log(Level.INFO, "Updating app property");
    String dateStr = request.getDate();
    String filename = request.getFilename();
    if (dateStr != null && filename != null)
        throw new UnexpectedServerException("Both date and filename are persent");
    boolean isUpdated = false;
    if (dateStr != null && !dateStr.isEmpty()) {
        Logger.getLogger(AuthorListByReadCountApi.class.getSimpleName()).log(Level.INFO, "Updating Top author date app property");
        AppProperty appProperty = AppPropertyUtil.createOrUpdateTopAuthorsDate(dateStr);
        if (dateStr.equals(appProperty.getValue()))
            isUpdated = true;
    }
    if (filename != null && !filename.isEmpty()) {
        Logger.getLogger(AuthorListByReadCountApi.class.getSimpleName()).log(Level.INFO, "Updating personalized home filename");
        AppProperty appProperty = AppPropertyUtil.createOrUpdatePersonalizedHomeFilename(filename);
        if (appProperty.getValue().equals(filename))
            isUpdated = true;
    }
    return new PostResponse(isUpdated);
}
Also used : UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) AccessToken(com.pratilipi.data.type.AccessToken) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) AppProperty(com.pratilipi.data.type.AppProperty) Post(com.pratilipi.api.annotation.Post)

Aggregations

UnexpectedServerException (com.pratilipi.common.exception.UnexpectedServerException)46 IOException (java.io.IOException)19 JsonObject (com.google.gson.JsonObject)12 InvalidArgumentException (com.pratilipi.common.exception.InvalidArgumentException)12 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 HashMap (java.util.HashMap)12 Gson (com.google.gson.Gson)10 DataAccessor (com.pratilipi.data.DataAccessor)10 InsufficientAccessException (com.pratilipi.common.exception.InsufficientAccessException)6 BlobEntry (com.pratilipi.data.type.BlobEntry)6 Date (java.util.Date)6 File (java.io.File)5 JsonElement (com.google.gson.JsonElement)4 Get (com.pratilipi.api.annotation.Get)4 Post (com.pratilipi.api.annotation.Post)4 GenericResponse (com.pratilipi.api.shared.GenericResponse)4 OutputStream (java.io.OutputStream)4 URL (java.net.URL)4 GcsFilename (com.google.appengine.tools.cloudstorage.GcsFilename)3 Page (com.pratilipi.data.type.Page)3