/** 
 * (C) Copyright 2012 Chiral Behaviors, LLC. All Rights Reserved
 * 
 * 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 com.chiralbehaviors.CoRE.phantasm.jsonld.resources.test;

import java.util.EnumSet;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;

import org.eclipse.jetty.server.AbstractNetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlets.CrossOriginFilter;

import com.chiralbehaviors.CoRE.json.CoREModule;
import com.chiralbehaviors.CoRE.phantasm.jsonld.health.EmfHealthCheck;
import com.chiralbehaviors.CoRE.phantasm.jsonld.resources.FacetResource;
import com.chiralbehaviors.CoRE.phantasm.jsonld.resources.RuleformResource;
import com.chiralbehaviors.CoRE.phantasm.jsonld.resources.WorkspaceResource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module.Feature;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.server.DefaultServerFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

/**
 * @author hhildebrand
 * 
 */
public class TestApplication extends Application<TestServiceConfiguration> {

    public static void main(String[] argv) throws Exception {
        new TestApplication().run(argv);
    }

    private EntityManagerFactory emf;
    private Environment          environment;
    private Server               jettyServer;

    public TestApplication() {
    }

    public int getPort() {
        return ((AbstractNetworkConnector) environment.getApplicationContext().getServer().getConnectors()[0]).getLocalPort();
    }

    @Override
    public void initialize(Bootstrap<TestServiceConfiguration> bootstrap) {
        bootstrap.addBundle(new AssetsBundle("/assets", "/assets"));
        ObjectMapper objMapper = bootstrap.getObjectMapper();
        objMapper.registerModule(new CoREModule());
        Hibernate4Module module = new Hibernate4Module();
        module.enable(Feature.FORCE_LAZY_LOADING);
        objMapper.registerModule(module);
    }

    /* (non-Javadoc)
     * @see io.dropwizard.AbstractService#initialize(io.dropwizard.config.Configuration, io.dropwizard.config.Environment)
     */
    @Override
    public void run(TestServiceConfiguration configuration,
                    Environment environment) throws Exception {
        // Enable CORS headers for Angular JS
        final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS",
                                                                                 CrossOriginFilter.class);

        // Configure CORS parameters
        cors.setInitParameter("allowedOrigins", "*");
        cors.setInitParameter("allowedHeaders",
                              "X-Requested-With,Content-Type,Accept,Origin");
        cors.setInitParameter("allowedMethods",
                              "OPTIONS,GET,PUT,POST,DELETE,HEAD");

        // Add URL mapping
        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
                                      "/*");
        if (configuration.isRandomPort()) {
            ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getApplicationConnectors().get(0)).setPort(0);
            ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getAdminConnectors().get(0)).setPort(0);
        }
        this.environment = environment;
        environment.lifecycle().addServerLifecycleListener(server -> jettyServer = server);
        JpaConfiguration jpaConfig = configuration.getCrudServiceConfiguration();

        String unit = jpaConfig.getPersistenceUnit();
        Map<String, String> properties = jpaConfig.getProperties();
        emf = Persistence.createEntityManagerFactory(unit, properties);
        environment.jersey().register(new FacetResource(emf));
        environment.jersey().register(new WorkspaceResource(emf));
        environment.jersey().register(new RuleformResource(emf));
        environment.healthChecks().register("EMF Health",
                                            new EmfHealthCheck(emf));
    }

    public void stop() {
        emf.close();
        if (jettyServer != null) {
            try {
                jettyServer.setStopTimeout(100);
                jettyServer.stop();
            } catch (Throwable e) {
                // ignore
            }
        }
    }
}

@@ -705,34 +705,8 @@
 t;%0A%0A
-import java.util.EnumSet;%0A
 impo
@@ -812,86 +812,8 @@
 nce;
-%0Aimport javax.servlet.DispatcherType;%0Aimport javax.servlet.FilterRegistration;
 %0A%0Aim
@@ -911,61 +911,8 @@
 ver;
-%0Aimport org.eclipse.jetty.servlets.CrossOriginFilter;
 %0A%0Aim
@@ -2982,737 +2982,8 @@
 n %7B%0A
-        // Enable CORS headers for Angular JS%0A        final FilterRegistration.Dynamic cors = environment.servlets().addFilter(%22CORS%22,%0A                                                                                 CrossOriginFilter.class);%0A%0A        // Configure CORS parameters%0A        cors.setInitParameter(%22allowedOrigins%22, %22*%22);%0A        cors.setInitParameter(%22allowedHeaders%22,%0A                              %22X-Requested-With,Content-Type,Accept,Origin%22);%0A        cors.setInitParameter(%22allowedMethods%22,%0A                              %22OPTIONS,GET,PUT,POST,DELETE,HEAD%22);%0A%0A        // Add URL mapping%0A        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,%0A                                      %22/*%22);%0A
     

remove cors.