/**
 *
 */
package com.github.mrcritical.ironcache;

import java.util.List;
import java.util.Locale;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.annotation.ThreadSafe;
import org.joda.time.DateTime;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import com.github.mrcritical.ironcache.internal.http.ApacheHttpTransport;
import com.github.mrcritical.ironcache.internal.http.ResponseInitializer;
import com.github.mrcritical.ironcache.internal.model.CacheRequest;
import com.github.mrcritical.ironcache.internal.model.CacheResponse;
import com.github.mrcritical.ironcache.internal.model.Increment;
import com.github.mrcritical.ironcache.internal.model.IncrementCacheResponse;
import com.github.mrcritical.ironcache.internal.model.requests.CacheItemUrl;
import com.github.mrcritical.ironcache.internal.model.requests.CacheUrl;
import com.github.mrcritical.ironcache.internal.model.requests.CachesUrl;
import com.github.mrcritical.ironcache.internal.model.requests.ClearCacheUrl;
import com.github.mrcritical.ironcache.internal.model.requests.IncrementCacheItemUrl;
import com.github.mrcritical.ironcache.internal.serializers.JodaDateTimeDeserializer;
import com.github.mrcritical.ironcache.internal.serializers.JodaDateTimeSerializer;
import com.github.mrcritical.ironcache.model.Cache;
import com.github.mrcritical.ironcache.model.CacheItemRequest;
import com.github.mrcritical.ironcache.model.CachedItem;
import com.github.mrcritical.ironcache.model.HTTPException;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Strings;
import com.google.api.client.util.Throwables;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;

/**
 * A implementation of the cache client that is to handle each project
 * separately. The default hostname is "cache-aws-us-east-1". Unless you need to
 * explicitly set a different hostname you can use the
 * {@link #DefaultSimpleIronCache(String, String)} constructor.
 *
 * @author pjarrell
 *
 */
@Slf4j
@ThreadSafe
public class DefaultIronCacheProvider implements IronCacheProvider {

	/**
	 * Configures the ObjectMapper. Currently adds {@link AfterburnerModule} for
	 * more speed and Joda date/time serializer/deserializers.
	 *
	 * @param json
	 *            is the {@link ObjectMapper} to augment
	 */
	protected static ObjectMapper configure(final ObjectMapper json) {
		final SimpleModule jodaModule = new SimpleModule("Joda");
		jodaModule.addSerializer(new JodaDateTimeSerializer());
		jodaModule.addDeserializer(DateTime.class, new JodaDateTimeDeserializer());
		json.registerModule(jodaModule);

		// Increase performance even more
		json.registerModule(new AfterburnerModule());
		return json;
	}

	private static final String DEFAULT_HOST_NAME = "cache-aws-us-east-1";

	private static HttpTransport httpTransport;

	private static final JsonFactory JSON_FACTORY = new JacksonFactory();

	private static ObjectMapper objectMapper;

	@Getter
	private final String hostName;

	@Getter
	private final String projectId;

	private final HttpRequestFactory requestFactory;

	@Getter(AccessLevel.PROTECTED)
	private final String token;

	/**
	 * Create a new cache for the specified project using the default hostname
	 * {@link #DEFAULT_HOST_NAME}.
	 *
	 * @param token
	 *            is the authentication token to use
	 * @param projectId
	 *            is the project id this cache is configured for
	 */
	public DefaultIronCacheProvider(final String token, final String projectId) {
		this(token, projectId, DEFAULT_HOST_NAME);
	}

