com.mortgage.serial.LicenseService.java Source code

Java tutorial

Introduction

Here is the source code for com.mortgage.serial.LicenseService.java

Source

package com.mortgage.serial;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.Named;
import com.google.api.server.spi.response.CollectionResponse;
import com.google.appengine.repackaged.org.apache.commons.codec.digest.DigestUtils;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.mortgage.serial.model.AuthorizationResponse;
import com.mortgage.serial.model.License;
import com.mortgage.serial.model.LogEntry;
import com.mortgage.serial.model.User;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.googlecode.objectify.ObjectifyService.ofy;

@Api(name = "license", version = "v1")
public class LicenseService {
    @Inject
    HttpServletRequest servletRequest;

    public LicenseService() {
        ObjectifyService.register(License.class);
        ObjectifyService.register(User.class);
        ObjectifyService.register(LogEntry.class);
    }

    public User createUser(User user) {
        ofy().save().entity(user).now();
        return user;
    }

    public CollectionResponse<User> getUsers() {
        return CollectionResponse.<User>builder().setItems(ofy().load().type(User.class).list()).build();
    }

    private void addUserLogEntry(User user, String log) {
        LogEntry logEntry = new LogEntry();
        logEntry.setDate(new Date());
        logEntry.setLog(log);
        ofy().save().entity(logEntry).now();
    }

    public License createUserLicense(@Named("userId") Long userId, @Named("durationDays") int durationDays)
            throws Exception {
        Key<User> userKey = Key.create(User.class, userId);
        User user = ofy().load().key(userKey).now();
        License newLicense = new License(userKey);
        newLicense.setDurationDays(durationDays);
        String serialNumber = DigestUtils.md5Hex(user.getEmail() + new Date().toString() + new Random().toString());
        newLicense.setSerialNumber(serialNumber);
        newLicense.setCreationDate(new Date());
        ofy().save().entities(newLicense, user).now();
        return newLicense;
    }

    public CollectionResponse<License> getUserLicenses(@Named("userId") Long userId) {
        Key<User> userKey = Key.create(User.class, userId);
        User user = ofy().load().key(userKey).now();
        List<License> userLicenses = ofy().load().type(License.class).ancestor(user).list();
        return CollectionResponse.<License>builder().setItems(userLicenses).build();

    }

    private Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); // minus number would decrement the days
        return cal.getTime();
    }

    public CollectionResponse<LogEntry> getUserLogEntries(@Named("userId") Long userId) {
        Key<User> userKey = Key.create(User.class, userId);
        return CollectionResponse.<LogEntry>builder()
                .setItems(ofy().load().type(LogEntry.class).ancestor(userKey).list()).build();
    }

    public AuthorizationResponse authorize(AuthorizationRequest request) {
        // find user according to email from rquest
        User user = ofy().load().type(User.class).filter("email", request.getEmail()).first().now();

        if (user == null) {
            // we don't have user to write log
            return new AuthorizationResponse(false, "user does not exist");
        }

        // find the license that belongs to that user
        License license = ofy().load().type(License.class).ancestor(user)
                .filter("serialNumber", request.getSerialNumber()).first().now();

        boolean success = false;
        String message;

        if (license == null) {
            message = "license does not exist for this user";
            success = false;
        } else if (license.getGuid() == null) { // is it first activation
            license.setActivationDate(new Date());
            license.setGuid(request.getGuid());
            ofy().save().entity(license).now();
            message = "activation with guid: " + request.getGuid();
            success = true;
        } else if (!license.getGuid().equals(request.getGuid())) {
            message = "non matching guid authorization attempt with guid: " + request.getGuid();
            success = false;
        } else if (new Date().after(addDays(license.getActivationDate(), license.getDurationDays()))) {
            success = false;
            message = "license expired";
        } else {
            success = true;
            message = "authorized";
        }

        // authorized
        addUserLogEntry(user, message);
        ofy().save().entity(user).now();
        return new AuthorizationResponse(success, message);
    }
}