Example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException

List of usage examples for org.apache.maven.plugin MojoExecutionException MojoExecutionException

Introduction

In this page you can find the example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException.

Prototype

public MojoExecutionException(String message) 

Source Link

Document

Construct a new MojoExecutionException exception providing a message.

Usage

From source file:ca.trentonadams.maven.plugins.RunRMI.java

License:Apache License

/**
 * Initialization tasks such as checking parameters are correct, creating
 * the classpath, etc.//from  w  w  w.  j a v a2s.  c  om
 *
 * @throws MojoExecutionException if an unrecoverable error occurs.
 */
private void initialize() throws MojoExecutionException {
    mojoLog = getLog();
    mojoLog.info("javaHome: " + javaHome);
    javaCommand = javaHome + File.separatorChar + "bin" + File.separatorChar + "java";
    rmiRegistryCommand = javaHome + File.separatorChar + "bin" + File.separatorChar + "rmiregistry";
    if (verify != null && verify.length != 3) {
        throw new MojoExecutionException("The \"verify\" parameter is setup "
                + "incorrectly.  Please specify a Remote interface class name, "
                + "followed by a method name, followed by an expected string " + "return value.");
    } else if (verify != null && verify.length == 3) {
        verifyMethod = verify[0];
        verifyReturnValue = verify[1];
        verifyBindName = verify[2];

        mojoLog.info("verification method: " + verifyMethod);
        mojoLog.info("verification return value: " + verifyReturnValue);
        mojoLog.info("verification bind name: " + verifyBindName);
    }

    mojoLog.info("registry port: " + registryPort);

    threads = new Vector<CommandThread>();

    try {
        classpath = StringUtils.join(project.getCompileClasspathElements().iterator(), File.pathSeparator);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error getting classpath: ", e);
    }

    mojoLog.info("codebase: " + codebase);

    try {
        final ClassWorld world = new ClassWorld();

        //use the existing ContextClassLoader in a realm of the classloading space
        final ClassRealm realm = world.newRealm("plugin.maven.rmi",
                Thread.currentThread().getContextClassLoader());

        //create another realm for just the jars we have downloaded on-the-fly and make
        //sure it is in a child-parent relationship with the current ContextClassLoader
        final ClassRealm rmiRealm = realm.createChildRealm("rmi");

        final List elements = project.getCompileClasspathElements();

        for (final Object element : elements) {
            mojoLog.debug("element: " + element);
            rmiRealm.addConstituent(new File((String) element).toURL());
        }

        //make the child realm the ContextClassLoader
        Thread.currentThread().setContextClassLoader(rmiRealm.getClassLoader());
    } catch (DuplicateRealmException e) {
        throw new MojoExecutionException("class loading modification " + "failed", e);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("class loading modification " + "failed", e);
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("class loading modification " + "failed", e);
    }
}

From source file:ca.uhn.hl7v2.mvnplugin.ConfGenMojo.java

License:Mozilla Public License

/**
 * {@inheritDoc}/*from w  w w .j a  v a2  s  .c  o m*/
 */
