net.navasoft.madcoin.backend.services.rest.impl.OrdersService.java Source code

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.services.rest.impl.OrdersService.java

Source

/*******************************************************************************
 * Copyright 2014 Juan Diego Navarre Gonzalez
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package net.navasoft.madcoin.backend.services.rest.impl;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;

import net.navasoft.madcoin.backend.OrderStatus;
import net.navasoft.madcoin.backend.annotations.ProcessedField;
import net.navasoft.madcoin.backend.annotations.ProcessorService;
import net.navasoft.madcoin.backend.annotations.helper.Precedence;
import net.navasoft.madcoin.backend.model.controller.exceptions.AlreadyAcceptedException;
import net.navasoft.madcoin.backend.model.controller.exceptions.AlreadyOnSourceException;
import net.navasoft.madcoin.backend.model.controller.exceptions.InexistentOrderException;
import net.navasoft.madcoin.backend.model.controller.exceptions.NonexistentEntityException;
import net.navasoft.madcoin.backend.model.controller.exceptions.PreexistingEntityException;
import net.navasoft.madcoin.backend.model.entities.impl.EndUsers;
import net.navasoft.madcoin.backend.model.entities.impl.EndUsersPK;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceCategories;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceProviders;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceProvidersPK;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestLocations;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequests;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsPK;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsXEndUsers;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsXServiceProviders;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsXServiceProvidersPK;
import net.navasoft.madcoin.backend.services.EFilters;
import net.navasoft.madcoin.backend.services.controller.exception.ControllerExceptionArgument;
import net.navasoft.madcoin.backend.services.controller.exception.impl.ControllerExceptionFactory;
import net.navasoft.madcoin.backend.services.controller.exception.impl.InexistentCategoryException;
import net.navasoft.madcoin.backend.services.controller.exception.impl.InexistentLOBException;
import net.navasoft.madcoin.backend.services.push.Notification;
import net.navasoft.madcoin.backend.services.push.PushNotificationConfiguration;
import net.navasoft.madcoin.backend.services.push.PushNotificationException;
import net.navasoft.madcoin.backend.services.push.PushNotificationService;
import net.navasoft.madcoin.backend.services.rest.IMaster;
import net.navasoft.madcoin.backend.services.rest.IOrdersService;
import net.navasoft.madcoin.backend.services.security.BCrypt;
import net.navasoft.madcoin.backend.services.vo.IFilteredFields;
import net.navasoft.madcoin.backend.services.vo.WorkRequestListVO;
import net.navasoft.madcoin.backend.services.vo.WorkRequestVO;
import net.navasoft.madcoin.backend.services.vo.request.SuccessRequestVO;
import net.navasoft.madcoin.backend.services.vo.response.AnswerServiceSuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.SuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.impl.AllowedAcceptingMode;
import net.navasoft.madcoin.backend.services.vo.response.impl.AppAcceptServiceSuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.impl.AppAnswerServiceSuccessResponseVO;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * net.navasoft.madcoin.backend.services.rest.impl Class class OrdersService.
 * Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 31/08/2014 02:50:04 PM
 */
@Service("ordersService")
@Scope(BeanDefinition.SCOPE_SINGLETON)
@ProcessorService
public class OrdersService implements IOrdersService {

    @Autowired
    @Qualifier("pushMaster")
    private IMaster<Provider> master;
    private static final Logger journal = Logger.getLogger(OrdersService.class);

    @Autowired
    @Qualifier("applePush")
    private PushNotificationService<PushNotificationConfiguration> notifier;

