Search in sources :

Example 11 with GenericResponse

use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.

the class PratilipiProcessApi method getPratilipiProcess.

@Get
public GenericResponse getPratilipiProcess(GenericRequest request) throws UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    // START: Creating ValidateData Tasks
    // Fetching AppProperty
    String appPropertyId = "Api.PratilipiProcess.ValidateData";
    AppProperty appProperty = dataAccessor.getAppProperty(appPropertyId);
    if (appProperty == null) {
        appProperty = dataAccessor.newAppProperty(appPropertyId);
        appProperty.setValue(new Date(0));
    }
    // Fetching list of Pratilipi ids.
    PratilipiFilter pratilipiFilter = new PratilipiFilter();
    pratilipiFilter.setMinLastUpdate((Date) appProperty.getValue(), false);
    List<Long> pratilipiIdList = dataAccessor.getPratilipiIdList(pratilipiFilter, null, 0, 10000).getDataList();
    // Creating one task per Pratilipi id.
    List<Task> taskList = new ArrayList<>(pratilipiIdList.size());
    for (Long pratilipiId : pratilipiIdList) {
        Task task = TaskQueueFactory.newTask().setUrl("/pratilipi/process").addParam("pratilipiId", pratilipiId.toString()).addParam("validateData", "true");
        taskList.add(task);
    }
    TaskQueueFactory.getPratilipiOfflineTaskQueue().addAll(taskList);
    logger.log(Level.INFO, "Added " + taskList.size() + " ValidateData tasks.");
    // Updating AppProperty.
    if (pratilipiIdList.size() > 0) {
        Pratilipi pratilipi = dataAccessor.getPratilipi(pratilipiIdList.get(pratilipiIdList.size() - 1));
        Date lastUpdatedDate = pratilipi.getLastUpdated();
        logger.log(Level.INFO, "Processing all contents updated from " + (Date) appProperty.getValue() + " to " + lastUpdatedDate + ".");
        logger.log(Level.INFO, "Last Updated PratilipiID : " + pratilipi.getId());
        appProperty.setValue(lastUpdatedDate);
        appProperty = dataAccessor.createOrUpdateAppProperty(appProperty);
    }
    return new GenericResponse();
}
Also used : PratilipiFilter(com.pratilipi.common.util.PratilipiFilter) Task(com.pratilipi.taskqueue.Task) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) ArrayList(java.util.ArrayList) Pratilipi(com.pratilipi.data.type.Pratilipi) AppProperty(com.pratilipi.data.type.AppProperty) Date(java.util.Date) Get(com.pratilipi.api.annotation.Get)

Example 12 with GenericResponse

use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.

the class PratilipiStatsApi method post.

@Post
public GenericResponse post(Request request) throws InvalidArgumentException, InsufficientAccessException, UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    Pratilipi pratilipi = dataAccessor.getPratilipi(request.pratilipiId);
    if (pratilipi == null || pratilipi.getState() != PratilipiState.PUBLISHED)
        return new GenericResponse();
    if (request.fbLikeShareCount == null) {
        Page page = dataAccessor.getPage(PageType.PRATILIPI, pratilipi.getId());
        request.fbLikeShareCount = FacebookApi.getUrlShareCount("http://" + Website.ALL_LANGUAGE.getHostName() + page.getUri());
    }
    PratilipiDataUtil.updatePratilipiStats(request.pratilipiId, request.readCountOffset, request.readCount, request.fbLikeShareCountOffset, request.fbLikeShareCount);
    PratilipiDataUtil.updatePratilipiSearchIndex(request.pratilipiId, null);
    if (pratilipi.getAuthorId() != null && (request.readCountOffset != null || request.readCount != null)) {
        Task task = TaskQueueFactory.newTask().setUrl("/author/process").addParam("authorId", pratilipi.getAuthorId().toString()).addParam("updateStats", "true");
        TaskQueueFactory.getAuthorOfflineTaskQueue().add(task);
    }
    return new GenericResponse();
}
Also used : Task(com.pratilipi.taskqueue.Task) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) Page(com.pratilipi.data.type.Page) Pratilipi(com.pratilipi.data.type.Pratilipi) Post(com.pratilipi.api.annotation.Post)

Example 13 with GenericResponse

use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.

the class UserProcessApi method post.