	/**
	 * Create a new cache for the specified project.
	 *
	 * @param token
	 *            is the authentication token to use
	 * @param projectId
	 *            is the project id this cache is configured for
	 * @param hostName
	 *            is the hostname for the cache server
	 *            (https://<hostName>.iron.io, only supply the <hostName> value
	 *            in this argument)
	 */
	public DefaultIronCacheProvider(final String token, final String projectId, final String hostName) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(projectId), "A valid project id is required");
		Preconditions.checkArgument(!Strings.isNullOrEmpty(token), "A valid token is required");
		Preconditions.checkArgument(!Strings.isNullOrEmpty(hostName), "A valid hostName is required");

		this.token = token;
		this.projectId = projectId;
		this.hostName = hostName;

		if (null == httpTransport) {
			DefaultIronCacheProvider.httpTransport = new ApacheHttpTransport();
		}

		if (null == objectMapper) {
			DefaultIronCacheProvider.objectMapper = configure(new ObjectMapper());
		}

		requestFactory = DefaultIronCacheProvider.httpTransport.createRequestFactory(new ResponseInitializer(token,
				JSON_FACTORY));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#clearCache(java.lang.
	 * String)
	 */
	@Override
	public void clearCache(final String name) {
		try {

			final CacheResponse response = objectMapper.readValue(
					requestFactory.buildPostRequest(new ClearCacheUrl(hostName, projectId, name), new EmptyContent())
							.execute().getContent(), CacheResponse.class);

			validate(response, "cleared");

			log.debug("Successful request to clear to cache {}", name);

		} catch (final HTTPException e) {
			if (e.getStatusCode() == 301) {
				// Swallow this since that is what happens when cleared (it
				// isn't documented in the API spec)
				return;
			}
			throw Throwables.propagate(e);

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#deleteCache(java.lang
	 * .String)
	 */
	@Override
	public void deleteCache(final String name) {
		try {

			final CacheResponse response = objectMapper.readValue(
					requestFactory.buildDeleteRequest(new CacheUrl(hostName, projectId, name)).execute().getContent(),
					CacheResponse.class);

			validate(response, "deleted");

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#deleteItem(java.lang.
	 * String, java.lang.String)
	 */
	@Override
	public void deleteItem(final String name, final String key) {
		try {

			final CacheResponse response = objectMapper.readValue(
					requestFactory.buildDeleteRequest(new CacheItemUrl(hostName, projectId, name, key)).execute()
							.getContent(), CacheResponse.class);

			validate(response, "deleted");

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#getCache(java.lang.String
	 * )
	 */
	@Override
	public Optional<Cache> getCache(final String name) {
		try {

			return Optional.fromNullable(objectMapper.readValue(
					requestFactory.buildGetRequest(new CacheUrl(hostName, projectId, name)).execute().getContent(),
					Cache.class));

		} catch (final HTTPException e) {
			if (e.getStatusCode() == 404) {
				return Optional.absent();
			}
			throw Throwables.propagate(e);

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#getItem(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Optional<CachedItem> getItem(final String name, final String key) {
		try {

			return Optional.fromNullable(objectMapper.readValue(
					requestFactory.buildGetRequest(new CacheItemUrl(hostName, projectId, name, key)).execute()
							.getContent(), CachedItem.class));

		} catch (final HTTPException e) {
			if (e.getStatusCode() == 404) {
				return Optional.absent();
			}
			throw Throwables.propagate(e);

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#incrementItem(java.lang
	 * .String, java.lang.String, int)
	 */
	@Override
	public void incrementItem(final String name, final String key, final int amount) {
		try {

			final IncrementCacheResponse response = objectMapper.readValue(
					requestFactory
							.buildPostRequest(new IncrementCacheItemUrl(hostName, projectId, name, key),
									new JsonHttpContent(JSON_FACTORY, new Increment().amount(amount))).execute()
							.getContent(), IncrementCacheResponse.class);

			// Validate an increment, presence of a value is validation
			if (null == response.getValue()) {
				String message = MoreObjects.firstNonNull(
						response.getMessage(), "Increment value returned NULL");
				throw new IllegalArgumentException(message);
			}

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.github.mrcritical.ironcache.SimpleIronCache#listCaches()
	 */
	@Override
	public List<Cache> listCaches() {
		try {

			return objectMapper.readValue(requestFactory.buildGetRequest(new CachesUrl(hostName, projectId)).execute()
					.getContent(), new TypeReference<List<Cache>>() {
			});

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.github.mrcritical.ironcache.SimpleIronCache#putItem(java.lang.String,
	 * com.github.mrcritical.ironcache.model.CacheItemRequest)
	 */
	@Override
	public void putItem(final String name, final CacheItemRequest request) {
		try {
			validate(request);
			final CacheRequest item = new CacheRequest().value(request.getValue()).cas(request.getCas())
					.expires(request.getExpireAfter());
			// .replace(request.getOnlyIfExists())
			// .add(request.getOnlyIfNotExists());

			final CacheResponse response = objectMapper.readValue(
					requestFactory
							.buildPutRequest(new CacheItemUrl(hostName, projectId, name, request.getKey()),
									new JsonHttpContent(JSON_FACTORY, item)).execute().getContent(),
					CacheResponse.class);

			validate(response, "stored");

			log.debug("Successful request to add item {} with value {} to the cache {}", request.getKey(),
					request.getValue(), name);

		} catch (final Exception e) {
			throw Throwables.propagate(e);
		}
	}

	/**
	 * Validates that the request being made is going to end up in a valid
	 * request when processed on the server. This includes:
	 *
	 *

	 *
Verifying that a key was provided that is not blank

	 *
Verifying that a NON-NULL value was provided

	 *
That {@link CacheItemRequest#getOnlyIfExists()} and
	 * {@link CacheItemRequest#getOnlyIfNotExists()} are not both set (that
	 * negate each other)

	 *
Verifying that any expiration provided is greater then 0

	 *

	 *
	 * @param request
	 *            is the request to validate
	 */
	private void validate(final CacheItemRequest request) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(request.getKey()), "A valid key must be supplied");
		Preconditions.checkArgument(null != request.getValue(),
				"A valid value must be supplied, it maybe an empty string");
		Preconditions.checkArgument(!(null != request.getOnlyIfExists() && null != request.getOnlyIfNotExists()),
				"Cannot specify both Only If Exists and Only If Not Exists. The two conditions negate each other.");
		Preconditions.checkArgument(
				null == request.getExpireAfter() || null != request.getExpireAfter() && request.getExpireAfter() > 0,
				"An expiration value must be greater then 0");
	}

	/**
	 * Validates that the keyword expected was returned. Otherwise throws an
	 * exception with the message returned included.
	 *
	 * @param response
	 *            is the response to check
	 * @param keyword
	 *            is the keyword to expected
	 */
	private void validate(final CacheResponse response, final String keyword) {
		if (!response.getMessage().toLowerCase(Locale.US).startsWith(keyword)) {
			throw new IllegalArgumentException(response.getMessage());
		}
	}

}


package org.criteria4jpa.order;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 *

 * Class to specify result ordering of {@link Criteria} instances.
 *

 *
 *

 * Instances of this class are created by calling the static factory methods
 * {@link #asc(String)} or {@link #desc(String)}. Instances can then be added to a
 * criteria by calling {@link Criteria#addOrder(Order)}.
 *

 *
 *

 * All path expressions are relative to the entity of the {@link Criteria}
 * the ordering is specified for.
 *

 *
 *
Example:

 *
 *

 * Criteria criteria = CriteriaUtils.createCriteria(entityManager, Person.class);
 * criteria.addOrder( Order.asc("age") );
 *

 *
 * @see Criteria
 * @author Christian Kaltepoth
 *
 */
public class Order {

  private String relativePath;
  private boolean ascending;

  /**
   * Instance creation only with {@link #asc(String)} and {@link #desc(String)}
   */
  private Order(String relativePath, boolean ascending) {
    this.relativePath = relativePath;
    this.ascending = ascending;
  }

  /**
   * Renders the order to a ORDER BY substring of JPQL query
   *
   * @param criteria The {@link Criteria} the order is associated with
   * @param queryBuilder The builder of the JPQL query
   * @return the generated query string
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    String absolutePath = queryBuilder.getAbsolutePath(criteria, relativePath);
    return ascending ? absolutePath : absolutePath+" DESC";
  }

  /**
   * Creates an {@link Order} instance representing an ascending ordering
   * regarding the specified persistent field. The path expression
   * has to be relative to the entity of the {@link Criteria} this ordering
   * is added to.
   *
   * @param relativePath the path expression for a persistent field
   * @return new {@link Order} instance
   */
  public static Order asc(String relativePath) {
    return new Order(relativePath, true);
  }

  /**
   * Creates an {@link Order} instance representing an descending ordering
   * regarding the specified persistent field. The path expression
   * has to be relative to the entity of the {@link Criteria} this ordering
   * is added to.
   *
   * @param relativePath the path expression for a persistent field
   * @return new {@link Order} instance
   */
  public static Order desc(String relativePath) {
    return new Order(relativePath, false);
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * 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.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/

package org.glassmaker.ui;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.text.templates.ContextTypeRegistry;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.glassmaker.ui.editor.CardContextType;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class GlassmakerUIPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.glassmaker.ui.editor"; //$NON-NLS-1$

	// The shared instance
	private static GlassmakerUIPlugin plugin;

	/**
	 * The template store for the card editor.
	 */
	private TemplateStore fTemplateStore;

	/**
	 * The template context type registry for the card editor.
	 */
	private ContextTypeRegistry fContextTypeRegistry;

	/**
	 * The constructor
	 */
	public GlassmakerUIPlugin() {
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static GlassmakerUIPlugin getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given plug-in
	 * relative path
	 *
	 * @param path
	 *            the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}

	protected void initializeImageRegistry(ImageRegistry reg) {
		super.initializeImageRegistry(reg);
		reg.put("org.glassmaker.ui.templates.text", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_text.gif")));
		reg.put("org.glassmaker.ui.templates.autoresize", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_autosize.gif")));
		reg.put("org.glassmaker.ui.templates.hybrid", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_hybrid.gif")));
		reg.put("org.glassmaker.ui.templates.hybridmosaic", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_hybridmosaic.gif")));
		reg.put("org.glassmaker.ui.templates.multipage", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_multipage.gif")));
		reg.put("org.glassmaker.ui.templates.simpleevent", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_simpleevent.gif")));
		reg.put("org.glassmaker.ui.templates.list", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_list.gif")));
		reg.put("org.glassmaker.ui.templates.knowledge", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_knowledge.gif")));
		reg.put("org.glassmaker.ui.templates.knowledgemosaic", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_knowledgemosaic.gif")));
		reg.put("org.glassmaker.ui.templates.stock", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_stock.gif")));
		reg.put("org.glassmaker.ui.templates.sports", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_sports.gif")));
		reg.put("org.glassmaker.ui.templates.flight", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_flight.gif")));
		reg.put("org.glassmaker.ui.templates.movie", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_movie.gif")));
		reg.put("org.glassmaker.ui.templates.transit", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_transit.gif")));
		reg.put("org.glassmaker.ui.templates.author", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_author.gif")));
		reg.put("org.glassmaker.ui.templates.simplemessage", ImageDescriptor.createFromURL(getBundle().getEntry("/icons/card_simplemessage.gif")));
	}

	public static void log(int severity, String msg, Throwable t) {
		plugin.getLog().log(new Status(severity, PLUGIN_ID, msg, t));
	}

	public static void logError(String msg, Exception t) {
		log(Status.ERROR, msg, t);
	}

	public static void logWarning(String msg) {
		log(Status.WARNING, msg, null);
	}

	public static void logInfo(String msg) {
		log(Status.INFO, msg, null);
	}

	public static void logWarning(String msg, Throwable t) {
		log(Status.WARNING, msg, t);
	}

	public static File getPreviewFile(String name) {

		File previewFile = null;
		URL previewPath = FileLocator.find(plugin.getBundle(), new Path("/preview"), null);
		try {
			previewFile = new File(FileLocator.resolve(previewPath).getPath()+"/"+name);
		} catch (Exception e) {
		    logError(e.getMessage(), e);
		}

		return previewFile;

	}

	/**
	 * Returns the template store for the html editor templates.
	 *
	 * @return the template store for the html editor templates
	 */
	public TemplateStore getTemplateStore() {
		if (fTemplateStore == null) {
			fTemplateStore = new ContributionTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), "org.eclipse.wst.sse.ui.custom_templates");

			try {
				fTemplateStore.load();
			} catch (IOException e) {
				logError("",e);
			}
		}
		return fTemplateStore;
	}

	/**
	 * Returns the template context type registry for the html plugin.
	 *
	 * @return the template context type registry for the html plugin
	 */
	public ContextTypeRegistry getTemplateContextRegistry() {
		if (fContextTypeRegistry == null) {
			ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry();
			registry.addContextType(CardContextType.CONTEXT_TYPE);

			fContextTypeRegistry = registry;
		}

		return fContextTypeRegistry;
	}

}


package org.criteria4jpa.criterion;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a "in" restriction.
 * It is recommended to use the static factory methods of
 * {@link Restrictions} to created instances of this class.
 *
 * @see Restrictions#in(String, Object[])
 * @see Restrictions#in(String, java.util.Collection)
 *
 * @author Christian Kaltepoth
 *
 */
public class InExpression implements Criterion {

  private final String relativePath;
  private final Object[] values;

  /**
   * Creates a "in" expression
   *
   * @param relativePath relative path of a field.
   * @param values Array of expected values
   */
  public InExpression(String relativePath, Object[] values) {
    this.relativePath = relativePath;
    this.values = values;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    // query builder
    StringBuilder builder = new StringBuilder();

    // build the basic query
    builder.append( queryBuilder.getAbsolutePath(criteria, relativePath) );
    builder.append( " IN (");

    // We must add each value as a parameter, because not all JPA
    // implementations allow lists or arrays as parameters.
    if( values != null ) {
      for( int i = 0; i < values.length; i++) {
        builder.append( queryBuilder.createPositionalParameter() );
        if( i < values.length - 1 ) {
          builder.append(',');
        }
      }
    }
    builder.append(")");

    // return result
    return builder.toString();
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#getParameterValues()
   */
  public Object[] getParameterValues() {
    return values;
  }

}


package org.criteria4jpa.criterion;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a custom JPQL restriction.
 * It is recommended to use the static factory methods of
 * {@link Restrictions} to created instances of this class.
 *
 * @see Restrictions#jpqlRestriction(String, Object...)
 *
 * @author Christian Kaltepoth
 *
 */
public class JPQLExpression implements Criterion {

  private final String jpql;
  private final Object[] values;

  /**
   * Creates a custom JPQL restriction.
   *
   * @param jpql The JPQL fragment
   * @param values The query parameters to add to the query
   */
  public JPQLExpression(String jpql, Object[] values) {
    this.jpql = jpql;
    this.values = values;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    // replace alias variable by real name
    String queryFragment =
      jpql.replace( "{alias}", queryBuilder.getRequiredAlias(criteria) );

    // process parameters
    for(int i = 1; i <= values.length; i++) {

      // create positional parameter for this value
      String paramater = queryBuilder.createPositionalParameter();

      /*
       * Replace variable with generated positional parameter.
       * Note: This kind of string processing is not very efficient,
       * because it generates a new string object in each iteration.
       * But we assume that the number of iterations will be
       * relative small, so it won't be a real problem.
       */
      queryFragment = queryFragment.replace( "{"+i+"}", paramater);

    }

    return queryFragment;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#getParameterValues()
   */
  public Object[] getParameterValues() {
    return values;
  }

}


/**
 *
 */
package com.github.mrcritical.ironcache.internal.http;

import java.io.IOException;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;

import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.util.Preconditions;

/**
 * @author Yaniv Inbar
 *
 */
public class ApacheHttpRequest extends LowLevelHttpRequest {

	private final HttpClient httpClient;

	private final HttpRequestBase request;

	public ApacheHttpRequest(HttpClient httpClient, HttpRequestBase request) {
		this.httpClient = httpClient;
		this.request = request;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.google.api.client.http.LowLevelHttpRequest#addHeader(java.lang.String
	 * , java.lang.String)
	 */
	@Override
	public void addHeader(String name, String value) throws IOException {
		request.addHeader(name, value);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.google.api.client.http.LowLevelHttpRequest#setTimeout(int, int)
	 */
	@Override
	public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
		request.setConfig(RequestConfig.custom().setSocketTimeout(readTimeout).setConnectTimeout(connectTimeout)
				.build());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.google.api.client.http.LowLevelHttpRequest#execute()
	 */
	@Override
	public LowLevelHttpResponse execute() throws IOException {
		if (getStreamingContent() != null) {
			Preconditions.checkArgument(request instanceof HttpEntityEnclosingRequest,
					"Apache HTTP client does not support %s requests with content.", request.getRequestLine()
							.getMethod());
			ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
			entity.setContentEncoding(getContentEncoding());
			entity.setContentType(getContentType());
			((HttpEntityEnclosingRequest) request).setEntity(entity);
		}
		return new ApacheHttpResponse(request, httpClient.execute(request));
	}

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * 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.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.editor;

import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;

/**
 * Manages the installation/deinstallation of global actions for multi-page editors.
 * Responsible for the redirection of global actions to the active editor.
 * Multi-page contributor replaces the contributors for the individual editors in the multi-page editor.
 */
public class CardEditorContributor extends MultiPageEditorActionBarContributor {
	private IEditorPart activeEditorPart;
	private Action sampleAction;
	/**
	 * Creates a multi-page contributor.
	 */
	public CardEditorContributor() {
		super();
		createActions();
	}
	/**
	 * Returns the action registed with the given text editor.
	 * @return IAction or null if editor is null.
	 */
	protected IAction getAction(ITextEditor editor, String actionID) {
		return (editor == null ? null : editor.getAction(actionID));
	}
	/* (non-JavaDoc)
	 * Method declared in AbstractMultiPageEditorActionBarContributor.
	 */

	public void setActivePage(IEditorPart part) {
		if (activeEditorPart == part)
			return;

		activeEditorPart = part;

		IActionBars actionBars = getActionBars();
		if (actionBars != null) {

			ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part : null;

			actionBars.setGlobalActionHandler(
				ActionFactory.DELETE.getId(),
				getAction(editor, ITextEditorActionConstants.DELETE));
			actionBars.setGlobalActionHandler(
				ActionFactory.UNDO.getId(),
				getAction(editor, ITextEditorActionConstants.UNDO));
			actionBars.setGlobalActionHandler(
				ActionFactory.REDO.getId(),
				getAction(editor, ITextEditorActionConstants.REDO));
			actionBars.setGlobalActionHandler(
				ActionFactory.CUT.getId(),
				getAction(editor, ITextEditorActionConstants.CUT));
			actionBars.setGlobalActionHandler(
				ActionFactory.COPY.getId(),
				getAction(editor, ITextEditorActionConstants.COPY));
			actionBars.setGlobalActionHandler(
				ActionFactory.PASTE.getId(),
				getAction(editor, ITextEditorActionConstants.PASTE));
			actionBars.setGlobalActionHandler(
				ActionFactory.SELECT_ALL.getId(),
				getAction(editor, ITextEditorActionConstants.SELECT_ALL));
			actionBars.setGlobalActionHandler(
				ActionFactory.FIND.getId(),
				getAction(editor, ITextEditorActionConstants.FIND));
			actionBars.setGlobalActionHandler(
				IDEActionFactory.BOOKMARK.getId(),
				getAction(editor, IDEActionFactory.BOOKMARK.getId()));
			actionBars.updateActionBars();
		}
	}
	private void createActions() {
		sampleAction = new Action() {
			public void run() {
				MessageDialog.openInformation(null, "Card Editor", "Sample Action Executed");
			}
		};
		sampleAction.setText("Sample Action");
		sampleAction.setToolTipText("Sample Action tool tip");
		sampleAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
	}
	public void contributeToMenu(IMenuManager manager) {
		IMenuManager menu = new MenuManager("Editor &Menu");
		manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu);
		menu.add(sampleAction);
	}
	public void contributeToToolBar(IToolBarManager manager) {
		manager.add(new Separator());
		manager.add(sampleAction);
	}
}


package com.github.mrcritical.ironcache.internal.serializers;

import java.io.IOException;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * Deserialize a Joda {@link LocalDateTime}.
 *
 * @author pjarrell
 *
 */
public class JodaDateTimeDeserializer extends JsonDeserializer<DateTime> {

	private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(
			DateTimeZone.UTC);

	/*
	 * (non-Javadoc)
	 *
	 * @see org.codehaus.jackson.map.JsonDeserializer#deserialize(org.codehaus
	 * .jackson .JsonParser, org.codehaus.jackson.map.DeserializationContext)
	 */
	@Override
	public DateTime deserialize(final JsonParser parser, final DeserializationContext context) throws IOException,
	JsonProcessingException {
		return formatter.parseDateTime(parser.getText());
	}

}


package org.criteria4jpa.projection;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Simple projection that refers project to the entity of the root
 * criteria of the criteria hierarchy.  It is recommended to use the static
 * factory methods of {@link Projections} to created instances of this
 * class.
 *
 * @see Projections
 *
 * @author Christian Kaltepoth
 *
 */
public class RootEntityProjection implements Projection {

  /*
   * @see org.criteria4jpa.projection.Projection#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    return queryBuilder.getRequiredAlias( queryBuilder.getRootCriteria() );
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toGroupByString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toGroupByString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    return null;
  }

}


package org.criteria4jpa.criterion;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a "is null" or "is not null" restriction.
 * It is recommended to use the static factory methods of
 * {@link Restrictions} to created instances of this class.
 *
 * @see Restrictions#isNull(String)
 * @see Restrictions#isNotNull(String)
 *
 * @author Christian Kaltepoth
 *
 */
public class IsNullExpression implements Criterion {

  private final String propertyName;
  private final boolean negate;

  /**
   * Creates a "is null" or "is not null" expression
   *
   * @param relativePath relative path of a field.
   * @param negate true to create a "is not null" instead
   *   of a "is null" expression
   */
  public IsNullExpression(String relativePath, boolean negate) {
    this.propertyName = relativePath;
    this.negate = negate;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    String path = queryBuilder.getAbsolutePath(criteria, propertyName);
    if( !negate ) {
      return path+" IS NULL";
    } else {
      return path+" IS NOT NULL";
    }
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#getParameterValues()
   */
  public Object[] getParameterValues() {
    return new Object[0];
  }

}


/*
 * ao-encoding-servlet - High performance character encoding in a Servlet environment.
 * Copyright (C) 2016  AO Industries, Inc.
 *     support@aoindustries.com
 *     7262 Bull Pen Cir
 *     Mobile, AL 36695
 *
 * This file is part of ao-encoding-servlet.
 *
 * ao-encoding-servlet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ao-encoding-servlet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with ao-encoding-servlet.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aoindustries.encoding.servlet;

import com.aoindustries.encoding.EncodingContext;
import com.aoindustries.net.UrlUtils;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;

/**
 * Encoding being done within a servlet context.
 *
 * @author  AO Industries, Inc.
 */
public class HttpServletResponseEncodingContext implements EncodingContext {

	private final HttpServletResponse response;

	public HttpServletResponseEncodingContext(HttpServletResponse response) {
		this.response = response;
	}

	/**
	 * Encodes the URL by:
	 *

	 *
Encoding the path elements with the current response character encoding.

	 *
Calling response.encodeURL()

	 *

	 * @see  UrlUtils#encodeUrlPath(java.lang.String, java.lang.String)
	 * @see  HttpServletResponse#encodeRedirectURL(java.lang.String)
	 */
	@Override
	public String encodeURL(String href) throws UnsupportedEncodingException {
		return response.encodeURL(
			UrlUtils.encodeUrlPath(
				href,
				response.getCharacterEncoding()
			)
		);
	}
}


/**
 * Copyright (C) 2012 Ness Computing, Inc.
 *
 * 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.nesscomputing.migratory.maven;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.skife.jdbi.v2.DBI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nesscomputing.migratory.Migratory;
import com.nesscomputing.migratory.MigratoryConfig;
import com.nesscomputing.migratory.MigratoryOption;

abstract class AbstractMigratoryMojo extends AbstractMojo
{
    private static final Logger CONSOLE = LoggerFactory.getLogger("console");

    protected MigratoryOption [] optionList;

    /**
     * @parameter expression="${encoding}"
     */
    private String encoding = "utf8";

    /**
     * @parameter expression="${metadata-table}"
     */
    private String metadataTable = "migratory_metadata";

    /**
     * @parameter expression="${readonly}"
     */
    private boolean readOnly = false;

    /**
     * @parameter expression="${create-personalities}"
     */
    private boolean createPersonalities = true;

    /**
     * @parameter expression="${allow-rollforward}"
     */
    private boolean allowRollforward = true;

    /**
     * @parameter expression="${allow-rollbackward}"
     */
    private boolean allowRollbackward = true;

    /**
     * @parameter expression="${db.driver}"
     */
    private String driver;

    /**
     * @parameter expression="${db.url}"
     * @required
     */
    private String url;

    /**
     * @parameter expression="${db.user}"
     */
    private String user;

    /**
     * @parameter expression="${db.password}"
     */
    private String password;

    /**
     * @parameter expression="${options}"
     */
    private String options;

    @Override
    public final void execute() throws MojoExecutionException, MojoFailureException
    {
        ConfigureLog4j.start(this);

        try {
            this.optionList = parseOptions(options);

            final Migratory migratory = new Migratory(getConfig(), createDBI());
            doExecute(migratory);
        }
        catch (Exception e) {
            CONSOLE.error("While executing Mojo {}", this.getClass().getSimpleName(), e);
            throw new MojoExecutionException("Migratory Error: ", e);
        }
        finally {
            ConfigureLog4j.stop(this);
        }
    }

    /**
     * Executes this mojo.
     */
    protected abstract void doExecute(Migratory migratory) throws Exception;

    /**
     * Creates the datasource config based on the provided parameters.
     */
    private DBI createDBI() throws Exception
    {
        if (driver != null) {
            Class.forName(driver).newInstance();
        }
        return new DBI(url, user, password);
    }

    private MigratoryConfig getConfig()
    {
        return new MigratoryConfig() {
            @Override
            public String getEncoding()
            {
                return encoding;
            }

            @Override
            public String getMetadataTableName()
            {
                return metadataTable;
            }

            @Override
            public boolean isReadOnly()
            {
                return readOnly;
            }

            @Override
            public boolean isCreatePersonalities()
            {
                return createPersonalities;
            }

            @Override
            public boolean isAllowRollForward()
            {
                return allowRollforward;
            }

            @Override
            public boolean isAllowRollBack()
            {
                return allowRollbackward;
            }
        };
    }

    protected MigratoryOption [] parseOptions(final String options)
    {
        final String [] optionList = StringUtils.stripAll(StringUtils.split(options, ","));

        if (optionList == null) {
            return new MigratoryOption[0];
        }

        final MigratoryOption [] migratoryOptions = new MigratoryOption[optionList.length];
        for (int i = 0 ; i < optionList.length; i++) {
            migratoryOptions[i] = MigratoryOption.valueOf(optionList[i].toUpperCase(Locale.ENGLISH));
        }

        CONSOLE.debug("Parsed {} into {}", options, migratoryOptions);
        return migratoryOptions;
    }

    protected List<String> parsePersonalities(final String personalityList)
    {
        final String [] personalities = StringUtils.stripAll(StringUtils.split(personalityList, ","));
        final List<String> result = personalities == null ? null : Arrays.asList(personalities);
        CONSOLE.debug("Found {} as personalities", result);
        return result;
    }

}


package com.azaptree.services.domain.entity.dao;

/*
 * #%L
 * AZAPTREE-DOMAIN-ENTITY
 * %%
 * Copyright (C) 2012 - 2013 AZAPTREE.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.
 * #L%
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;

import com.azaptree.services.domain.entity.Entity;
import com.google.common.collect.ImmutableMap;

public abstract class JDBCEntityDAOSupport<T extends Entity> implements EntityDAO<T> {

	protected final Logger log = LoggerFactory.getLogger(getClass());
	protected final JdbcTemplate jdbc;
	protected final String table;

	/**
	 * Maps entity field to table column
	 */
	protected Map<String, String> fieldColumnMappings = new HashMap<>();

	public JDBCEntityDAOSupport(final JdbcTemplate jdbc, final String table) {
		Assert.notNull(jdbc, "jdbc is required");
		Assert.hasText("table");
		this.jdbc = jdbc;
		this.table = table;
		initFieldColumnMappings();
		buildImmutableFieldColumnMappings();
	}

	/**
	 * Appends LIMIT and OFFSET for POSTGRESQL SQL queries
	 *
	 *
		  SELECT select_list
			FROM table_expression
			[ ORDER BY ... ]
			[ LIMIT { number | ALL } ] [ OFFSET number ]

	 *
	 * @param sql
	 * @param page
	 */
	protected void appendLimitAndOffSet(final StringBuilder sql, final Page page) {
		sql.append(" LIMIT ").append(page.getPageSize()).append(" OFFSET ").append(page.getOffset());
	}

	protected void appendOrderBy(final StringBuilder sql, final SortField... fields) {
		if (ArrayUtils.isNotEmpty(fields)) {
			sql.append(" ORDER BY ");
			SortField f;
			for (int i = 0; i < fields.length;) {
				f = fields[i];
				final String column = fieldColumnMappings.get(f.getFieldName());
				Assert.notNull(column, "Invalid field : " + f.getFieldName());
				sql.append(column).append(' ');
				if (!f.isAscending()) {
					sql.append("DESC");
				}
				if (++i < fields.length) {
					sql.append(",");
				}
			}
		}
	}

	protected void buildImmutableFieldColumnMappings() {
		fieldColumnMappings = ImmutableMap.<String, String> builder().putAll(fieldColumnMappings).build();
	}

	protected void check(final Page page, final SortField... fields) {
		Assert.notNull(page, "page is required");
		checkEntityField(fields);
	}

	protected void checkEntityField(final SortField... field) {
		if (ArrayUtils.isEmpty(field)) {
			return;
		}
		for (final SortField f : field) {
			Assert.isTrue(fieldColumnMappings.containsKey(f.getFieldName()), "Invalid field: " + field);
		}
	}

	@Override
	public boolean delete(final UUID id) {
		Assert.notNull(id, "id is required");
		final String sql = new StringBuilder("delete from ").append(table).append(" where entity_id = ?").toString();
		return jdbc.update(sql, id) > 0;
	}

	@Override
	public boolean exists(final UUID id) {
		Assert.notNull(id, "id is required");
		final String sql = new StringBuilder("select 1 from ").append(table).append(" where entity_id = ?").toString();
		final Object[] args = { id };
		try {
			jdbc.queryForInt(sql, args);
			return true;
		} catch (final IncorrectResultSizeDataAccessException e) {
			return false;
		}
	}

	@Override
	public SearchResults<T> findAll(final Page page, final SortField... sort) {
		check(page, sort);
		final StringBuilder sql = new StringBuilder("select * from t_subject");
		appendOrderBy(sql, sort);
		appendLimitAndOffSet(sql, page);

		final long totalCount = getTotalCount();
		final List<T> data = jdbc.query(sql.toString(), getRowMapper());

		return new SearchResults<>(page, totalCount, data);
	}

	@Override
	public T findById(final UUID id) {
		Assert.notNull(id, "id is required");
		final String sql = new StringBuilder("select * from ").append(table).append(" where entity_id = ?").toString();
		final Object[] args = { id };
		try {
			return jdbc.queryForObject(sql, args, getRowMapper());
		} catch (final IncorrectResultSizeDataAccessException e) {
			return null;
		}
	}

	@Override
	public Set<String> getEntityFields() {
		return fieldColumnMappings.keySet();
	}

	protected abstract RowMapper<T> getRowMapper();

	@Override
	public long getTotalCount() {
		return jdbc.queryForLong(new StringBuilder("select count(*) from ").append(table).toString());
	}

	/**
	 *
	 * EntityId -> entity_id
	 *
	 */
	protected void initFieldColumnMappings() {
		fieldColumnMappings.put("EntityId", "entity_id");
	}
}


package org.sbolstandard.examples;

import java.net.URI;

import javax.xml.namespace.QName;

import org.sbolstandard.core.datatree.DocumentRoot;
import org.sbolstandard.core.datatree.NamespaceBinding;
import org.sbolstandard.core.datatree.NestedDocument;
import org.sbolstandard.core.datatree.TopLevelDocument;
import org.sbolstandard.core.io.rdf.RdfTerms;
import org.sbolstandard.core.schema.SchemaCatalog;

import static org.sbolstandard.core.datatree.Datatree.*;
import static org.sbolstandard.core.schema.Schema.*;

/**
 * Provides methods to create example Datatrees.

 * @author goksel
 *
 */
public class DataTreeCreator {

  private static final NamespaceBinding partsRegistry = NamespaceBinding("http://partsregistry.org/", "pr");
  private static final NamespaceBinding sbolExample = NamespaceBinding("http://sbolstandard.org/example#", "example");
  private static final NamespaceBinding obo = NamespaceBinding("http://purl.obolibrary.org/obo/", "obo");
  private static final NamespaceBinding utah = NamespaceBinding("http://www.async.ece.utah.edu/", "utah");

//  private static String dctermsNS = "http://purl.org/dc/terms/";
//  private static String dctermsPF = "dcterms";

  /**
   * Creates an example {@link DocumentRoot} object with data from the SBOL2.0 proposed data model.
   * Included SBOL objects are Module, Interaction, Participation, ComponentInstantiation and Model.
   * @return {@link DocumentRoot}
   */
  public static DocumentRoot<QName> makeSBOL2Document()
  {
    NestedDocument<QName> instantiationLacI=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,
            sbolExample.namespacedUri("module_LacI_inverter/LacI_instantiation"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "LacI")
            ));

    NestedDocument<QName> instantiationIPTG=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,

            sbolExample.namespacedUri("module_LacI_inverter/IPTG"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "IPTG")
            ));

    NestedDocument<QName> instantiationIPTGLacI=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,
            sbolExample.namespacedUri("module_LacI_inverter/IPTG_LacI_complex"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "IPTG LacI complex")
            ));
    NestedDocument<QName> instantiationpLac=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,

            sbolExample.namespacedUri("module_LacI_inverter/pLac_instantiation"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "pLac promoter")
            ));
    NestedDocument<QName> instantiationcTetR=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,

            sbolExample.namespacedUri("module_LacI_inverter/cTetR_instantiation"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "cTetR")
            ));
    NestedDocument<QName> instantiationTetR=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,

            sbolExample.namespacedUri("module_LacI_inverter/TetR_instantiation"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "TetR")
            ));

    NestedDocument<QName> interactionIPTGBinding=NestedDocument(
            Sbol2Terms.module.interaction,

            sbolExample.namespacedUri("module_LacI_inverter/interaction/IPTG_binding"),

            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "IPTG Binding"),
                    NamedProperty(RdfTerms.rdfType, URI.create("http://purl.obolibrary.org/obo/non_covalent_binding")),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/IPTG_Binding/LacI_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role,URI.create("http://purl.obolibrary.org/obo/reactant")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationLacI.getIdentity())
                                    )
                            )
                    ),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/IPTG_Binding/IPTGLacI_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role, URI.create("http://purl.obolibrary.org/obo/product")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationIPTGLacI.getIdentity())
                                    )
                            )),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/IPTG_Binding/IPTG_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role, URI.create("http://purl.obolibrary.org/obo/reactant")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationIPTG.getIdentity())
                                    )
                            )
                    )
            )
    );

    NestedDocument<QName> interactionLacIRepression=NestedDocument(
            Sbol2Terms.module.interaction,
            sbolExample.namespacedUri("module_LacI_inverter/interaction/LacI_repression"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "LacI Repression"),
                    NamedProperty(RdfTerms.rdfType, URI.create("http://purl.obolibrary.org/obo/repression")),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/LacI_repression/LacI"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role,URI.create("http://purl.obolibrary.org/obo/repressor")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationLacI.getIdentity())
                                    )
                            )
                    ),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/LacI_repression/pLac"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role, URI.create("http://purl.obolibrary.org/obo/repressed")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationpLac.getIdentity())
                                    )
                            )
                    )
            )
    );

    NestedDocument<QName> interactionTetRTranscriptionTranslation=NestedDocument(
            Sbol2Terms.module.interaction,

            sbolExample.namespacedUri("module_LacI_inverter/interaction/TetR_transcription_translation"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "TetR Transcription Translation"),
                    NamedProperty(RdfTerms.rdfType, URI.create("http://purl.obolibrary.org/obo/genetic_production")),
                    NamedProperty(RdfTerms.rdfType, URI.create("http://made.up.terms.org/unicorns")),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/TetR_transcription_translation/TetR_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role,URI.create("http://purl.obolibrary.org/obo/product")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationTetR.getIdentity())
                                    )
                            )
                    ),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/TetR_transcription_translation/cTetR_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role, URI.create("http://purl.obolibrary.org/obo/transcribed")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationcTetR.getIdentity())
                                    )
                            )
                    ),
                    NamedProperty(Sbol2Terms.module.hasParticipation,
                            NestedDocument(
                                    Sbol2Terms.module.participation,
                                    partsRegistry.namespacedUri("module_LacI_inverter/interaction/TetR_transcription_translation/pLac_participation"),
                                    NamedProperties(
                                            NamedProperty(Sbol2Terms.module.role, URI.create("http://purl.obolibrary.org/obo/modifier")),
                                            NamedProperty(Sbol2Terms.module.participant, instantiationpLac.getIdentity())
                                    )
                            )
                    )
            )
    );

    TopLevelDocument<QName> modelLacIInverter=TopLevelDocument(
            NamespaceBindings(utah),
            Sbol2Terms.model.model,
            sbolExample.namespacedUri("model/LacI_inverter"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "LacI Inverter Model"),
                    NamedProperty(Sbol2Terms.model.source,URI.create("http://www.async.ece.utah.edu/LacI_Inverter.xml")),
                    NamedProperty(Sbol2Terms.model.language,"SBML"),
                    NamedProperty(Sbol2Terms.model.framework,"ODE"),
                    NamedProperty(Sbol2Terms.model.role,"simulation")
            )
    );

    TopLevelDocument<QName> moduleLacIInverter=TopLevelDocument(
            Sbol2Terms.module.module,
            sbolExample.namespacedUri("module/LacI_inverter"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "LacI Inverter"),
                    NamedProperty(Sbol2Terms.module.hasInteraction, interactionIPTGBinding),
                    NamedProperty(Sbol2Terms.module.hasInteraction, interactionLacIRepression),
                    NamedProperty(Sbol2Terms.module.hasInteraction, interactionTetRTranscriptionTranslation),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationLacI),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationIPTG),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationIPTGLacI),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationpLac),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationcTetR),
                    NamedProperty(Sbol2Terms.instantiation.hasComponentInstantiation, instantiationTetR),
                    NamedProperty(Sbol2Terms.module.hasModel,modelLacIInverter.getIdentity())
            )
    );

    return DocumentRoot(
            NamespaceBindings(RdfTerms.rdf, SbolTerms.sbol2, partsRegistry, sbolExample, obo),
            TopLevelDocuments(moduleLacIInverter,modelLacIInverter));
  }

  /**
   * Creates an example {@link DocumentRoot} object with data from the SBOL2.0 proposed data model.
   * Included SBOL objects from the data model are SequenceComponent, ComponentInstantiation, SequenceAnnotation and SequenceComponent.
   * @return {@link DocumentRoot}
   */
  public static DocumentRoot<QName> makeSBOL2SequenceComponent()
  {
    TopLevelDocument<QName> pLac=TopLevelDocument(
            Sbol2Terms.component.sequenceComponent,
            sbolExample.namespacedUri("sequenceComponent/pLac"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "pLac"),
                    NamedProperty(Sbol2Terms.documented.displayId, "pLac"),
                    NamedProperty(RdfTerms.rdfType, URI.create("DNA")),
                    NamedProperty(Sbol2Terms.component.sequenceType, URI.create("http://purl.org/obo/owl/SO#SO_0000167"))
            ));

    NestedDocument<QName> instantiationpLac=NestedDocument(
            Sbol2Terms.instantiation.componentInstantiation,
            sbolExample.namespacedUri("sequenceComponent/pLac/instantiation"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "pLac"),
                    NamedProperty(Sbol2Terms.component.component, pLac.getIdentity())
            ));

    NestedDocument<QName> pLacAnnotation=NestedDocument(
            Sbol2Terms.component.sequenceAnnotation,
            sbolExample.namespacedUri("sequenceComponent/UU_002/pLac_annotation"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.component.orientation, "inline"),
                    NamedProperty(Sbol2Terms.instantiation.subComponentInstantiation, instantiationpLac)
            ));

    TopLevelDocument<QName> lacIRepressibleGeneSequence=TopLevelDocument(
            Sbol2Terms.component.sequence,
            sbolExample.namespacedUri("sequenceComponent/UU_002/sequence"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.component.elements, "atg")
            ));

    TopLevelDocument<QName> lacIRepressibleGene=TopLevelDocument(
            Sbol2Terms.component.sequenceComponent,
            sbolExample.namespacedUri("sequenceComponent/UU_002"),
            NamedProperties(
                    NamedProperty(Sbol2Terms.documented.name, "LacI Repressible Gene"),
                    NamedProperty(Sbol2Terms.documented.displayId, "UU_002"),
                    NamedProperty(RdfTerms.rdfType, URI.create("DNA")),
                    NamedProperty(Sbol2Terms.component.sequenceType, URI.create("http://purl.org/obo/owl/SO#SO_0000774")),
                    NamedProperty(Sbol2Terms.component.annotation, pLacAnnotation),
                    NamedProperty(Sbol2Terms.component.hasSequence, lacIRepressibleGeneSequence.getIdentity())
            ));

    return DocumentRoot(
            NamespaceBindings(SbolTerms.sbol2),
            TopLevelDocuments(lacIRepressibleGene,pLac,lacIRepressibleGeneSequence)
    );
  }

  /**
   * Creates an example {@link DocumentRoot} object with data from the SBOL1.1 data model.
   * Included SBOL objects are DnaComponent, SequenceAnnotation and DnaSequence.
   * @return {@link DocumentRoot}
   */
  public static DocumentRoot<QName> makeDocument()
  {
    return DocumentRoot(
            NamespaceBindings(SbolTerms.sbol2),
            TopLevelDocuments(
                    TopLevelDocument(
                            SbolTerms.dnaComponent,
                            partsRegistry.namespacedUri("Part:BBa_I0462"),
                            NamedProperties(
                                    NamedProperty(SbolTerms.name, "I0462"),
                                    NamedProperty(SbolTerms.description, "LuxR protein generator"),
                                    NamedProperty(SbolTerms.dnaSequence, partsRegistry.namespacedUri("Part:BBa_I0462/sequence")),
                                    NamedProperty(
                                            SbolTerms.sequenceAnnotation,
                                            NestedDocument(
                                                    SbolTerms.annotation,
                                                    partsRegistry.namespacedUri("Part:BBa_I0462/anot/1234567"),
                                                    NamedProperties(
                                                            NamedProperty(SbolTerms.bioStart, 1),
                                                            NamedProperty(SbolTerms.bioEnd, 12),
                                                            NamedProperty(SbolTerms.strand, "+"),
                                                            NamedProperty(
                                                                    SbolTerms.subComponent,
                                                                    partsRegistry.namespacedUri("Part:BBa_B0034")
                                                            )
                                                    )
                                            )
                                    ),
                                    NamedProperty(
                                            SbolTerms.annotation,
                                            NestedDocument(
                                                    SbolTerms.sequenceAnnotation,
                                                    partsRegistry.namespacedUri("Part:BBa_I0462/annotation/2345678"),
                                                    NamedProperties(
                                                            NamedProperty(SbolTerms.bioStart, 19),
                                                            NamedProperty(SbolTerms.bioEnd, 774),
                                                            NamedProperty(SbolTerms.subComponent, partsRegistry.namespacedUri("Part:BBa_C0062"))
                                                    )
                                            )
                                    )
                            )
                    ),
                    TopLevelDocument(
                            SbolTerms.dnaSequence,
                            partsRegistry.namespacedUri("Part:BBa_I0462/sequence"),
                            NamedProperties(NamedProperty(
                                    SbolTerms.nucleotides,
                                    "aaagaggagaaatactagatgaaaaacataaatgccgacgacacatacagaataattaataaaattaaagcttgtagaagcaataatgatattaatcaatgcttatctgatatgactaaaatggtacattgtgaatattatttactcgcgatcatttatcctcattctatggttaaatctgatatttcaatcctagataattaccctaaaaaatggaggcaatattatgatgacgctaatttaataaaatatgatcctatagtagattattctaactccaatcattcaccaattaattggaatatatttgaaaacaatgctgtaaataaaaaatctccaaatgtaattaaagaagcgaaaacatcaggtcttatcactgggtttagtttccctattcatacggctaacaatggcttcggaatgcttagttttgcacattcagaaaaagacaactatatagatagtttatttttacatgcgtgtatgaacataccattaattgttccttctctagttgataattatcgaaaaataaatatagcaaataataaatcaaacaacgatttaaccaaaagagaaaaagaatgtttagcgtgggcatgcgaaggaaaaagctcttgggatatttcaaaaatattaggttgcagtgagcgtactgtcactttccatttaaccaatgcgcaaatgaaactcaatacaacaaaccgctgccaaagtatttctaaagcaattttaacaggagcaattgattgcccatactttaaaaattaataacactgatagtgctagtgtagatcactactagagccaggcatcaaataaaacgaaaggctcagtcgaaagactgggcctttcgttttatctgttgtttgtcggtgaacgctctctactagagtcacactggctcaccttcgggtgggcctttctgcgtttata"
                            ))
                    ),

                    TopLevelDocument(
                            SbolTerms.dnaComponent,
                            partsRegistry.namespacedUri("Part:BBa_B0034"),
                            NamedProperties(
                                    NamedProperty(SbolTerms.name, "I0462"),
                                    NamedProperty(SbolTerms.displayId, "BBa_B0034"),
                                    NamedProperty(RdfTerms.rdfType, URI.create("http://purl.obolibrary.org/obo/SO_0000139"))
                            )),
                    TopLevelDocument(
                            SbolTerms.dnaComponent,
                            partsRegistry.namespacedUri("Part:BBa_C0062"),
                            NamedProperties(
                                    NamedProperty(SbolTerms.name, "luxR"),
                                    NamedProperty(SbolTerms.displayId, "BBa_C0062"),
                                    NamedProperty(RdfTerms.rdfType, URI.create("http://purl.obolibrary.org/obo/SO_0000316"))
                            )
                    )
            ));
  }

  /**
   * Creates a {@link SchemaCatalog} for the SBOL20 core objects
   * @return {@link SchemaCatalog}
   */
  public static SchemaCatalog makeCoreSchemaCatalog()
  {
    return SchemaCatalog(
            Sbol2Terms.sbol2.namespacedUri("/schemaexample/core"),
            ImportedSchemas(),
            DocumentSchemas(
                    DocumentSchema(
                            Sbol2Terms.sbol2.namespacedUri("/schema/identified"),
                            Extends(),
                            IdentifierSchemas(),
                            TypeSchemas(),
                            PropertySchemas()
                    ),
                    DocumentSchema(
                            Sbol2Terms.sbol2.namespacedUri("/schema/documented"),
                            Extends(Sbol2Terms.sbol2.namespacedUri("/schema/identified")),
                            IdentifierSchemas(),
                            TypeSchemas(),
                            PropertySchemas(
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.documented.displayId)
                                            ),
                                            cardinality.required,
                                            PropertyValueSchemas(propertyType.string)
                                    ),
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.documented.name)
                                            ),
                                            cardinality.optional,
                                            PropertyValueSchemas(propertyType.string)
                                    ),
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.documented.description)
                                            ),
                                            cardinality.optional,
                                            PropertyValueSchemas(propertyType.string)
                                    )
                            )
                    )
            )
    );
  }

  /**
   * Creates a {@link SchemaCatalog} for the SBOL20 instantiation objects
   * @return {@link SchemaCatalog}
   */
  public static SchemaCatalog makeInstantiationSchemaCatalog()
  {
    return SchemaCatalog(
            Sbol2Terms.sbol2.namespacedUri("/schemaexample/instantiation"),
            ImportedSchemas(),
            DocumentSchemas(
                    DocumentSchema(
                            Sbol2Terms.sbol2.namespacedUri("/schema/component_instantiation"),
                            Extends(),
                            IdentifierSchemas(),
                            TypeSchemas(
                                    TypeSchema(Sbol2Terms.instantiation.componentInstantiation)
                            ),
                            PropertySchemas(
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.instantiation.hasComponentInstantiation)
                                            ),
                                            cardinality.required,
                                            PropertyValueSchemas(ReferenceValue(Sbol2Terms.sbol2.namespacedUri("/schema/sequence_component")))
                                    )
                            )
                    )
            )
    );
  }

  /**
   * Creates a {@link SchemaCatalog} for the SBOL20 component objects
   * @return {@link SchemaCatalog}
   */
  public static SchemaCatalog makeComponentSchemaCatalog()
  {
    return SchemaCatalog(
            Sbol2Terms.sbol2.namespacedUri("/schemaexample/component"),
            ImportedSchemas(
                    Sbol2Terms.sbol2.namespacedUri("/schema/core"),
                    Sbol2Terms.sbol2.namespacedUri("/schema/instantiation")
            ),
            DocumentSchemas(
                    DocumentSchema(
                            Sbol2Terms.sbol2.namespacedUri("/schema/sequence"),
                            Extends(),
                            IdentifierSchemas(),
                            TypeSchemas(
                                    TypeSchema(Sbol2Terms.component.sequence)
                            ),
                            PropertySchemas(
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.component.elements)
                                            ),
                                            cardinality.required,
                                            PropertyValueSchemas(propertyType.string)
                                    )
                            )
                    ),
                    DocumentSchema(
                            Sbol2Terms.sbol2.namespacedUri("/schema/sequence_component"),
                            Extends(Sbol2Terms.sbol2.namespacedUri("/schema/documented")),
                            IdentifierSchemas(),
                            TypeSchemas(
                                    TypeSchema(Sbol2Terms.component.sequenceComponent)
                            ),
                            PropertySchemas(
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.component.hasSequence)
                                            ),
                                            cardinality.optional,
                                            PropertyValueSchemas(ReferenceValue(Sbol2Terms.sbol2.namespacedUri("/schema/sequence")))
                                    ),
                                    PropertySchema(
                                            TypeSchemas(
                                                    TypeSchema(Sbol2Terms.component.annotation)
                                            ),
                                            cardinality.many,
                                            PropertyValueSchemas(
                                                    DocumentValue(
                                                            DocumentSchema(
                                                                    Sbol2Terms.sbol2.namespacedUri("/schema/sequence_annotation"),
                                                                    Extends(Sbol2Terms.sbol2.namespacedUri("/schema/documented")),
                                                                    IdentifierSchemas(),
                                                                    TypeSchemas(
                                                                            TypeSchema(Sbol2Terms.component.sequenceComponent)
                                                                    ),
                                                                    PropertySchemas(
                                                                            PropertySchema(
                                                                                TypeSchemas(
                                                                                TypeSchema(Sbol2Terms.instantiation.subComponentInstantiation)
                                                                                ),
                                                                                cardinality.required,
                                                                                PropertyValueSchemas(ReferenceValue(Sbol2Terms.sbol2.namespacedUri("/schema/component_instantiation")))
                                                                            ),
                                                                            PropertySchema(
                                                                                TypeSchemas(
                                                                                TypeSchema(Sbol2Terms.component.orientation)
                                                                                ),
                                                                                cardinality.required,
                                                                                PropertyValueSchemas(propertyType.oneOf("inline","reverse_compliment"))
                                                                            ),
                                                                            PropertySchema(
                                                                                TypeSchemas(
                                                                                TypeSchema(Sbol2Terms.component.start)
                                                                                ),
                                                                                cardinality.optional,
                                                                                PropertyValueSchemas(propertyType.integer)
                                                                            ),
                                                                            PropertySchema(
                                                                                TypeSchemas(
                                                                                TypeSchema(Sbol2Terms.component.end)
                                                                                ),
                                                                                cardinality.optional,
                                                                                PropertyValueSchemas(propertyType.integer)
                                                                            )
                                                                    )
                                                            )
                                                    )
                                            )
                                    )

                            )

                    )
            )
    );
  }
}