    /**
     * token generator.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier(value = "tokenutils")
    private TokenUtils tokenGenerator;

    /**
     * token generator.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier(value = "providerTokenutils")
    private TokenUtils providerTokenGenerator;

    @Autowired
    @Qualifier("ordersDAO")
    private IDataAccess<WorkRequests> ordersDAO;

    @Autowired
    @Qualifier("usersOrdersDAO")
    private IDataAccess<WorkRequestsXEndUsers> requestorDAO;

    @Autowired
    @Qualifier("providerOrdersDAO")
    private IDataAccess<WorkRequestsXServiceProviders> attenderDAO;

    @Autowired
    @Qualifier("locationsDAO")
    private IDataAccess<WorkRequestLocations> locationDAO;

    @Autowired
    @Qualifier("categoryDAO")
    private IDataAccess<ServiceCategories> categoryDAO;

    @ProcessedField(expectedType = String.class, possibleVariables = "lob", precedence = Precedence.BASIC_REQUIRED)
    private String lob;

    @ProcessedField(expectedType = String.class, possibleVariables = "category", precedence = Precedence.BASIC_REQUIRED)
    private String category;

    @ProcessedField(expectedType = String.class, possibleVariables = "generatedToken", precedence = Precedence.BASIC_REQUIRED)
    private String generatedToken;

    /**
     * request address.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_OPTIONAL, possibleVariables = "requestAddress")
    private String requestAddress;

    /**
     * model.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "model")
    private String model;

    /**
     * operative system.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "operativeSystem")
    private String operativeSystem;

    /**
     * serial.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "serial")
    private String serial;

    /**
     * version.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "version")
    private String version;

    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "comments")
    private String comments;

    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "location")
    private String location;

    @ProcessedField(precedence = Precedence.BASIC_REQUIRED, expectedType = Long.class, possibleVariables = "minCost")
    private Long minCost;

    @ProcessedField(precedence = Precedence.BASIC_REQUIRED, expectedType = Long.class, possibleVariables = "maxCost")
    private Long maxCost;

    @ProcessedField(expectedType = Date.class, precedence = Precedence.COMPLEX_REQUIRED, possibleVariables = "pretendedDate")
    private Date pretendedDate;

    @ProcessedField(expectedType = Date.class, precedence = Precedence.COMPLEX_REQUIRED, possibleVariables = "initDate")
    private Date estimatedArrivalDate;

    @ProcessedField(expectedType = Date.class, precedence = Precedence.COMPLEX_REQUIRED, possibleVariables = "finishDate")
    private Date estimatedClosingDate;

    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "serviceID")
    private String orderID;

    @Autowired
    @Qualifier("endUsersDao")
    private IDataAccess<EndUsers> endUsersDao;

    @Autowired
    @Qualifier("dataAccessProvider")
    private IDataAccess<ServiceProviders> providersDao;

    /**
     * Book request.
     * 
     * @param orderRequest
     *            the order request
     * @return the success response vo
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public SuccessResponseVO bookRequest(SuccessRequestVO orderRequest) {
        AnswerServiceSuccessResponseVO response = new AppAnswerServiceSuccessResponseVO();
        orderRequest.processValues(this);
        lob = String.valueOf(orderRequest.extractValue("lob"));
        category = String.valueOf(orderRequest.extractValue("category"));
        comments = String.valueOf(orderRequest.extractValue("comments"));
        location = String.valueOf(orderRequest.extractValue("location"));
        minCost = (Long) orderRequest.extractValue("minCost");
        maxCost = (Long) orderRequest.extractValue("maxCost");
        pretendedDate = Date.class.cast(orderRequest.extractValue("pretendedDate"));
        model = String.valueOf(orderRequest.extractValue("model"));
        operativeSystem = String.valueOf(orderRequest.extractValue("operativeSystem"));
        serial = String.valueOf(orderRequest.extractValue("serial"));
        version = String.valueOf(orderRequest.extractValue("version"));
        generatedToken = String.valueOf(orderRequest.extractValue("generatedToken"));
        generatedToken = generatedToken.replace("%2B", "+").replace("%2F", "/");
        try {
            if (tokenGenerator.validate(generatedToken)) {

                UserDetails userRequested = tokenGenerator.getUserFromToken(generatedToken);
                ServiceCategories cat = categoryDAO.getByLogicalId(category);
                if (cat.getParentLob().getLobPrefix().equals(lob)) {
                    WorkRequests order = new WorkRequests();
                    order.setGenerationDate(Calendar.getInstance().getTime());
                    order.setRealArrival(pretendedDate);
                    order.setServiceCategories(cat);
                    EndUsersPK user = new EndUsersPK();
                    user.setAppUsername(userRequested.getUsername());
                    EndUsers requestingUser = endUsersDao.getByLogicalId(user);
                    order.setComments(comments);
                    order.setProcessStatus(OrderStatus.REGISTERED.name());
                    try {
                        order = ordersDAO.create(order);
                        WorkRequestLocations locationOrder = new WorkRequestLocations();
                        locationOrder.setAddress(location);
                        locationOrder.setCity("BOGOTA");
                        locationOrder.setAdditionalData(location);
                        locationOrder.setWorkRequests(order);
                        locationDAO.create(locationOrder);
                        WorkRequestsXEndUsers cross = new WorkRequestsXEndUsers();
                        cross.setCreatedOn(Calendar.getInstance().getTime());
                        cross.setEndUsers(requestingUser);
                        cross.setWorkRequests(order);
                        requestorDAO.create(cross);

                        try {
                            order.setMinCost(minCost);
                            order.setMaxCost(maxCost);
                            master.init(order);
                            journal.info("Ejecutando la busqueda...");
                            master.getWorkspace();
                            journal.info("Paralelizando tareas...");
                            master.distribute();
                            journal.info("Ejecutando notificaciones...");
                            master.process();
                            journal.info("Esperando...");
                            master.getProcessedLoad();
                            journal.info("Finalizando...");
                            master.finish();
                        } catch (Exception e) {
                            journal.error(e.getMessage(), e);
                        }

                        response.setOrderSequence(order.getServiceCategories().getCategoryPrefix() + "-"
                                + String.valueOf(order.getWorkRequestsPK().getIdWorkRequests()));
                        response.setOrderStatus(OrderStatus.REGISTERED);
                        ((AppAnswerServiceSuccessResponseVO) response).setAttemptNumber(master.askWorkspace());
                        ((AppAnswerServiceSuccessResponseVO) response).setCyclicInterval(20000L);
                    } catch (PersistenceException e) {
                        e.printStackTrace();
                    } catch (PreexistingEntityException e) {
                        throw new AlreadyOnSourceException(e.getMessage());
                    }
                } else {
                    throw ControllerExceptionFactory.createException(
                            InexistentLOBException.class.getCanonicalName(), 2,
                            new ControllerExceptionArgument(lob));
                }

            } else {
                throw ControllerExceptionFactory.createException(BadCredentialsException.class.getCanonicalName(),
                        3, orderRequest.getErrorProcessingValues());
            }
        } catch (BadPaddingException badtoken) {
            throw ControllerExceptionFactory.createException(BadCredentialsException.class.getCanonicalName(), 3,
                    orderRequest.getErrorProcessingValues());
        }

        catch (NoResultException categoryNotFound) {
            throw ControllerExceptionFactory.createException(InexistentCategoryException.class.getCanonicalName(),
                    2, new ControllerExceptionArgument(category));
        } catch (UsernameNotFoundException invalidUser) {
            throw ControllerExceptionFactory.createException(invalidUser.getClass().getCanonicalName(), 3,
                    orderRequest.getErrorProcessingValues());
        }
        return response;
    }

    /**
     * Accept request.
     * 
     * @param providerRequest
     *            the provider request
     * @return the success response vo
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public SuccessResponseVO acceptRequest(SuccessRequestVO providerRequest) {
        AnswerServiceSuccessResponseVO response = new AppAcceptServiceSuccessResponseVO();
        providerRequest.processValues(this);
        lob = String.valueOf(providerRequest.extractValue("lob"));
        category = String.valueOf(providerRequest.extractValue("category"));
        orderID = String.valueOf(providerRequest.extractValue("serviceID")).trim();
        comments = String.valueOf(providerRequest.extractValue("comments"));
        estimatedArrivalDate = Date.class.cast(providerRequest.extractValue("initDate"));
        estimatedClosingDate = Date.class.cast(providerRequest.extractValue("finishDate"));
        model = String.valueOf(providerRequest.extractValue("model"));
        operativeSystem = String.valueOf(providerRequest.extractValue("operativeSystem"));
        serial = String.valueOf(providerRequest.extractValue("serial"));
        version = String.valueOf(providerRequest.extractValue("version"));
        generatedToken = String.valueOf(providerRequest.extractValue("generatedToken"));
        generatedToken = generatedToken.replace("%2B", "+").replace("%2F", "/");
        try {
            if (providerTokenGenerator.validate(generatedToken)) {
                UserDetails providerAccepted = providerTokenGenerator.getUserFromToken(generatedToken);
                ServiceCategories cat = categoryDAO.getByLogicalId(category);
                if (cat.getParentLob().getLobPrefix().equals(lob)) {
                    try {
                        WorkRequests order;
                        if (orderID.contains("-")) {
                            String[] compositeId = orderID.split("-");
                            ServiceCategories helper = categoryDAO.getByLogicalId(compositeId[0]);
                            if (!helper.equals(cat)) {
                                throw ControllerExceptionFactory.createException(
                                        InexistentCategoryException.class.getCanonicalName(), 2,
                                        new ControllerExceptionArgument(helper));
                            } else {
                                order = ordersDAO.getByLogicalId(new WorkRequestsPK(Long.valueOf(compositeId[1]),
                                        helper.getIdServiceCategory()));
                            }
                        } else {
                            order = ordersDAO.getByLogicalId(
                                    new WorkRequestsPK(Long.valueOf(orderID), cat.getIdServiceCategory()));
                        }
                        if (order.getWorkRequestsXServiceProvidersCollection().size() == 0) {
                            ServiceProvidersPK user = new ServiceProvidersPK();
                            user.setAppUsername(providerAccepted.getUsername());
                            ServiceProviders acceptingUser = providersDao.getByLogicalId(user);
                            WorkRequestsXServiceProviders cross = new WorkRequestsXServiceProviders();
                            cross.setServiceProviders(acceptingUser);
                            cross.setWorkRequests(order);
                            WorkRequestsXServiceProvidersPK key = new WorkRequestsXServiceProvidersPK(
                                    acceptingUser.getServiceProvidersPK().getIdServiceProvider(),
                                    acceptingUser.getServiceProvidersPK().getAppUsername(),
                                    order.getWorkRequestsPK().getIdWorkRequests(),
                                    order.getWorkRequestsPK().getCategoryId());
                            cross.setWorkRequestsXServiceProvidersPK(key);
                            cross.setAssignedOn(Calendar.getInstance().getTime());
                            cross = attenderDAO.create(cross);
                            Collection<WorkRequestsXServiceProviders> attenders = new ArrayList<WorkRequestsXServiceProviders>();
                            attenders.add(cross);
                            order.setWorkRequestsXServiceProvidersCollection(attenders);
                            order.setEstimatedArrival(estimatedArrivalDate);
                            order.setEstimatedClosing(estimatedClosingDate);
                            order.setProcessStatus(OrderStatus.ACCEPTED.name());
                            Calendar accepted = Calendar.getInstance();
                            response.setOrderSequence(order.getServiceCategories().getCategoryPrefix() + "-"
                                    + String.valueOf(order.getWorkRequestsPK().getIdWorkRequests()));
                            String hashed = BCrypt.hashpw(
                                    providerAccepted.getUsername() + accepted.getTimeInMillis(), BCrypt.gensalt());
                            hashed = hashed.substring(hashed.length() - 5);
                            order.setSafetyCode(hashed);
                            order = ordersDAO.edit(order);
                            response.setOrderStatus(OrderStatus.ACCEPTED);
                            ((AppAcceptServiceSuccessResponseVO) response)
                                    .setAcceptingMode(AllowedAcceptingMode.PROVIDER_MANUAL_ACCEPT);
                            ((AppAcceptServiceSuccessResponseVO) response).setAcceptedDate(accepted.getTime());
                            ((AppAcceptServiceSuccessResponseVO) response)
                                    .setProviderName(providerAccepted.getUsername());
                            ((AppAcceptServiceSuccessResponseVO) response).setSafetyCode(hashed);
                            Calendar proxyDate = Calendar.getInstance();
                            proxyDate.setTime(order.getGenerationDate());
                            proxyDate.setTimeInMillis(accepted.getTimeInMillis() - proxyDate.getTimeInMillis());
                            ((AppAcceptServiceSuccessResponseVO) response).setWaitingTime(proxyDate.getTime());
                            for (WorkRequestsXEndUsers endUser : order.getWorkRequestsXEndUsersCollection()) {
                                // TODO Obtener token de logueo de usuario
                                journal.info("Notifying to user "
                                        + endUser.getEndUsers().getEndUsersPK().getAppUsername() + " with token "
                                        + "df75a122 60b499a0 ae60c94f 4040330d 2e10a37d ba657451 c4df2120 fca8ad25");
                                notifier.sendNotification(new Notification(1,
                                        "Su servicio " + order.getServiceCategories().getCategoryPrefix() + "-"
                                                + order.getWorkRequestsPK().getIdWorkRequests()
                                                + "  ha sido aceptado por " + providerAccepted.getUsername()
                                                + ". Su passcode es: " + hashed,
                                        "default",
                                        "df75a122 60b499a0 ae60c94f 4040330d 2e10a37d ba657451 c4df2120 fca8ad25"));
                            }
                        } else {
                            String providerUser = "";
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            String acceptedDate = "";
                            for (WorkRequestsXServiceProviders acceptedProviders : order
                                    .getWorkRequestsXServiceProvidersCollection()) {
                                providerUser += acceptedProviders.getWorkRequestsXServiceProvidersPK()
                                        .getNameServiceProvider() + ", ";
                                acceptedDate += sdf.format(acceptedProviders.getAssignedOn()) + ", ";
                            }
                            providerUser = providerUser.substring(0, providerUser.length() - 2);
                            acceptedDate = acceptedDate.substring(0, acceptedDate.length() - 2);
                            throw new AlreadyAcceptedException(
                                    "Este servicio ya ha sido aceptado por otro(s) proveedor(es): {" + providerUser
                                            + "} en {" + acceptedDate + "}");
                        }
                    } catch (NonexistentEntityException e) {
                        throw new InexistentOrderException(
                                "La orden que intenta aceptar no existe en el sistema: {" + orderID + "}");
                    } catch (IndexOutOfBoundsException e) {
                        throw new InexistentOrderException(
                                "La orden que intenta aceptar no existe en el sistema: {" + orderID + "}");
                    } catch (PushNotificationException e) {
                        e.printStackTrace();
                    } catch (PreexistingEntityException e) {
                        throw new AlreadyAcceptedException(e.getMessage());
                    } catch (AlreadyAcceptedException e) {
                        throw e;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    throw ControllerExceptionFactory.createException(
                            InexistentLOBException.class.getCanonicalName(), 2,
                            new ControllerExceptionArgument(lob));
                }
            } else {
                throw ControllerExceptionFactory.createException(BadCredentialsException.class.getCanonicalName(),
                        3, providerRequest.getErrorProcessingValues());
            }
        } catch (BadPaddingException badtoken) {
            throw ControllerExceptionFactory.createException(BadCredentialsException.class.getCanonicalName(), 3,
                    providerRequest.getErrorProcessingValues());
        }

        catch (NoResultException categoryNotFound) {
            throw ControllerExceptionFactory.createException(InexistentCategoryException.class.getCanonicalName(),
                    2, new ControllerExceptionArgument(category));
        } catch (UsernameNotFoundException invalidUser) {
            throw ControllerExceptionFactory.createException(invalidUser.getClass().getCanonicalName(), 3,
                    providerRequest.getErrorProcessingValues());
        }
        return response;
    }

    /**
     * Cancel request.
     * 
     * @param actorRequest
     *            the actor request
     * @return the success response vo
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public SuccessResponseVO cancelRequest(SuccessRequestVO actorRequest) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * Gets the available requests by segment.
     * 
     * @param userType
     *            the user type
     * @param business_line
     *            the business_line
     * @param service_category
     *            the service_category
     * @param filter
     *            the filter
     * @return the available requests by segment
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public WorkRequestListVO getAvailableRequestsBySegment(String userType, String business_line,
            String service_category, IFilteredFields<?, ?, ?> filter) {
        WorkRequestListVO list = new WorkRequestListVO();
        int orderAmount = Calendar.getInstance().get(Calendar.HOUR);
        do {
            WorkRequestVO order = new WorkRequestVO();
            order.setRequestIdentifier(
                    MessageFormat.format("{0}-{1}-{2}", business_line, service_category, orderAmount));
            order.setCategory(business_line);
            order.setSubCategory(service_category);
            order.setOrderLocation("Carrera 26 # 27A - 13 Sur");
            order.setOrderLocationDetails("Click -n- Done CTO - Master Developer");
            order.setUsernameRequester("jnavarre");
            Calendar orderDate = Calendar.getInstance();
            orderDate.add(Calendar.HOUR, -orderAmount);
            order.setOrderGeneration(orderDate.getTime());
            order.setOrderStatus(orderDate.get(Calendar.HOUR_OF_DAY) % 2 == 0 ? OrderStatus.ASSIGNED_BY_ADMIN
                    : OrderStatus.CANCELLED_BY_USER);
            order.setOrderSummary("Asking for Blowjob...");
            list.addWorkRequest(order);
            orderAmount--;
        } while (orderAmount > 0);
        return list;
    }

    /**
     * Randomize.
     * 
     * @param amount
     *            the amount
     * @param timeParam
     *            the time param
     * @param order
     *            the order
     * @return the work request vo
     * @since 27/07/2014, 06:48:18 PM
     */
    private WorkRequestVO randomize(int amount, int timeParam, WorkRequestVO order) {
        order.setUsernameRequester("random" + (amount * timeParam));
        return order;
    }