@Post
public GenericResponse post(PostRequest request) throws InvalidArgumentException, UnexpectedServerException {
    if (request.validateData != null && request.validateData) {
        DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
        User user = dataAccessor.getUser(request.userId);
        // DELETED User entity can not have a non-DELETED Author entity linked.
        if (user.getState() == UserState.DELETED) {
            Author author = dataAccessor.getAuthorByUserId(user.getId());
            if (author != null && author.getState() != AuthorState.DELETED)
                throw new InvalidArgumentException("DELETED User entity has a non-DELETED Author entity linked.");
            // TODO: DELETED User entity can not have non-DELETED UserAuthor entities.
            return new GenericResponse();
        }
        // Either of two - email and facebook id - must be present.
        if (user.getEmail() == null && user.getFacebookId() == null)
            throw new InvalidArgumentException("Neither email nor facebook id is set.");
        // Email, if present, must not be empty.
        if (user.getEmail() != null && user.getEmail().trim().isEmpty())
            throw new InvalidArgumentException("Email is empty.");
        // Facebook id, if present, must not be empty.
        if (user.getFacebookId() != null && user.getFacebookId().trim().isEmpty())
            throw new InvalidArgumentException("Facebook Id is empty.");
        // Email, if present, must be trimmed and converted to lower case.
        if (user.getEmail() != null && !user.getEmail().equals(user.getEmail().trim().toLowerCase()))
            throw new InvalidArgumentException("Email is either not trimmed or not converted to lower case.");
        // Only one non-DELETED User entity can exist per email id.
        if (user.getEmail() != null) {
            Query<UserEntity> query = ObjectifyService.ofy().load().type(UserEntity.class).filter("EMAIL", user.getEmail()).filter("STATE !=", UserState.DELETED).order("STATE").order("SIGN_UP_DATE");
            List<UserEntity> list = query.list();
            if (list.size() != 1)
                throw new InvalidArgumentException(list.size() + " non-DELETED User entities found for email " + user.getEmail() + " .");
        }
        // Only one non-DELETED User entity can exist per facebook id.
        if (user.getFacebookId() != null) {
            Query<UserEntity> query = ObjectifyService.ofy().load().type(UserEntity.class).filter("FACEBOOK_ID", user.getFacebookId()).filter("STATE !=", UserState.DELETED).order("STATE").order("SIGN_UP_DATE");
            List<UserEntity> list = query.list();
            if (list.size() != 1)
                throw new InvalidArgumentException(list.size() + " non-DELETED User entities found for Facebook Id " + user.getFacebookId() + " .");
        }
        // Author profile for the user.
        Query<AuthorEntity> query = ObjectifyService.ofy().load().type(AuthorEntity.class).filter("USER_ID", user.getId()).filter("STATE !=", AuthorState.DELETED).order("STATE").order("REGISTRATION_DATE");
        List<AuthorEntity> authorList = query.list();
        if (authorList.size() == 0) {
            if (user.getState() != UserState.REFERRAL || user.getSignUpSource() != UserSignUpSource.PRE_LAUNCH_WEBSITE)
                throw new InvalidArgumentException("Could not find an Author entity linked.");
        } else if (authorList.size() == 1) {
        // Do Nothing.
        } else {
            throw new InvalidArgumentException("User has " + authorList.size() + " non-DELETED Author entities linked.");
        }
    }
    if (request.updateFollowsDoc != null && request.updateFollowsDoc) {
        UserDocUtil.updateUserFollows(request.userId);
    }
    if (request.updateUserAuthorStats != null && request.updateUserAuthorStats) {
        UserDataUtil.updateUserAuthorStats(request.userId);
    }
    return new GenericResponse();
}
Also used : User(com.pratilipi.data.type.User) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) Author(com.pratilipi.data.type.Author) UserEntity(com.pratilipi.data.type.gae.UserEntity) AuthorEntity(com.pratilipi.data.type.gae.AuthorEntity) Post(com.pratilipi.api.annotation.Post)

Example 14 with GenericResponse

use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.

the class UserEmailApi method post.

