Search in sources :

Example 21 with GenericResponse

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();
}
Also used : Task(com.pratilipi.taskqueue.Task) Email(com.pratilipi.data.type.Email) User(com.pratilipi.data.type.User) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) ArrayList(java.util.ArrayList) Date(java.util.Date) RtdbAccessor(com.pratilipi.data.RtdbAccessor) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) UserPreferenceRtdb(com.pratilipi.data.type.UserPreferenceRtdb) SimpleDateFormat(java.text.SimpleDateFormat) HashSet(java.util.HashSet) Get(com.pratilipi.api.annotation.Get)

Example 22 with 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();
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) AuthorFilter(com.pratilipi.common.util.AuthorFilter) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) Page(com.pratilipi.data.type.Page) Post(com.pratilipi.api.annotation.Post)

Example 23 with 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();
}
Also used : GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) Get(com.pratilipi.api.annotation.Get)

Example 24 with 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);
    }
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) HashMap(java.util.HashMap) GenericResponse(com.pratilipi.api.shared.GenericResponse) JsonElement(com.google.gson.JsonElement) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonObject(com.google.gson.JsonObject)

Example 25 with GenericResponse

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();
}
Also used : GenericResponse(com.pratilipi.api.shared.GenericResponse) AccessToken(com.pratilipi.data.type.AccessToken) Gson(com.google.gson.Gson) TagData(com.pratilipi.data.client.TagData) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) Post(com.pratilipi.api.annotation.Post)

Aggregations

GenericResponse (com.pratilipi.api.shared.GenericResponse)29 DataAccessor (com.pratilipi.data.DataAccessor)17 Post (com.pratilipi.api.annotation.Post)15 Get (com.pratilipi.api.annotation.Get)12 Task (com.pratilipi.taskqueue.Task)11 Date (java.util.Date)10 ArrayList (java.util.ArrayList)8 Gson (com.google.gson.Gson)7 InvalidArgumentException (com.pratilipi.common.exception.InvalidArgumentException)6 BlobEntry (com.pratilipi.data.type.BlobEntry)6 AppProperty (com.pratilipi.data.type.AppProperty)5 Pratilipi (com.pratilipi.data.type.Pratilipi)5 InsufficientAccessException (com.pratilipi.common.exception.InsufficientAccessException)4 Author (com.pratilipi.data.type.Author)4 SimpleDateFormat (java.text.SimpleDateFormat)4 GsonBuilder (com.google.gson.GsonBuilder)3 JsonObject (com.google.gson.JsonObject)3 GenericFileDownloadResponse (com.pratilipi.api.shared.GenericFileDownloadResponse)3 AuthorFilter (com.pratilipi.common.util.AuthorFilter)3 BlobAccessor (com.pratilipi.data.BlobAccessor)3