Package com.googlecode.objectify.test.dataloader

Source Code of com.googlecode.objectify.test.dataloader.ObjectifiedTest

/**
   Copyright 2012 Shakil Siraj (shakil.siraj@gmail.com)

   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.googlecode.objectify.test.dataloader;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;

import org.milyn.Smooks;
import org.milyn.container.ExecutionContext;
import org.milyn.persistence.util.PersistenceUtil;
import org.milyn.scribe.register.MapDaoRegister;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.util.Strings;

import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.test.dataloader.annotation.Dataloader;
import com.googlecode.objectify.test.dataloader.annotation.EntitiesList;
import com.googlecode.objectify.test.dataloader.annotation.NotAnObjectifiedDataloaderTest;

/**
* The base class for all dataloader unit tests. Also works as a generic unit
* test skeleton for all Objectify unit tests.
*
* @author Shakil Siraj
*/

@Test
public class ObjectifiedTest {

  /**
   * Log4J logger for the class.
   */
  private final Logger log = Logger
      .getLogger(ObjectifiedTest.class.getName());
  /**
   * Name of the test group for which the beforeMethod should be executed.
   */
  protected static final String OFY_DATALOADER_GROUP = "ofyDataloaderGroup";
  /**
   * Name of the Objectify Helper Bean class that will be added to the Smooks
   * execution context.
   */
  protected static final String OFY_HELPER = "ofyHelper";

  /**
   * AppEngine test helper class.
   */
  private final LocalServiceTestHelper helper;

  /**
   * Default constructor.
   */
  public ObjectifiedTest() {
    helper = getLocalServiceTestHelperImpl();
  }

  /**
   * Returns the AppEngine {@link LocalServiceTestHelper} implementation for
   * the tests. Note: Override this method for custom requirement
   *
   * @return Appengine Local test helper config
   */
  protected LocalServiceTestHelper getLocalServiceTestHelperImpl() {
    return new LocalServiceTestHelper(
        new LocalDatastoreServiceTestConfig()
            .setAlternateHighRepJobPolicyClass(AlwaysApplyJobPolicy.class),
        new LocalMemcacheServiceTestConfig(),
        new LocalTaskQueueTestConfig());
  }

  /**
   * This intercepter registers and loads up the Smooks configurations before
   * methods get tested. This also checks if there was any Dataloader and
   * EnititiesList annotation defined. If not then it will use the class level
   * annotations to pre-populate the datastore for the particular unit test.
   *
   * @param method
   *            the method that is about to be unit-tested
   * @throws Exception
   *             from the method under microscope
   */
  @BeforeMethod(alwaysRun = true, groups = { OFY_DATALOADER_GROUP })
  public final void beforeMethod(final Method method) throws Exception {
    if (!method.isAnnotationPresent(NotAnObjectifiedDataloaderTest.class)) {
      this.helper.setUp();
      if (method.isAnnotationPresent(EntitiesList.class)) {
        log.fine("Using EntitiesList for the method "
            + method.getName());
        registerObjectifyEntityType(method
            .getAnnotation(EntitiesList.class));
      } else {
        if (getClass().isAnnotationPresent(EntitiesList.class)) {
          log.fine("Using class level EntitiesList for the method "
              + method.getName());
          registerObjectifyEntityType((EntitiesList) getClass()
              .getAnnotation(EntitiesList.class));
        }
      }
      if (method.isAnnotationPresent(Dataloader.class)) {
        log.fine("Using Dataloader for the method " + method.getName());
        setupSmooksDataLoader(method.getAnnotation(Dataloader.class));
      } else if (getClass().isAnnotationPresent(Dataloader.class)) {
        log.fine("Using class level dataloader for the method "
            + method.getName());
        setupSmooksDataLoader((Dataloader) getClass().getAnnotation(
            Dataloader.class));
      }
    }
  }

  /**
   * Registers the entities list with Objectify.
   *
   * @param entitiesList
   *            The specified entities list
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  private void registerObjectifyEntityType(final EntitiesList entitiesList) {
    for (int i = 0; i < entitiesList.classes().length; i++) {
      Class clazz = entitiesList.classes()[i];
      log.fine("Registering entity type " + clazz.getName());
      ObjectifyService.register(clazz);
    }
  }

  /**
   * Setup the dataloader so smooks can load data. If the dataloader is not
   * present at method level, use the dataloader defined at class level.
   *
   * @param dataLoader
   *            the {@link Dataloader} definition
   * @throws Exception
   *             Any thrown while loading data
   */
  private void setupSmooksDataLoader(final Dataloader dataLoader)
      throws Exception {

    if (!Strings.isNullOrEmpty(dataLoader.file()[0])) {
      String configFileName = dataLoader.config();

      log.fine("Loading smooks configuration file " + configFileName);
      Smooks smooks = new Smooks(getClass().getResourceAsStream(
          configFileName));
      ExecutionContext executionContext = smooks.createExecutionContext();
      executionContext.getBeanContext().addBean(OFY_HELPER,
          getOfyHelperBean());
      MapDaoRegister<Object> register = MapDaoRegister
          .newInstance(getDAOMap());

      PersistenceUtil.setDAORegister(executionContext, register);

      for (int i = 0; i < dataLoader.file().length; i++) {
        StreamSource streamSource = new StreamSource(this.getClass()
            .getResourceAsStream(dataLoader.file()[i]));
        smooks.filterSource(executionContext, streamSource,
            new Result[] { null });
      }
    } else {
      log.info("Skipping loading smooks configuration "
          + "file as there is no StreamSource " + "file defined");
    }

  }

  /**
   * Creates an instance of {@link ObjectifyHelper}. NOTE:If you need to set
   * more options simply override
   *
   * @return Objectify Helper class
   */
  protected Object getOfyHelperBean() {
    return new ObjectifyHelper();
  }

  /**
   * Returns a Map of smooks DAOs that will be used by smooks to persist the
   * data. NOTE: if you want to add more of your DAOs, simply override.
   *
   * @return A {@link Map} containing all application DAOs
   */
  protected Map<String, ? extends Object> getDAOMap() {
    HashMap<String, Object> daoMap = new HashMap<String, Object>();
    daoMap.put("genericDAO", new ObjectifySmooksDAO());
    return daoMap;
  }

  /**
   * After each test method execution, clean up the persistence store.
   *
   * @param method
   *            the method that has just finished execution
   */
  @AfterMethod(alwaysRun = true, groups = { OFY_DATALOADER_GROUP })
  public final void afterMethod(final Method method) {
    if (!method.isAnnotationPresent(NotAnObjectifiedDataloaderTest.class)) {
      ObjectifyService.ofy().clear();
      this.helper.tearDown();
    }
  }
}
TOP

Related Classes of com.googlecode.objectify.test.dataloader.ObjectifiedTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.