com.sinet.gage.tasklets.DominFullImportTasklet.java Source code

Java tutorial

Introduction

Here is the source code for com.sinet.gage.tasklets.DominFullImportTasklet.java

Source

package com.sinet.gage.tasklets;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.mashape.unirest.http.exceptions.UnirestException;
import com.sinet.gage.dao.DomainsRepository;
import com.sinet.gage.dlap.clients.DlapDomainClient;
import com.sinet.gage.dlap.entities.DomainResponse;
import com.sinet.gage.dlap.utils.DlapSession;
import com.sinet.gage.entities.Domain;

/**
 * Tasklet will import all current district and state domains by calling DALP
 * API
 * 
 * @author Team Gage
 *
 */
public class DominFullImportTasklet implements Tasklet {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
    DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    boolean loginToDlapServer = false;
    String currentStateId = null, currentStateName = null, currentDistrictId = null, currentDistrictName = null;
    List<DomainResponse> stateDomains = null;
    int stateCounter = 0;

    @Value("${domain.customer-id}")
    Integer parentDomainId;

    @Autowired
    private DomainsRepository domainsRepository;

    @Autowired
    private DlapSession dlapSession;

    @Autowired
    private DlapDomainClient dlapDomainClient;

    int domainCounter = 0;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

        if (!loginToDlapServer)
            loginToDlap();

        if (stateDomains == null)
            stateDomains = dlapDomainClient.getDomainReponseList(null, parentDomainId, "", "", 10000);

        if (stateCounter < stateDomains.size()) {
            DomainResponse stateDomain = stateDomains.get(stateCounter);
            currentStateName = stateDomain.getName();
            logger.info("DomainFullImportTasklet importing domain of state ### " + currentStateName);
            List<Domain> childDomains = getAllChildDomains(stateDomain);

            insertDomainsForState(childDomains, currentStateName);

            stateCounter++;
            return RepeatStatus.CONTINUABLE;
        } else {
            logger.info("DomainFullImportTasklet executed ...");

            return RepeatStatus.FINISHED;
        }
    }

    /**
     * Inserting all child domains for state
     * 
     * @param childDomains
     * @param stateName 
     */
    private void insertDomainsForState(List<Domain> childDomains, String stateName) {
        try {
            if (!CollectionUtils.isEmpty(childDomains)) {
                domainsRepository.insertDomains(childDomains);
            }
        } catch (Exception e) {
            logger.error("Error inserting domains " + childDomains.size() + " for state " + stateName, e);
        }
    }

    private List<Domain> getAllChildDomains(DomainResponse stateDomain) {
        List<Domain> domains = new ArrayList<>();
        List<DomainResponse> districts = dlapDomainClient.getDomainReponseListWithDomainData(null,
                Integer.parseInt(stateDomain.getId()), "", "", 10000);
        for (DomainResponse districtDomain : districts) {
            if (districtDomain != null) {
                currentDistrictName = districtDomain.getName();
                logger.info("DomainFullImportTasklet importing domain of district --- " + currentDistrictName);
                Domain district = mapToDomain(districtDomain);
                district.setStateDomainId(Long.parseLong(stateDomain.getId()));
                district.setStateDomainName(currentStateName);
                district.setParentDomainName(currentStateName);
                domains.add(district);
                List<Domain> schools = getAllSchoolDomains(stateDomain, districtDomain);
                domains.addAll(schools);
            }
        }

        return domains;
    }

    private List<Domain> getAllSchoolDomains(DomainResponse state, DomainResponse district) {
        List<Domain> domains = new ArrayList<>();
        List<DomainResponse> schools = dlapDomainClient.getDomainReponseListWithDomainData(null,
                Integer.parseInt(district.getId()), "", "", 10000);
        for (DomainResponse schoolDomain : schools) {
            if (schoolDomain != null) {
                logger.info("DomainFullImportTasklet importing domain of school = " + schoolDomain.getName());
                Domain school = mapToDomain(schoolDomain);
                school.setStateDomainId(Long.parseLong(state.getId()));
                school.setStateDomainName(currentStateName);
                school.setParentDomainName(district.getName());
                domains.add(school);
            }
        }

        return domains;
    }

    private Domain mapToDomain(DomainResponse response) {
        Domain domain = new Domain();
        domain.setDomainId(Long.parseLong(response.getId()));
        domain.setGuid(UUID.fromString(response.getGuid()));
        domain.setDomainName(response.getName());
        domain.setLoginPrefix(response.getUserspace());
        domain.setFlag(response.getFlags());
        domain.setParentDomainId(Long.parseLong(response.getParentid()));

        if (response.getData().getCustomization() != null
                && response.getData().getCustomization().getEdivatelearn() != null) {
            domain.setDomainType(response.getData().getCustomization().getEdivatelearn().getDomaintype());

            domain.setLicenseType(response.getData().getCustomization().getEdivatelearn().getLicensetype());
            domain.setLicensePoolType(response.getData().getCustomization().getEdivatelearn().getPooltype());
            domain.setNoOfLicense(parseLicenseNumber(response));
            domain.setPilot(response.getData().getCustomization().getEdivatelearn().isPilot());
            domain.setPilotStartDate(
                    getDateFormat(response.getData().getCustomization().getEdivatelearn().getPilotstartdate()));
            domain.setPilotEndDate(
                    getDateFormat(response.getData().getCustomization().getEdivatelearn().getPilotenddate()));
            domain.setFullSubscription(
                    response.getData().getCustomization().getEdivatelearn().isFullsubscription());
            domain.setSubscriptionStartDate(getDateFormat(
                    response.getData().getCustomization().getEdivatelearn().getSubscriptionstartdate()));
            domain.setSubscriptionEndDate(getDateFormat(
                    response.getData().getCustomization().getEdivatelearn().getSubscriptionenddate()));
        }

        domain.setCreatorUserId(Long.parseLong(response.getCreationby()));
        domain.setCreationDate(getDateWithISOFormat(response.getCreationdate()));
        domain.setModifierUserId(Long.parseLong(response.getModifiedby()));
        domain.setModifiedDate(getDateWithISOFormat(response.getModifieddate()));

        return domain;
    }

    /**
     * @param response
     * @return
     */
    private int parseLicenseNumber(DomainResponse response) {
        try {
            return Integer.parseInt(response.getData().getCustomization().getEdivatelearn().getNooflicense());
        } catch (Exception e) {
            logger.error("Unable to parse number of license for domain " + response.getName());
        }
        return 0;
    }

    private Timestamp getDateWithISOFormat(String dateString) {
        Timestamp formattedDate = null;
        try {
            if (StringUtils.hasLength(dateString)) {
                formattedDate = new Timestamp(
                        dateTimeFormatter.withOffsetParsed().parseDateTime(dateString).getMillis());
            }
        } catch (Exception e) {
            logger.error("Invalid date format: " + e.getMessage());
        }
        return formattedDate;
    }

    private Date getDateFormat(String dateString) {
        Date formattedDate = null;
        try {
            if (StringUtils.hasLength(dateString)) {
                formattedDate = new Date(dateFormat.parse(dateString).getTime());
            }
        } catch (ParseException e) {
            logger.error("Invalid date format: " + e.getMessage());
        }
        return formattedDate;
    }

    /**
     * Login to DLAP server
     * 
     * @throws UnirestException
     */
    private void loginToDlap() throws UnirestException {
        logger.info("Logging in to DLAP Server");
        dlapSession.login();
        loginToDlapServer = true;
    }

}