package hudson.plugins.dry;

import hudson.maven.AggregatableAction;
import hudson.maven.MavenAggregatedReport;
import hudson.maven.MavenBuild;
import hudson.maven.MavenModule;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Action;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.core.HealthDescriptor;
import hudson.plugins.analysis.core.ParserResult;

import java.util.List;
import java.util.Map;

/**
 * A {@link DryResultAction} for native maven jobs. This action
 * additionally provides result aggregation for sub-modules and for the main
 * project.
 *
 * @author Ulli Hafner
 * @deprecated not used anymore
 */
@Deprecated
public class MavenDryResultAction extends DryResultAction implements AggregatableAction, MavenAggregatedReport {
    /** The default encoding to be used when reading and parsing files. */
    private final String defaultEncoding;

    /**
     * Creates a new instance of MavenPmdResultAction.
     *
     * @param owner
     *            the associated build of this action
     * @param healthDescriptor
     *            health descriptor to use
     * @param defaultEncoding
     *            the default encoding to be used when reading and parsing files
     * @param result
     *            the result in this build
     */
    public MavenDryResultAction(final AbstractBuild<?, ?> owner, final HealthDescriptor healthDescriptor,
            final String defaultEncoding, final DryResult result) {
        super(owner, healthDescriptor, result);
        this.defaultEncoding = defaultEncoding;
    }

