use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.
the class EmailProcessApi method get.
@Get
public GenericResponse get(GenericRequest request) throws UnexpectedServerException {
DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
RtdbAccessor rtdbAccessor = DataAccessorFactory.getRtdbAccessor();
Map<Long, UserPreferenceRtdb> userPreferences = null;
List<Email> emailList = new ArrayList<>();
DataListIterator<Email> it = dataAccessor.getEmailListIteratorForStatePending(null, false);
Set<Long> userIds = new HashSet<>();
while (it.hasNext()) {
Email email = it.next();
emailList.add(email);
userIds.add(email.getUserId());
}
userPreferences = rtdbAccessor.getUserPreferences(userIds);
Map<Long, User> users = dataAccessor.getUsers(userPreferences.keySet());
// Re-scheduling for all Emails
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("IST"));
for (Email email : emailList) {
UserPreferenceRtdb preference = userPreferences.get(email.getUserId());
User user = users.get(email.getUserId());
if (email.getScheduledDate().before(new Date()))
continue;
if (email.getScheduledDate().equals(preference.getEmailFrequency().getNextSchedule(user.getLastEmailedDate())))
continue;
logger.log(Level.INFO, "Rescheduling email: " + email.getId() + " from " + dateFormat.format(email.getScheduledDate()) + " to " + dateFormat.format(preference.getEmailFrequency().getNextSchedule(user.getLastEmailedDate())));
email.setScheduledDate(preference.getEmailFrequency().getNextSchedule(user.getLastEmailedDate()));
if (// User changed setting to NEVER -> Scheduled Date will be null
email.getScheduledDate() == null)
email.setState(EmailState.DROPPED);
email.setLastUpdated(new Date());
}
// Creating Tasks
List<Task> taskList = new ArrayList<>();
Set<Long> userIdTaskSet = new HashSet<>();
for (Email email : emailList) {
if (// User changed setting to NEVER -> Email Dropped
email.getState() != EmailState.PENDING)
continue;
if (email.getScheduledDate().after(new Date()))
continue;
UserPreferenceRtdb preference = userPreferences.get(email.getUserId());
if (preference.getEmailFrequency() == EmailFrequency.IMMEDIATELY)
taskList.add(TaskQueueFactory.newTask().setUrl("/email/process").addParam("emailId", email.getId().toString()));
else
userIdTaskSet.add(email.getUserId());
email.setState(EmailState.IN_PROGRESS);
email.setLastUpdated(new Date());
}
for (Long userId : userIdTaskSet) taskList.add(TaskQueueFactory.newTask().setUrl("/email/process").addParam("userId", userId.toString()));
TaskQueueFactory.getEmailHpTaskQueue().addAll(taskList);
emailList = dataAccessor.createOrUpdateEmailList(emailList);
return new GenericResponse();
}
use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.
the class BatchProcessApi method post.
@Post
public GenericResponse post(PostRequest request) throws InvalidArgumentException, InsufficientAccessException {
DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
if (request.type == BatchProcessType.NOTIFACTION_BY_AUTHOR_FILTER) {
Page page = null;
JsonObject errorMessages = new JsonObject();
if (request.message == null || request.message.trim().isEmpty())
errorMessages.addProperty("message", "message is required !");
if (request.sourceUri == null || request.sourceUri.trim().isEmpty())
errorMessages.addProperty("sourceUri", "sourceUri is required !");
else if ((page = dataAccessor.getPage(request.sourceUri)) == null)
errorMessages.addProperty("sourceUri", "Invalid url !");
else if (page.getType() != PageType.PRATILIPI)
errorMessages.addProperty("sourceUri", "Must be a content url !");
if (errorMessages.size() != 0)
throw new InvalidArgumentException(errorMessages);
AuthorFilter authorFilter = new AuthorFilter();
authorFilter.setLanguage(request.language);
authorFilter.setState(AuthorState.ACTIVE);
// Creating Init Doc
JsonObject initDoc = new JsonObject();
initDoc.add("authorFilter", new Gson().toJsonTree(authorFilter));
// Creating Exec Doc
JsonObject execDoc = new JsonObject();
execDoc.addProperty("message", request.message);
execDoc.addProperty("sourceId", page.getPrimaryContentId().toString());
execDoc.addProperty("type", NotificationType.PRATILIPI.toString());
BatchProcessDataUtil.createBatchProcess(request.type, initDoc.toString(), execDoc.toString(), request.language);
}
return new GenericResponse();
}
use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.
the class AccessTokenCleanupApi method get.
@Get
public GenericResponse get(GenericRequest request) {
DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
while (true) {
int count = dataAccessor.deleteExpiredAccessTokenList(1000);
logger.log(Level.INFO, "Deleted " + count + " AccessToken entities ...");
if (count < 1000)
break;
}
return new GenericResponse();
}
use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.
the class GenericBatchApi method service.
@Override
protected final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Logging
if (SystemProperty.STAGE != SystemProperty.STAGE_PROD)
logHeaders(request);
logRequestParams(request);
String method = request.getMethod();
Object apiResponse = null;
if (method.equals("GET")) {
Gson gson = new Gson();
JsonObject apiReqs = gson.fromJson(// e.g. {"req1":"/page?uri=/munshi-premchand/godan","req2":"/pratilipi?pratilipiId=$req1.primaryContentId"}
request.getParameter("requests"), JsonElement.class).getAsJsonObject();
Map<String, Object> apiResps = new HashMap<>();
for (Entry<String, JsonElement> apiReq : apiReqs.entrySet()) {
// e.g. /pratilipi?pratilipiId=$req1.primaryContentId
String reqUri = apiReq.getValue().getAsString();
int index = reqUri.indexOf('?');
GenericApi api = // e.g. /pratilipi
index == -1 ? ApiRegistry.getApi(reqUri) : ApiRegistry.getApi(reqUri.substring(0, index));
JsonObject reqPayloadJson = // e.g. pratilipiId=$req1.primaryContentId
index == -1 ? new JsonObject() : createRequestPayloadJson(reqUri.substring(index + 1), request);
// Replacing variables by values
for (Entry<String, JsonElement> paramVal : reqPayloadJson.entrySet()) {
if (paramVal.getValue() == null)
continue;
String var = paramVal.getValue().getAsString();
if (!var.startsWith("$"))
continue;
Object varResp = apiResps.get(var.substring(1, var.indexOf(".")));
if (varResp == null)
reqPayloadJson.add(paramVal.getKey(), null);
else if (varResp instanceof JsonElement)
reqPayloadJson.add(paramVal.getKey(), ((JsonElement) varResp).getAsJsonObject().get(var.substring(var.indexOf(".") + 1)));
else
reqPayloadJson.add(paramVal.getKey(), null);
}
Object apiResp = executeApi(api, api.getMethod, reqPayloadJson, api.getMethodParameterType, request);
if (apiResp instanceof GenericResponse)
apiResp = gson.toJsonTree(apiResp);
apiResps.put(apiReq.getKey(), apiResp);
}
dispatchApiResponse(apiResps, request, response);
} else {
apiResponse = new InvalidArgumentException("Invalid resource or method.");
dispatchApiResponse(apiResponse, request, response);
}
}
use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.
the class TagsApi method addTags.
@Post
public GenericResponse addTags(PostRequest request) throws InsufficientAccessException {
// Security Hack
AccessToken accessToken = AccessTokenFilter.getAccessToken();
if (accessToken.getUserId() != 5073076857339904L) {
Logger.getLogger(TagsApi.class.getSimpleName()).log(Level.SEVERE, "AccessToken : " + accessToken.getId());
Logger.getLogger(TagsApi.class.getSimpleName()).log(Level.SEVERE, "User Id : " + accessToken.getUserId());
throw new InsufficientAccessException();
}
Gson gson = new Gson();
// Creating TagData object.
TagData tagData = gson.fromJson(gson.toJson(request), TagData.class);
tagData = TagDataUtil.saveTag(tagData);
return new GenericResponse();
}
Aggregations