/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.com.amx.mx.dda.crn.msjb;

/**
 *
 * @author albarranoi
 */
import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import mx.com.amx.mx.dda.crn.DDAClienteSAP;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@WebServlet(name="serviceEnmienda", urlPatterns={"/servicioEnmienda"})
public class Service extends HttpServlet {

    private DDAClienteSAP ex;
    private final Logger LOG = Logger.getLogger(this.getClass().getSimpleName());

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ejec();
        out.write("{\"rows\":\"OK\"}");
    }

    public void ejec() {

        ScheduledExecutorService se = Executors.newScheduledThreadPool(5);
        ScheduledFuture sf = se.schedule(new Callable() {

            @Override
            public Object call() throws Exception {
                LOG.info("<< :::::::::::::::: Inicia CRN Cliente SAP :::::::::::::::: >>");

                ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
                setEx((DDAClienteSAP) context.getBean("clienteSAP_DDA"));

                getEx().ejecutaProceso();
                LOG.info("<< :::::::::::::::: Terminando CRN Cliente SAP :::::::::::::::: >>");
                return "Done";
            }

        }, 1, TimeUnit.SECONDS);//Retrazo de tiempo

        // System.out.println("Result of ScheduledFuture: " );
        se.shutdown();
    }

    /**
     * @return the ex
     */
    public DDAClienteSAP getEx() {
        return ex;
    }

    /**
     * @param ex the ex to set
     */
    public void setEx(DDAClienteSAP ex) {
        this.ex = ex;
    }

}