public void execute() throws MojoExecutionException, MojoFailureException {

    GenerateDataTypesEnum genDt;
    try {
        genDt = GenerateDataTypesEnum.valueOf(generateDataTypes);
    } catch (IllegalArgumentException e) {
        throw new MojoExecutionException("Unknown \"generateDataTypes\" value: " + generateDataTypes);
    }

    try {

        String profileString;
        FileReader reader = new FileReader(profile);
        profileString = IOUtil.toString(reader);

        ProfileParser profileParser = new ProfileParser(false);
        RuntimeProfile runtimeProfile = profileParser.parse(profileString);

        ProfileSourceGenerator gen = new ProfileSourceGenerator(runtimeProfile, targetDirectory, packageName,
                genDt, templatePackage, fileExt);
        gen.generate();

        if (!structuresAsResources) {
            getLog().info("Adding path to compile sources: " + targetDirectory);
            project.addCompileSourceRoot(targetDirectory);
        }

    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    project.addCompileSourceRoot(targetDirectory);

}

From source file:ca.uhn.hl7v2.mvnplugin.SuperStructureMojo.java

License:Mozilla Public License

/**
 * {@inheritDoc}//from  w w w  .j  av a2  s.co  m
 */
public void execute() throws MojoExecutionException, MojoFailureException {

    if (skip) {
        getLog().warn("Configured to skip");
    }

    try {
        List<String> allStructures = new ArrayList<String>();
        DefaultModelClassFactory mcf = new DefaultModelClassFactory();

        // We want a sorted and unique list of all structures
        Version versionOf = Version.versionOf(version);
        if (versionOf == null) {
            throw new MojoExecutionException("Unknown version: " + version);
        }

        //         Map<String, String> eventMap = mcf.getEventMapForVersion(versionOf);
        //         if (eventMap == null) {
        //            throw new MojoExecutionException("Failed to load structures for version " + version + ". Do you have the right dependencies configured for this plugin?");
        //         }
        //
        //         Set<String> allStructuresSet = new HashSet<String>();
        //         allStructuresSet.addAll(eventMap.values());
        //         allStructures.addAll(allStructuresSet);
        //         Collections.sort(allStructures);

        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                true);
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader(
                GenericComposite.class.getClassLoader());
        scanner.setResourceLoader(resourceLoader);
        scanner.addIncludeFilter(new AssignableTypeFilter(Message.class));
        Set<BeanDefinition> components = scanner
                .findCandidateComponents("ca/uhn/hl7v2/model/" + versionOf.getPackageVersion() + "/message");
        for (BeanDefinition beanDefinition : components) {
            String nextName = Class.forName(beanDefinition.getBeanClassName()).getSimpleName();
            if (nextName.equals(targetStructureName)) {
                continue;
            }
            allStructures.add(nextName);
        }

        getLog().info("Found " + allStructures.size() + " message classes for version: " + version);

        List<Message> messagesToMerge = new ArrayList<Message>();

        Collections.sort(allStructures);
        for (String nextStructure : allStructures) {
            for (String nextStructureToMerge : structures) {
                if (nextStructure.matches(nextStructureToMerge)) {
                    Class<? extends Message> clazz = mcf.getMessageClass(nextStructure, version, true);
                    messagesToMerge.add(ReflectionUtil.instantiateMessage(clazz, mcf));
                }
            }
        }

        if (messagesToMerge.isEmpty()) {
            throw new MojoFailureException("No messages match pattern(s): " + structures);
        }

        ListOfStructureDefsAndMapOfStructreNames mergedMessages = mergeGroups(messagesToMerge, messagesToMerge);
        List<StructureDef> structures = mergedMessages.myStructureDefs;
        if (structures.isEmpty()) {
            throw new MojoExecutionException("No structures found matching structures to merge");
        }

        getLog().info("Creating directory: " + targetDirectory);
        new File(targetDirectory).mkdirs();

        boolean haveGroups = false;
        for (StructureDef structureDef : structures) {
            if (structureDef.isGroup()) {
                haveGroups = true;
                writeGroup((GroupDef) structureDef);
            }
        }

        String fileName = MessageGenerator.determineTargetDir(targetDirectory + "/", version) + "/"
                + targetStructureName + ".java";
        getLog().info("Filename will be: " + fileName);

        StructureDef[] contents = structures.toArray(new StructureDef[structures.size()]);
        String basePackageName = DefaultModelClassFactory.getVersionPackageName(version);
        MessageGenerator.writeMessage(fileName, contents, targetStructureName, "", version, basePackageName,
                haveGroups, templatePackage, mergedMessages.myStructureNameToChildNames);

    } catch (Exception e) {
        throw new MojoFailureException("Failed to generate structure", e);
    }
    getLog().info("Adding " + targetDirectory + " to compile source root");
    project.addCompileSourceRoot(targetDirectory);

}

From source file:cascading.avro.AbstractAvroMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {
    boolean hasSourceDir = null != getSourceDirectory() && getSourceDirectory().isDirectory();
    boolean hasTestDir = null != getTestSourceDirectory() && getTestSourceDirectory().isDirectory();
    if (!hasSourceDir && !hasTestDir) {
        throw new MojoExecutionException("neither sourceDirectory: " + getSourceDirectory()
                + " or testSourceDirectory: " + getTestSourceDirectory() + " are directories");
    }//from  w  w  w . ja  v  a 2 s .co m
    if (hasSourceDir) {
        String[] includedFiles = getIncludedFiles(getSourceDirectory().getAbsolutePath(), getExcludes(),
                getIncludes());
        compileFiles(includedFiles, getSourceDirectory(), getOutputDirectory());
        project.addCompileSourceRoot(getOutputDirectory().getAbsolutePath());
    }
    if (hasTestDir) {
        String[] includedFiles = getIncludedFiles(getTestSourceDirectory().getAbsolutePath(), getTestExcludes(),
                getTestIncludes());
        compileFiles(includedFiles, getTestSourceDirectory(), getTestOutputDirectory());
        project.addTestCompileSourceRoot(getTestOutputDirectory().getAbsolutePath());
    }
}

From source file:ch.entwine.weblounge.maven.S3DeployMojo.java

License:Open Source License