    /** {@inheritDoc} */
    public MavenAggregatedReport createAggregatedAction(final MavenModuleSetBuild build, final Map<MavenModule, List<MavenBuild>> moduleBuilds) {
        return new MavenDryResultAction(build, getHealthDescriptor(), defaultEncoding,
                new DryResult(build, defaultEncoding, new ParserResult(), false));
    }

    /** {@inheritDoc} */
    public Action getProjectAction(final MavenModuleSet moduleSet) {
        return new DryProjectAction(moduleSet);
    }

    /** {@inheritDoc} */
    public Class<? extends AggregatableAction> getIndividualActionType() {
        return getClass();
    }

    /**
     * Called whenever a new module build is completed, to update the aggregated
     * report. When multiple builds complete simultaneously, Hudson serializes
     * the execution of this method, so this method needs not be
     * concurrency-safe.
     *
     * @param moduleBuilds
     *            Same as <tt>MavenModuleSet.getModuleBuilds()</tt> but provided
     *            for convenience and efficiency.
     * @param newBuild
     *            Newly completed build.
     */
    public void update(final Map<MavenModule, List<MavenBuild>> moduleBuilds, final MavenBuild newBuild) {
        // not used anymore
    }

    /** Backward compatibility. @deprecated */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings("UUF")
    @SuppressWarnings("PMD")
    @Deprecated
    private transient String height;
}