    /**
     * Gets the available requests.
     * 
     * @param userType
     *            the user type
     * @param filter
     *            the filter
     * @return the available requests
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public WorkRequestListVO getAvailableRequests(String userType, IFilteredFields<?, ?, ?> filter) {
        WorkRequestListVO list = new WorkRequestListVO();
        int orderAmount = Calendar.getInstance().get(Calendar.HOUR);
        do {
            WorkRequestVO order = new WorkRequestVO();
            order.setOrderLocation("Carrera 15 # 82 -51 Of. 204");
            order.setOrderLocationDetails("Vision-AR Office - Mancho Nieto");
            order.setOrderStatus(OrderStatus.REGISTERED);
            order.setSubCategory("GENERAL CARE");
            String llaveUsuario = EFilters.getSpecificProperty("username", 0);
            Calendar orderDate = Calendar.getInstance();
            orderDate.add(Calendar.HOUR, -orderAmount);
            order.setOrderGeneration(orderDate.getTime());
            String lob = (orderDate.get(Calendar.MINUTE) % 2 == 0 ? "HOME" : "BEAUTY");
            order.setRequestIdentifier(MessageFormat.format("{0}-{1}-{2}", lob, "GENERAL CARE", orderAmount));
            order.setCategory(lob);
            if (filter != null) {
                if (!filter.getFilteredFields().isEmpty() && filter.getFilteredFields().containsKey(llaveUsuario)) {
                    order.setUsernameRequester((String) filter.getFilteredFields().get(llaveUsuario));
                } else {
                    order = randomize(orderAmount,
                            Math.abs(orderDate.get(Calendar.SECOND) - orderDate.get(Calendar.MINUTE)), order);
                }
            } else {
                order = randomize(orderAmount, orderDate.get(Calendar.SECOND), order);
            }
            order.setOrderSummary("Test!!!");
            list.addWorkRequest(order);
            orderAmount--;
        } while (orderAmount > 0);
        return list;
    }

    /**
     * Gets the all requests by segment.
     * 
     * @param userType
     *            the user type
     * @param business_line
     *            the business_line
     * @param service_category
     *            the service_category
     * @return the all requests by segment
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public WorkRequestListVO getAllRequestsBySegment(String userType, String business_line,
            String service_category) {
        WorkRequestListVO list = new WorkRequestListVO();
        int orderAmount = Calendar.getInstance().get(Calendar.HOUR);
        do {
            WorkRequestVO order = new WorkRequestVO();
            order.setRequestIdentifier(
                    MessageFormat.format("{0}-{1}-{2}", business_line, service_category, orderAmount));
            order.setCategory(business_line);
            order.setSubCategory(service_category);
            order.setOrderLocation("Carrera 26 # 27A - 13 Sur");
            order.setOrderLocationDetails("Click -n- Done CTO - Master Developer");
            order.setUsernameRequester("jnavarre");
            Calendar orderDate = Calendar.getInstance();
            orderDate.add(Calendar.HOUR, -orderAmount);
            order.setOrderGeneration(orderDate.getTime());
            order.setOrderStatus(orderDate.get(Calendar.HOUR_OF_DAY) % 2 == 0 ? OrderStatus.REGISTERED
                    : OrderStatus.CANCELLED_BY_USER);
            order.setOrderSummary("Asking for Blowjob...");
            list.addWorkRequest(order);
            orderAmount--;
        } while (orderAmount > 0);
        return list;
    }

    /**
     * Gets all requests.
     * 
     * @return the all requests
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    // Servicio para administrador...
    public WorkRequestListVO getAllRequests() {
        WorkRequestListVO list = new WorkRequestListVO();
        List<WorkRequests> allOrders = ordersDAO.getAll();
        for (WorkRequests order : allOrders) {
            WorkRequestVO itemResponse = new WorkRequestVO();
            itemResponse.setCategory(order.getServiceCategories().getParentLob().getLobPrefix());
            itemResponse.setSubCategory(order.getServiceCategories().getCategoryPrefix());
            itemResponse.setOrderGeneration(order.getGenerationDate());
            itemResponse.setOrderLocation(order.getWorkRequestLocations().getCity());
            itemResponse.setOrderLocationDetails(order.getWorkRequestLocations().getAddress());
            for (WorkRequestsXEndUsers user : order.getWorkRequestsXEndUsersCollection()) {
                itemResponse.setUsernameRequester(user.getEndUsers().getEndUsersPK().getAppUsername());
            }
            itemResponse.setRequestIdentifier(
                    MessageFormat.format("{0}-{1}", order.getServiceCategories().getCategoryPrefix(),
                            order.getWorkRequestsPK().getIdWorkRequests()));
            itemResponse.setOrderSummary(order.getComments());
            itemResponse.setOrderStatus(OrderStatus.valueOf(order.getProcessStatus()));
            list.addWorkRequest(itemResponse);
        }
        return list;
    }

    /**
     * Gets the all assigned requests.
     * 
     * @param filter
     *            the filter
     * @return the all assigned requests
     * @since 31/08/2014, 02:50:04 PM
     */
    @Override
    public WorkRequestListVO getAllAssignedRequests(IFilteredFields<?, ?, ?> filter) {
        ordersDAO.getAll();
        return null;
    }

}