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();
}
}
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);
}
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;
}
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();
}
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);
}
Aggregations