public class CompositeURILastModifiedResolver implements
		URILastModifiedResolver {

	private final Map<String, URILastModifiedResolver> resolvers = new HashMap<String, URILastModifiedResolver>(
			10);

	private final Log logger;

	public CompositeURILastModifiedResolver(Log logger) {
		this.logger = Validate.notNull(logger);
		addResolvers(new FileURILastModifiedResolver(logger),
				new JarURILastModifiedResolver(logger, this),
				new HttpURILastModifiedResolver(logger),
				new HttpsURILastModifiedResolver(logger));
	}

	public CompositeURILastModifiedResolver() {
		this(NullLog.INSTANCE);
	}

	private Log getLogger() {
		return logger;
	}

	private void addResolvers(SchemeAwareURILastModifiedResolver... resolvers) {
		Validate.noNullElements(resolvers);
		for (final SchemeAwareURILastModifiedResolver resolver : resolvers) {
			this.resolvers.put(resolver.getScheme().toLowerCase(), resolver);
		}
	}

	private URILastModifiedResolver getResolver(String scheme) {
		return this.resolvers.get(scheme);
	}

	@Override
	public Long getLastModified(URI uri) {
		final String scheme = uri.getScheme();
		if (scheme == null) {
			getLogger()
					.error(MessageFormat.format(
							"URI [{0}] does not provide the scheme part.", uri));
		}
		final URILastModifiedResolver resolver = getResolver(scheme);
		if (resolver == null) {

			getLogger()
					.error(MessageFormat
							.format("Could not resolve the last modification of the URI [{0}] with the scheme [{1}].",
									uri, scheme));
		} else {
			return resolver.getLastModified(uri);
		}
		getLogger()
				.warn(MessageFormat
						.format("Last modification of the URI [{0}] is not known.",
								uri));
		return null;
	}
} public class FileURILastModifiedResolver extends
		AbstractSchemeAwareURILastModifiedResolver {

	public static final String SCHEME = "file";

	public FileURILastModifiedResolver(Log logger) {
		super(SCHEME, logger);
	}

	@Override
	protected Long getLastModifiedForScheme(final URI uri) {
		try {
			final File file = new File(uri);
			if (file.exists()) {
				long lastModified = file.lastModified();
				if (lastModified != 0) {
					getLogger()
							.debug(MessageFormat
									.format("Last modification timestamp of the file URI [{0}] is [{1,date,yyyy-MM-dd HH:mm:ss.SSS}].",
											uri, lastModified));
					return lastModified;
				} else {
					getLogger()
							.error(MessageFormat
									.format("Could not retrieve the last modification of the file [{0}] .",
											file.getAbsolutePath()));
				}
			} else {
				getLogger().error(
						MessageFormat.format("File [{0}] does not exist.",
								file.getAbsolutePath()));
			}
		} catch (Exception ex) {
			getLogger()
					.error(MessageFormat.format(
							"Could not retrieve the last modification of the URI [{0}] .",
							uri), ex);
		}
		getLogger()
				.warn(MessageFormat
						.format("Last modification of the URI [{0}] is not known.",
								uri));
		return null;
	}
} public interface URILastModifiedResolver {

	/**
	 * Finds out the last modification date for an URI.
	 * 
	 * @param uri
	 *            URI to find out the last modification date for.
	 * @return Last modification date or <code>null</code> if unknown.
	 */
	public Long getLastModified(URI uri);
} public class MavenCatalogResolver extends
		com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver {

	public static final String URI_SCHEME_MAVEN = "maven";
	private final DependencyResourceResolver dependencyResourceResolver;
	private final CatalogManager catalogManager;
	private final Log log;

	public MavenCatalogResolver(CatalogManager catalogManager,
			DependencyResourceResolver dependencyResourceResolver) {
		this(catalogManager, dependencyResourceResolver, NullLog.INSTANCE);
	}

	public MavenCatalogResolver(CatalogManager catalogManager,
			DependencyResourceResolver dependencyResourceResolver, Log log) {
		super(catalogManager);
		this.catalogManager = catalogManager;
		if (dependencyResourceResolver == null) {
			throw new IllegalArgumentException(
					"Dependency resource resolver must not be null.");
		}
		this.dependencyResourceResolver = dependencyResourceResolver;
		this.log = log != null ? log : NullLog.INSTANCE;
	}

	protected CatalogManager getCatalogManager() {
		return catalogManager;
	}

	protected Log getLog() {
		return log;
	}

	@Override
	public String getResolvedEntity(String publicId, String systemId) {
		getLog().debug(
				MessageFormat.format(
						"Resolving publicId [{0}], systemId [{1}].", publicId,
						systemId));
		final String superResolvedEntity = super.getResolvedEntity(publicId,
				systemId);
		getLog().debug(
				MessageFormat
						.format("Parent resolver has resolved publicId [{0}], systemId [{1}] to [{2}].",
								publicId, systemId, superResolvedEntity));
		if (superResolvedEntity != null) {
			systemId = superResolvedEntity;
		}

		if (systemId == null) {
			return null;
		}

		try {
			final URI uri = new URI(systemId);
			if (URI_SCHEME_MAVEN.equals(uri.getScheme())) {
				getLog().debug(
						MessageFormat
								.format("Resolving systemId [{1}] as Maven dependency resource.",
										publicId, systemId));
				final String schemeSpecificPart = uri.getSchemeSpecificPart();
				try {
					final DependencyResource dependencyResource = DependencyResource
							.valueOf(schemeSpecificPart);
					try {
						final URL url = dependencyResourceResolver
								.resolveDependencyResource(dependencyResource);
						String resolved = url.toString();
						getLog().debug(
								MessageFormat.format(
										"Resolved systemId [{1}] to [{2}].",
										publicId, systemId, resolved));
						return resolved;
					} catch (Exception ex) {
						getLog().error(
								MessageFormat
										.format("Error resolving dependency resource [{0}].",
												dependencyResource));
					}
				} catch (IllegalArgumentException iaex) {
					getLog().error(
							MessageFormat
									.format("Error parsing dependency descriptor [{0}].",
											schemeSpecificPart));

				}
				getLog().error(
						MessageFormat
								.format("Failed to resolve systemId [{1}] as dependency resource. "
										+ "Returning parent resolver result [{2}].",
										publicId, systemId, superResolvedEntity));
				return superResolvedEntity;
			} else {
				getLog().debug(
						MessageFormat
								.format("SystemId [{1}] is not a Maven dependency resource URI. "
										+ "Returning parent resolver result [{2}].",
										publicId, systemId, superResolvedEntity));
				return superResolvedEntity;
			}
		} catch (URISyntaxException urisex) {
			getLog().debug(
					MessageFormat
							.format("Coul not parse the systemId [{1}] as URI. "
									+ "Returning parent resolver result [{2}].",
									publicId, systemId, superResolvedEntity));
			return superResolvedEntity;
		}
	}

} public class ReResolvingEntityResolverWrapper implements EntityResolver {

	private final EntityResolver entityResolver;

	public ReResolvingEntityResolverWrapper(EntityResolver entityResolver) {
		if (entityResolver == null) {
			throw new IllegalArgumentException(
					"Provided entity resolver must not be null.");
		}
		this.entityResolver = entityResolver;
	}

	@Override
	public InputSource resolveEntity(String publicId, String systemId)
			throws SAXException, IOException {
		// System.out.println(MessageFormat.format("Resolving publicId [{0}], systemId [{1}].",
		// publicId, systemId));
		final InputSource resolvedInputSource = this.entityResolver
				.resolveEntity(publicId, systemId);
		if (resolvedInputSource == null) {
			// System.out.println("Resolution result is null.");
			return null;
		} else {
			// System.out.println(MessageFormat.format(
			// "Resolved to publicId [{0}], systemId [{1}].",
			// resolvedInputSource.getPublicId(),
			// resolvedInputSource.getSystemId()));
			final String pId = publicId != null ? publicId
					: resolvedInputSource.getPublicId();
			final String sId = systemId != null ? systemId
					: resolvedInputSource.getSystemId();
			return new ReResolvingInputSourceWrapper(this.entityResolver,
					resolvedInputSource, pId, sId);
		}
	}
} public class ArtifactUtils {

	private ArtifactUtils() {

	}

	public static Collection<Artifact> resolveTransitively(
			final ArtifactFactory artifactFactory,
			final ArtifactResolver artifactResolver,
			final ArtifactRepository localRepository,
			final ArtifactMetadataSource artifactMetadataSource,
			final Dependency[] dependencies, final MavenProject project)
			throws InvalidDependencyVersionException,
			ArtifactResolutionException, ArtifactNotFoundException {
		if (dependencies == null) {
			return Collections.emptyList();
		}

		@SuppressWarnings("unchecked")
		final Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(
				artifactFactory, Arrays.asList(dependencies), "runtime", null,
				project);

		final ArtifactResolutionResult artifactResolutionResult = artifactResolver
				.resolveTransitively(artifacts,

				project.getArtifact(),

				project.getRemoteArtifactRepositories(), localRepository,
						artifactMetadataSource);

		@SuppressWarnings("unchecked")
		final Set<Artifact> resolvedArtifacts = artifactResolutionResult
				.getArtifacts();

		return resolvedArtifacts;
	}

	public static Collection<Artifact> resolve(
			final ArtifactFactory artifactFactory,
			final ArtifactResolver artifactResolver,
			final ArtifactRepository localRepository,
			final ArtifactMetadataSource artifactMetadataSource,
			final Dependency[] dependencies, final MavenProject project)
			throws InvalidDependencyVersionException,
			ArtifactResolutionException, ArtifactNotFoundException {
		if (dependencies == null) {
			return Collections.emptyList();
		}

		@SuppressWarnings("unchecked")
		final Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(
				artifactFactory, Arrays.asList(dependencies), "runtime", null,
				project);

		for (Artifact artifact : artifacts) {
			artifactResolver.resolve(artifact,

			project.getRemoteArtifactRepositories(), localRepository);
		}

		final Set<Artifact> resolvedArtifacts = artifacts;
		return resolvedArtifacts;
	}

	public static final Function<Artifact, File> GET_FILE = new Function<Artifact, File>() {
		public File eval(Artifact argument) {
			return argument.getFile();
		}
	};

	public static final Collection<File> getFiles(Collection<Artifact> artifacts) {
		return CollectionUtils.apply(artifacts, ArtifactUtils.GET_FILE);
	}

	public static void mergeDependencyWithDefaults(Dependency dep, Dependency def) {
		if (dep.getScope() == null && def.getScope() != null) {
			dep.setScope(def.getScope());
			dep.setSystemPath(def.getSystemPath());
		}
	
		if (dep.getVersion() == null && def.getVersion() != null) {
			dep.setVersion(def.getVersion());
		}
	
		if (dep.getClassifier() == null && def.getClassifier() != null) {
			dep.setClassifier(def.getClassifier());
		}
	
		if (dep.getType() == null && def.getType() != null) {
			dep.setType(def.getType());
		}
	
		@SuppressWarnings("rawtypes")
		List exclusions = dep.getExclusions();
		if (exclusions == null || exclusions.isEmpty()) {
			dep.setExclusions(def.getExclusions());
		}
	}
} public class CollectionUtils {

	public static class PositiveComparatorWithNullAsGreatest<V extends Object & Comparable<? super V>>
			implements Comparator<V> {
		public int compare(V o1, V o2) {
			if (o1 == null && o2 == null)
				return 0;
			else if (o1 == null)
				return 1;
			else if (o2 == null)
				return -1;
			else
				return o1.compareTo(o2);
		}
	}

	public static class NegativeComparatorWithNullAsSmallest<V extends Object & Comparable<? super V>>
			implements Comparator<V> {
		public int compare(V o1, V o2) {
			if (o1 == null && o2 == null)
				return 0;
			else if (o1 == null)
				return 1;
			else if (o2 == null)
				return -1;
			else
				return -o1.compareTo(o2);
		}
	}

	public interface Function<T, V> {
		public V eval(T argument);
	}

	public static <T, V> List<V> apply(Collection<T> collection,
			Function<T, V> function) {
		final List<V> list = new ArrayList<V>(collection.size());
		for (T t : collection) {
			list.add(function.eval(t));
		}
		return list;
	}

	public static <T, V> V bestValue(Collection<T> collection,
			CollectionUtils.Function<T, V> function, Comparator<V> comparator) {

		if (collection == null || collection.isEmpty())
			return null;

		final Iterator<T> i = collection.iterator();
		V candidateValue = function.eval(i.next());

		while (i.hasNext()) {
			final V nextValue = function.eval(i.next());
			if (comparator.compare(candidateValue, nextValue) < 0) {
				candidateValue = nextValue;
			}
		}
		return candidateValue;
	}

	@SuppressWarnings("rawtypes")
	private static Comparator<?> LT_NULL_SMALLEST = new NegativeComparatorWithNullAsSmallest();

	@SuppressWarnings("rawtypes")
	private static Comparator<?> GT_NULL_GREATEST = new PositiveComparatorWithNullAsGreatest();

	public static <V extends Object & Comparable<? super V>> Comparator<V> ltWithNullAsSmallest() {
		@SuppressWarnings("unchecked")
		final Comparator<V> comparator = (Comparator<V>) LT_NULL_SMALLEST;
		return comparator;
	}

	public static <V extends Object & Comparable<? super V>> Comparator<V> gtWithNullAsGreatest() {
		@SuppressWarnings("unchecked")
		final Comparator<V> comparator = (Comparator<V>) GT_NULL_GREATEST;
		return comparator;
	}

} public interface Function<T, V> {
	public V eval(T argument);
} public class IOUtils {

	/**
	 * Creates an input source for the given file.
	 * 
	 * @param file
	 *            file to create input source for.
	 * 
	 * @return Created input source object.
	 */
	public static InputSource getInputSource(File file) {
		try {
			final URL url = file.toURI().toURL();
			return getInputSource(url);
		} catch (MalformedURLException e) {
			return new InputSource(file.getPath());
		}
	}

	public static InputSource getInputSource(final URL url) {
		return new InputSource(StringUtils.escapeSpace(url.toExternalForm()));
	}

	public static InputSource getInputSource(final URI uri) {
		return new InputSource(StringUtils.escapeSpace(uri.toString()));
	}

	public static final Function<File, URL> GET_URL = new Function<File, URL>() {
		public URL eval(File file) {
			try {
				return file.toURI().toURL();
			} catch (MalformedURLException muex) {
				throw new RuntimeException(muex);
			}
		}
	};

	/**
	 * Scans given directory for files satisfying given inclusion/exclusion
	 * patterns.
	 * 
	 * @param buildContext
	 *            Build context provided by the environment, used to scan for files.
	 * @param directory
	 *            Directory to scan.
	 * @param includes
	 *            inclusion pattern.
	 * @param excludes
	 *            exclusion pattern.
	 * @param defaultExcludes
	 *            default exclusion flag.
	 * @return Files from the given directory which satisfy given patterns. The
	 *         files are {@link File#getCanonicalFile() canonical}.
	 * @throws IOException
	 *             If an I/O error occurs, which is possible because the
	 *             construction of the canonical pathname may require filesystem
	 *             queries.
	 */
	public static List<File> scanDirectoryForFiles(BuildContext buildContext, final File directory,
			final String[] includes, final String[] excludes, boolean defaultExcludes) throws IOException {
		if (!directory.exists()) {
			return Collections.emptyList();
		}
		final Scanner scanner;

		if (buildContext != null) {
			scanner = buildContext.newScanner(directory, true);
		} else {
			final DirectoryScanner directoryScanner = new DirectoryScanner();
			directoryScanner.setBasedir(directory.getAbsoluteFile());
			scanner = directoryScanner;
		}
		scanner.setIncludes(includes);
		scanner.setExcludes(excludes);
		if (defaultExcludes) {
			scanner.addDefaultExcludes();
		}

		scanner.scan();

		final List<File> files = new ArrayList<File>();
		for (final String name : scanner.getIncludedFiles()) {
			files.add(new File(directory, name).getCanonicalFile());
		}

		return files;
	}
} public class LocaleUtils {
	public static Locale valueOf(String lang) {
		if ((lang == null) || lang.equals("")) {
			return Locale.getDefault();
		}
		String language = "";
		String country = "";
		String variant = "";

		int i1 = lang.indexOf('-');
		if (i1 < 0) {
			language = lang;
		} else {
			language = lang.substring(0, i1);
			++i1;
			int i2 = lang.indexOf('-', i1);
			if (i2 < 0) {
				country = lang.substring(i1);
			} else {
				country = lang.substring(i1, i2);
				variant = lang.substring(i2 + 1);
			}
		}

		if (language.length() == 2) {
			language = language.toLowerCase();
		} else {
			language = "";
		}

		if (country.length() == 2) {
			country = country.toUpperCase();
		} else {
			country = "";
		}

		if ((variant.length() > 0)
				&& ((language.length() == 2) || (country.length() == 2))) {
			variant = variant.toUpperCase();
		} else {
			variant = "";
		}

		return new Locale(language, country, variant);
	}
}
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.artifact.resolver.filter.TypeArtifactFilter;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.jvnet.jaxb2.maven2.net.CompositeURILastModifiedResolver;
import org.jvnet.jaxb2.maven2.net.FileURILastModifiedResolver;
import org.jvnet.jaxb2.maven2.net.URILastModifiedResolver;
import org.jvnet.jaxb2.maven2.resolver.tools.MavenCatalogResolver;
import org.jvnet.jaxb2.maven2.resolver.tools.ReResolvingEntityResolverWrapper;
import org.jvnet.jaxb2.maven2.util.ArtifactUtils;
import org.jvnet.jaxb2.maven2.util.CollectionUtils;
import org.jvnet.jaxb2.maven2.util.CollectionUtils.Function;
import org.jvnet.jaxb2.maven2.util.IOUtils;
import org.jvnet.jaxb2.maven2.util.LocaleUtils;
import org.sonatype.plexus.build.incremental.BuildContext;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver;
import com.sun.xml.txw2.annotation.XmlNamespace;

		if (getScanDependenciesForBindings()) {
			collectBindingUrisFromDependencies(bindingUris);
		}

		return bindingUris;
	}

	private List<InputSource> createBindFiles() throws MojoExecutionException {
		try {
			final List<URI> bindingURIs = getBindingURIs();
			return getInputSources(bindingURIs);
		} catch (IOException ioex) {
			throw new MojoExecutionException("Could not resolve binding files.", ioex);
		} catch (SAXException ioex) {
			throw new MojoExecutionException("Could not resolve binding files.", ioex);
		}
	}

	private List<URI> dependsURIs;

	public List<URI> getDependsURIs() {
		return dependsURIs;
	}

	private List<URI> producesURIs;

	public List<URI> getProducesURIs() {
		return producesURIs;
	}

	private static final Object lock = new Object();

	/**
	 * Execute the maven2 mojo to invoke the xjc2 compiler based on any
	 * configuration settings.
	 */
	public void execute() throws MojoExecutionException {
		synchronized (lock) {
			injectDependencyDefaults();
			resolveArtifacts();

			// Install project dependencies into classloader's class path
			// and execute xjc2.
			final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
			final ClassLoader classLoader = createClassLoader(currentClassLoader);
			Thread.currentThread().setContextClassLoader(classLoader);
			final Locale currentDefaultLocale = Locale.getDefault();
			try {
				final Locale locale = LocaleUtils.valueOf(getLocale());
				Locale.setDefault(locale);
				//
				doExecute();

			} finally {
				Locale.setDefault(currentDefaultLocale);
				// Set back the old classloader
				Thread.currentThread().setContextClassLoader(currentClassLoader);
			}
		}
	}

	/**
	 * ************************************************************************* *
	 */

	protected void injectDependencyDefaults() {
		injectDependencyDefaults(getPlugins());
		injectDependencyDefaults(getEpisodes());
	}

	@SuppressWarnings("unchecked")
	protected void injectDependencyDefaults(Dependency[] dependencies) {
		if (dependencies != null) {
			final Map<String, Dependency> dependencyMap = new TreeMap<String, Dependency>();
			for (final Dependency dependency : dependencies) {
				if (dependency.getScope() == null) {
					dependency.setScope(Artifact.SCOPE_RUNTIME);
				}
				dependencyMap.put(dependency.getManagementKey(), dependency);
			}

			final DependencyManagement dependencyManagement = getProject().getDependencyManagement();

			if (dependencyManagement != null) {
				merge(dependencyMap, dependencyManagement.getDependencies());
			}
			merge(dependencyMap, getProjectDependencies());
		}
	}

	private void merge(final Map<String, Dependency> dependencyMap, final List<Dependency> managedDependencies) {
		for (final Dependency managedDependency : managedDependencies) {
			final String key = managedDependency.getManagementKey();
			final Dependency dependency = (Dependency) dependencyMap.get(key);
			if (dependency != null) {
				ArtifactUtils.mergeDependencyWithDefaults(dependency, managedDependency);
			}
		}
	}

	protected void resolveArtifacts() throws MojoExecutionException {
		try {

			resolveXJCPluginArtifacts();
			resolveEpisodeArtifacts();
		} catch (ArtifactResolutionException arex) {
			throw new MojoExecutionException("Could not resolve the artifact.", arex);
		} catch (ArtifactNotFoundException anfex) {
			throw new MojoExecutionException("Artifact not found.", anfex);
		} catch (InvalidDependencyVersionException idvex) {
			throw new MojoExecutionException("Invalid dependency version.", idvex);
		}
	}

	protected void resolveXJCPluginArtifacts()
			throws ArtifactResolutionException, ArtifactNotFoundException, InvalidDependencyVersionException {

		this.xjcPluginArtifacts = ArtifactUtils.resolveTransitively(getArtifactFactory(), getArtifactResolver(),
				getLocalRepository(), getArtifactMetadataSource(), getPlugins(), getProject());
		this.xjcPluginFiles = ArtifactUtils.getFiles(this.xjcPluginArtifacts);

		this.xjcPluginURLs = CollectionUtils.apply(this.xjcPluginFiles, IOUtils.GET_URL);