/**
 * // w ww . j  a va  2 s.c  om
 * {@inheritDoc}
 * 
 * @see org.apache.maven.plugin.Mojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {

    // Setup AWS S3 client
    AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
    AmazonS3Client uploadClient = new AmazonS3Client(credentials);
    TransferManager transfers = new TransferManager(credentials);

    // Make sure key prefix does not start with a slash but has one at the
    // end
    if (keyPrefix.startsWith("/"))
        keyPrefix = keyPrefix.substring(1);
    if (!keyPrefix.endsWith("/"))
        keyPrefix = keyPrefix + "/";

    // Keep track of how much data has been transferred
    long totalBytesTransferred = 0L;
    int items = 0;
    Queue<Upload> uploads = new LinkedBlockingQueue<Upload>();

    try {
        // Check if S3 bucket exists
        getLog().debug("Checking whether bucket " + bucket + " exists");
        if (!uploadClient.doesBucketExist(bucket)) {
            getLog().error("Desired bucket '" + bucket + "' does not exist!");
            return;
        }

        getLog().debug("Collecting files to transfer from " + resources.getDirectory());
        List<File> res = getResources();
        for (File file : res) {
            // Make path of resource relative to resources directory
            String filename = file.getName();
            String extension = FilenameUtils.getExtension(filename);
            String path = file.getPath().substring(resources.getDirectory().length());
            String key = concat("/", keyPrefix, path).substring(1);

            // Delete old file version in bucket
            getLog().debug("Removing existing object at " + key);
            uploadClient.deleteObject(bucket, key);

            // Setup meta data
            ObjectMetadata meta = new ObjectMetadata();
            meta.setCacheControl("public, max-age=" + String.valueOf(valid * 3600));

            FileInputStream fis = null;
            GZIPOutputStream gzipos = null;
            final File fileToUpload;

            if (gzip && ("js".equals(extension) || "css".equals(extension))) {
                try {
                    fis = new FileInputStream(file);
                    File gzFile = File.createTempFile(file.getName(), null);
                    gzipos = new GZIPOutputStream(new FileOutputStream(gzFile));
                    IOUtils.copy(fis, gzipos);
                    fileToUpload = gzFile;
                    meta.setContentEncoding("gzip");
                    if ("js".equals(extension))
                        meta.setContentType("text/javascript");
                    if ("css".equals(extension))
                        meta.setContentType("text/css");
                } catch (FileNotFoundException e) {
                    getLog().error(e);
                    continue;
                } catch (IOException e) {
                    getLog().error(e);
                    continue;
                } finally {
                    IOUtils.closeQuietly(fis);
                    IOUtils.closeQuietly(gzipos);
                }
            } else {
                fileToUpload = file;
            }

            // Do a random check for existing errors before starting the next upload
            if (erroneousUpload != null)
                break;

            // Create put object request
            long bytesToTransfer = fileToUpload.length();
            totalBytesTransferred += bytesToTransfer;
            PutObjectRequest request = new PutObjectRequest(bucket, key, fileToUpload);
            request.setProgressListener(new UploadListener(credentials, bucket, key, bytesToTransfer));
            request.setMetadata(meta);

            // Schedule put object request
            getLog().info(
                    "Uploading " + key + " (" + FileUtils.byteCountToDisplaySize((int) bytesToTransfer) + ")");
            Upload upload = transfers.upload(request);
            uploads.add(upload);
            items++;
        }
    } catch (AmazonServiceException e) {
        getLog().error("Uploading resources failed: " + e.getMessage());
    } catch (AmazonClientException e) {
        getLog().error("Uploading resources failed: " + e.getMessage());
    }

    // Wait for uploads to be finished
    String currentUpload = null;
    try {
        Thread.sleep(1000);
        getLog().info("Waiting for " + uploads.size() + " uploads to finish...");
        while (!uploads.isEmpty()) {
            Upload upload = uploads.poll();
            currentUpload = upload.getDescription().substring("Uploading to ".length());
            if (TransferState.InProgress.equals(upload.getState()))
                getLog().debug("Waiting for upload " + currentUpload + " to finish");
            upload.waitForUploadResult();
        }
    } catch (AmazonServiceException e) {
        throw new MojoExecutionException("Error while uploading " + currentUpload);
    } catch (AmazonClientException e) {
        throw new MojoExecutionException("Error while uploading " + currentUpload);
    } catch (InterruptedException e) {
        getLog().debug("Interrupted while waiting for upload to finish");
    }

    // Check for errors that happened outside of the actual uploading
    if (erroneousUpload != null) {
        throw new MojoExecutionException("Error while uploading " + erroneousUpload);
    }

    getLog().info("Deployed " + items + " files ("
            + FileUtils.byteCountToDisplaySize((int) totalBytesTransferred) + ") to s3://" + bucket);
}

From source file:ch.ifocusit.livingdoc.plugin.common.Template.java

License:Apache License

public String process(String value) throws MojoExecutionException {
    try {//from  ww  w .  j  a v  a 2 s. com
        // read template
        final String content = IOUtils.toString(new FileInputStream(template), Charset.defaultCharset());

        // validate content
        if (StringUtils.isBlank(content)) {
            throw new MojoExecutionException(String.format("Template founded (%s) but empty !", template));
        }
        if (!content.contains(token)) {
            throw new MojoExecutionException(
                    String.format("1Token '%s' is not present in template file !", token));
        }
        // update content
        return content.replace(token, value);
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException(String.format("Remplate file not found (%s) !", template), e);
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Error during process template file (%s) !", template),
                e);
    }
}

From source file:ch.ivyteam.ivy.maven.AbstractEngineMojo.java

License:Apache License

protected final VersionRange getIvyVersionRange() throws MojoExecutionException {
    try {//w  w w  .  jav  a2 s . co  m
        VersionRange minimalCompatibleVersionRange = VersionRange
                .createFromVersionSpec("[" + AbstractEngineMojo.MINIMAL_COMPATIBLE_VERSION + ",)");
        VersionRange ivyVersionRange = VersionRange.createFromVersionSpec(ivyVersion);

        if (ivyVersionRange.getRecommendedVersion() != null) {
            ivyVersionRange = VersionRange.createFromVersionSpec("[" + ivyVersion + "]");
        }

        VersionRange restrictedIvyVersionRange = ivyVersionRange.restrict(minimalCompatibleVersionRange);
        if (!restrictedIvyVersionRange.hasRestrictions()) {
            throw new MojoExecutionException(
                    "The ivyVersion '" + ivyVersion + "' is lower than the minimal compatible version" + " '"
                            + MINIMAL_COMPATIBLE_VERSION + "'.");
        }
        return restrictedIvyVersionRange;
    } catch (InvalidVersionSpecificationException ex) {
        throw new MojoExecutionException("Invalid ivyVersion '" + ivyVersion + "'.", ex);
    }
}

From source file:ch.ivyteam.ivy.maven.engine.deploy.MarkerFileDeployer.java

License:Apache License

private void failOnError() throws MojoExecutionException {
    if (markerFile.errorLog().exists()) {
        try {//from w  w  w  . j a v  a2s  .  c om
            log.error(FileUtils.readFileToString(markerFile.errorLog()));
        } catch (IOException ex) {
            log.error("Failed to resolve deployment error cause", ex);
        }
        throw new MojoExecutionException(
                "Deployment of '" + markerFile.getDeployCandidate().getName() + "' failed!");
    }
}

From source file:ch.ivyteam.ivy.maven.InstallEngineMojo.java

License:Apache License

private void downloadAndInstallEngine(boolean cleanEngineDir) throws MojoExecutionException {
    if (autoInstallEngine) {
        getLog().info("Will automatically download Engine now.");
        EngineDownloader engineDownloader = new EngineDownloader();
        File downloadZip = engineDownloader.downloadEngine();
        if (cleanEngineDir) {
            removeOldEngineContent();//  w w w  .j a  v  a 2s  .  co m
        }
        if (!isEngineDirectoryIdentified()) {
            String engineZipFileName = engineDownloader.getZipFileNameFromDownloadUrl();
            engineDirectory = new File(engineCacheDirectory, ivyEngineVersionOfZip(engineZipFileName));
            engineDirectory.mkdirs();
        }
        unpackEngine(downloadZip);
        downloadZip.delete();

        ArtifactVersion installedEngineVersion = getInstalledEngineVersion(getRawEngineDirectory());
        if (installedEngineVersion == null || !getIvyVersionRange().containsVersion(installedEngineVersion)) {
            throw new MojoExecutionException(
                    "Automatic installation of an ivyEngine failed. " + "Downloaded version is '"
                            + installedEngineVersion + "' but expecting '" + ivyVersion + "'.");
        }
    } else {
        throw new MojoExecutionException("Aborting class generation as no valid ivy Engine is available! "
                + "Use the 'autoInstallEngine' parameter for an automatic installation.");
    }
}

From source file:ch.ringler.tools.m2cachecleanup.CleanupMavenCache.java

License:Apache License

public void execute() throws MojoExecutionException {

    try {//from   w  w w  .  j  a  va2  s  . c o  m
        //
        // Sanity checks
        //
        if (!isValidCache(directory))
            throw new MojoExecutionException(
                    "Directory '" + directory.getCanonicalPath() + "' is not a maven cache");

        CacheWalker walker = new CacheWalker(getLog());
        getLog().info("Cleaning Maven local cache at '" + directory.getCanonicalPath() + "'");
        walker.processDirectory(directory);

        // Print statistics
        getLog().info("Totally deleted " + walker.getDeleted() + " file(s).");
        getLog().info("Reclaimed space " + getHrSize(walker.getReclaimedSpace()));
        if (walker.getFailedToDelete() > 0) {
            getLog().info("Failed to delete " + walker.getFailedToDelete() + " file(s).");
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Unexpected exception during cache cleanup", e);
    }
}