@Post
public GenericResponse post(PostRequest request) throws InvalidArgumentException, InsufficientAccessException, UnexpectedServerException {
    JsonObject errorMessages = new JsonObject();
    if ((request.sendWelcomeMail() || request.sendBirthdayMail()) && request.getUserId() == null)
        errorMessages.addProperty("userId", GenericRequest.ERR_USER_ID_REQUIRED);
    if (request.sendEmailVerificationMail() && request.getUserId() == null && (request.getEmail() == null || request.getEmail().trim().isEmpty()))
        errorMessages.addProperty("email", GenericRequest.ERR_EMAIL_REQUIRED);
    if (request.sendPasswordResetMail() && (request.getEmail() == null || request.getEmail().trim().isEmpty()))
        errorMessages.addProperty("email", GenericRequest.ERR_EMAIL_REQUIRED);
    if (errorMessages.entrySet().size() > 0)
        throw new InvalidArgumentException(errorMessages);
    Language language = request.getLanguage() == null ? // User facing requests
    UxModeFilter.getDisplayLanguage() : // Offline requests
    request.getLanguage();
    if (request.sendWelcomeMail())
        UserDataUtil.sendWelcomeMail(request.getUserId(), language);
    if (request.sendEmailVerificationMail()) {
        if (request.getUserId() != null)
            UserDataUtil.sendEmailVerificationMail(request.getUserId(), language);
        else
            UserDataUtil.sendEmailVerificationMail(request.getEmail(), language);
    }
    if (request.sendPasswordResetMail())
        UserDataUtil.sendPasswordResetMail(request.getEmail(), language);
    if (request.sendBirthdayMail())
        throw new InvalidArgumentException("Feature not yet supported !");
    return new GenericResponse();
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) Language(com.pratilipi.common.type.Language) GenericResponse(com.pratilipi.api.shared.GenericResponse) JsonObject(com.google.gson.JsonObject) Post(com.pratilipi.api.annotation.Post)

Example 15 with GenericResponse

use of com.pratilipi.api.shared.GenericResponse in project pratilipi by Pratilipi.

the class UserBackupApi method get.

@Get
public GenericResponse get(GetRequest request) throws UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    BlobAccessor blobAccessor = DataAccessorFactory.getBlobAccessorBackup();
    Date backupDate = new Date();
    DateFormat yearFormat = new SimpleDateFormat("yyyy");
    DateFormat dayFormat = new SimpleDateFormat("dd");
    DateFormat hourFormat = new SimpleDateFormat("HH");
    DateFormat csvDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    yearFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    dayFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    hourFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    csvDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    StringBuilder backup = new StringBuilder();
    StringBuilder csv = new StringBuilder(CSV_HEADER + LINE_SEPARATOR);
    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonLongDateAdapter()).create();
    int batchSize = 1000;
    String cursor = null;
    int count = 0;
    while (true) {
        DataListCursorTuple<User> userListCursorTupe = dataAccessor.getUserList(cursor, batchSize);
        List<User> userList = userListCursorTupe.getDataList();
        for (User user : userList) {
            backup.append(gson.toJson(user) + LINE_SEPARATOR);
            if (request.generateCsv())
                csv.append("'" + user.getId().toString()).append(CSV_SEPARATOR).append(user.getFacebookId() == null ? "" : "'" + user.getFacebookId()).append(CSV_SEPARATOR).append(user.getEmail() == null ? "" : user.getEmail()).append(CSV_SEPARATOR).append(csvDateFormat.format(user.getSignUpDate())).append(LINE_SEPARATOR);
        }
        count = count + userList.size();
        if (userList.size() < batchSize)
            break;
        else
            cursor = userListCursorTupe.getCursor();
    }
    String year = yearFormat.format(backupDate);
    String day = dayFormat.format(backupDate);
    String hour = hourFormat.format(backupDate);
    String fileName = "datastore.user/" + year + "-mm-" + day + "/" + "user-" + year + "-mm-" + day + "-" + hour + ":xx-IST";
    BlobEntry userBackupEntry = blobAccessor.newBlob(fileName, backup.toString().getBytes(Charset.forName("UTF-8")), "text/plain");
    blobAccessor.createOrUpdateBlob(userBackupEntry);
    if (request.generateCsv()) {
        BlobEntry userCsvEntry = blobAccessor.newBlob("datastore/user.csv", csv.toString().getBytes(Charset.forName("UTF-8")), "text/csv");
        blobAccessor.createOrUpdateBlob(userCsvEntry);
    }
    logger.log(Level.INFO, "Backed up " + count + " User Entities.");
    return new GenericResponse();
}
Also used : User(com.pratilipi.data.type.User) GsonBuilder(com.google.gson.GsonBuilder) GenericResponse(com.pratilipi.api.shared.GenericResponse) DataAccessor(com.pratilipi.data.DataAccessor) BlobEntry(com.pratilipi.data.type.BlobEntry) Gson(com.google.gson.Gson) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) BlobAccessor(com.pratilipi.data.BlobAccessor) SimpleDateFormat(java.text.SimpleDateFormat) GsonLongDateAdapter(com.pratilipi.common.util.GsonLongDateAdapter) Get(com.pratilipi.api.annotation.Get)

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