org.apache.maven.plugin.MojoExecutionException Java Examples

The following examples show how to use org.apache.maven.plugin.MojoExecutionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LessCompilerMojo.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private WatchingException buildWatchingException(String stream, File file, MojoExecutionException e) {
    String[] lines = stream.split("\n");
    for (String l : lines) {
        if (!Strings.isNullOrEmpty(l)) {
            stream = l.trim();
            break;
        }
    }
    final Matcher matcher = LESS_ERROR_PATTERN.matcher(stream);
    if (matcher.matches()) {
        String line = matcher.group(2);
        String character = matcher.group(3);
        String reason = matcher.group(1);
        return new WatchingException("Less Compilation Error", reason, file,
                Integer.valueOf(line), Integer.valueOf(character), null);
    } else {
        return new WatchingException("Less Compilation Error", stream, file, e.getCause());
    }
}
 
Example #2
Source File: RepackageMojo.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {
    if ("war".equals(this.project.getPackaging())) {
        getLog().debug("repackage goal could not be applied to war project.");
        return;
    }
    if ("pom".equals(this.project.getPackaging())) {
        getLog().debug("repackage goal could not be applied to pom project.");
        return;
    }
    if (StringUtils.isSameStr(this.arkClassifier, this.bizClassifier)) {
        getLog().debug("Executable fat jar should be different from 'plug-in' module jar.");
        return;
    }
    if (this.skip) {
        getLog().debug("skipping repackaging as configuration.");
        return;
    }

    /* version of ark container packaged into fat jar follows the plugin version */
    PluginDescriptor pluginDescriptor = (PluginDescriptor) getPluginContext().get(
        "pluginDescriptor");
    arkVersion = pluginDescriptor.getVersion();

    repackage();
}
 
Example #3
Source File: StopMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * This will compute the vertx application id(s) that will be passed to the vertx applicaiton with "-id"
 * option, if the appId is not found in the configuration an new {@link UUID}  will be generated and assigned
 */
private void getAppId() throws MojoExecutionException {

    if (appIds == null) {
        appIds = new HashSet<>();
    }

    Path vertxPidFile = Paths.get(workDirectory.toString(), VERTX_PID_FILE);

    if (Files.exists(vertxPidFile)) {
        try {
            byte[] bytes = Files.readAllBytes(vertxPidFile);
            appIds.add(new String(bytes));
        } catch (IOException e) {
            throw new MojoExecutionException("Error reading " + VERTX_PID_FILE, e);
        }
    }
}
 
Example #4
Source File: StopMojoTest.java    From app-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStop() throws MojoExecutionException, AppEngineException {

  // wire up
  stopMojo.host = "host";
  stopMojo.port = 124;

  // invoke
  stopMojo.execute();

  // verify
  ArgumentCaptor<StopConfiguration> captor = ArgumentCaptor.forClass(StopConfiguration.class);
  verify(devServerMock).stop(captor.capture());

  Assert.assertEquals("host", captor.getValue().getHost());
  Assert.assertEquals(Integer.valueOf(124), captor.getValue().getPort());
}
 
Example #5
Source File: AbstractJnlpMojo.java    From webstart with MIT License 6 votes vote down vote up
/**
 * Iterate through all the extensions dependencies declared in the project and
 * collect all the runtime scope dependencies for inclusion in the .zip and just
 * copy them to the lib directory.
 * <p>
 * TODO, should check that all dependencies are well signed with the same
 * extension with the same signer.
 *
 * @throws MojoExecutionException TODO
 */
private void processExtensionsDependencies()
        throws MojoExecutionException
{

    Collection<Artifact> artifacts =
            isExcludeTransitive() ? getProject().getDependencyArtifacts() : getProject().getArtifacts();

    for ( JnlpExtension extension : jnlpExtensions )
    {
        ArtifactFilter filter = new IncludesArtifactFilter( extension.getIncludes() );

        for ( Artifact artifact : artifacts )
        {
            if ( filter.include( artifact ) )
            {
                processExtensionDependency( extension, artifact );
            }
        }
    }
}
 
Example #6
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the manifest for the über jar.
 */
private void generateManifest(JavaArchive jar, Map<String, String> entries) throws IOException,
    MojoExecutionException {
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    if (entries != null) {
        for (Map.Entry<String, String> entry : entries.entrySet()) {
            attributes.put(new Attributes.Name(entry.getKey()), entry.getValue());
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    manifest.write(bout);
    bout.close();
    byte[] bytes = bout.toByteArray();
    //TODO: merge existing manifest with current one
    jar.setManifest(new ByteArrayAsset(bytes));

}
 
Example #7
Source File: SpoonProcessingMojo.java    From camunda-bpm-swagger with Apache License 2.0 6 votes vote down vote up
@Override
@SneakyThrows
public void execute() throws MojoExecutionException, MojoFailureException {
  Context.builder()
  .executionEnvironment(executionEnvironment(project, session, buildPluginManager))
  .camundaVersion(camundaVersion)
  .unpackDirectory(unpackDirectory)
  .outputDirectory(outputDirectory)
  .noClasspath(false)
  .autoImports(false)
  .shouldCompile(false)
  .dtoYamlFile(dtoYamlFile)
  .serviceYamlFile(serviceYamlFile)
  .build()
  .initDirectory()
  .downloadSources()
  .loadDtoDocumentation()
  .loadServiceDocumentation()
  .processSources()
  ;
}
 
Example #8
Source File: SpringMvcTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void assertGeneratedSwaggerSpecYaml(String description) throws MojoExecutionException, MojoFailureException, IOException {
    mojo.getApiSources().get(0).setOutputFormats("yaml");
    mojo.execute();

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    String actualYaml = yaml.dump(yaml.load(FileUtils.readFileToString(new File(swaggerOutputDir, "swagger.yaml"))));
    String expectYaml = yaml.dump(yaml.load(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring.yaml")));

    ObjectMapper mapper = Json.mapper();
    JsonNode actualJson = mapper.readTree(YamlToJson(actualYaml));
    JsonNode expectJson = mapper.readTree(YamlToJson(expectYaml));

    changeDescription(expectJson, description);
    assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER));
}
 
Example #9
Source File: AbstractSarlMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
	if (isSkipped()) {
		getLog().info(Messages.AbstractSarlMojo_5);
		return;
	}
	try {
		this.mavenHelper = new MavenHelper(this.session, this.buildPluginManager, this.repositorySystem,
				this.resolutionErrorHandler, getLog());
		ensureDefaultParameterValues();
		prepareExecution();
		executeMojo();
	} catch (Exception e) {
		getLog().error(e.getLocalizedMessage(), e);
		throw e;
	}
}
 
Example #10
Source File: MojoExecutor.java    From heroku-maven-plugin with MIT License 6 votes vote down vote up
public static void copyDependenciesToBuildDirectory(MavenProject mavenProject,
                                                    MavenSession mavenSession,
                                                    BuildPluginManager pluginManager) throws MojoExecutionException {
    executeMojo(
            plugin(
                    groupId("org.apache.maven.plugins"),
                    artifactId("maven-dependency-plugin"),
                    version("2.4")
            ),
            goal("copy-dependencies"),
            configuration(
                    element(name("outputDirectory"), "${project.build.directory}/dependency")
            ),
            executionEnvironment(
                    mavenProject,
                    mavenSession,
                    pluginManager
            )
    );
}
 
Example #11
Source File: WsdlUtilities.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static List<File> getWsdlFiles(File dir, String[] includes, String[] excludes)
    throws MojoExecutionException {

    List<String> exList = new ArrayList<>();
    if (excludes != null) {
        Collections.addAll(exList, excludes);
    }
    Collections.addAll(exList, org.codehaus.plexus.util.FileUtils.getDefaultExcludes());

    String inc = joinWithComma(includes);
    String ex = joinWithComma(exList.toArray(new String[0]));

    try {
        List<?> newfiles = org.codehaus.plexus.util.FileUtils.getFiles(dir, inc, ex);
        return CastUtils.cast(newfiles);
    } catch (IOException exc) {
        throw new MojoExecutionException(exc.getMessage(), exc);
    }
}
 
Example #12
Source File: CSSMinifierMojoTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomArguments() throws MojoFailureException, MojoExecutionException, IOException {
    cleanup();
    less.execute();
    mojo.cleanCssArguments = "--debug -c ie7 -b";
    mojo.execute();

    File site = new File(FAKE_PROJECT_TARGET, "classes/assets/css/site-min.css");
    assertThat(site).isFile();
    assertThat(FileUtils.readFileToString(site))
            .contains("h1{color:red}");

    File style = new File(FAKE_PROJECT_TARGET, "classes/assets/less/style-min.css");
    assertThat(style).isFile();
    assertThat(FileUtils.readLines(style)).hasSize(2); // We don't remove line break.

}
 
Example #13
Source File: AbstractExecMojo.java    From exec-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the argument string given by the user. Strings are recognized as everything between STRING_WRAPPER.
 * PARAMETER_DELIMITER is ignored inside a string. STRING_WRAPPER and PARAMETER_DELIMITER can be escaped using
 * ESCAPE_CHAR.
 *
 * @return Array of String representing the arguments
 * @throws MojoExecutionException for wrong formatted arguments
 */
protected String[] parseCommandlineArgs()
    throws MojoExecutionException
{
    if ( commandlineArgs == null )
    {
        return null;
    }
    else
    {
        try
        {
            return CommandLineUtils.translateCommandline( commandlineArgs );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( e.getMessage() );
        }
    }
}
 
Example #14
Source File: AbstractCodegenMojo.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String[] createForkOnceArgs(List<List<String>> wargs) throws MojoExecutionException {
    try {
        File f = FileUtils.createTempFile("cxf-w2j", "args");
        PrintWriter fw = new PrintWriter(new FileWriter(f));
        for (List<String> args : wargs) {
            fw.println(Integer.toString(args.size()));
            for (String s : args) {
                fw.println(s);
            }
        }
        fw.println("-1");
        fw.close();
        return new String[] {
            f.getAbsolutePath()
        };
    } catch (IOException ex) {
        throw new MojoExecutionException("Could not create argument file", ex);
    }
}
 
Example #15
Source File: WebJarPackagerTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludesCustomization() throws MojoExecutionException, IOException {
    WebJarPackager packager = new WebJarPackager();
    packager.project = mock(MavenProject.class);
    packager.projectHelper = mock(MavenProjectHelper.class);
    when(packager.project.getArtifactId()).thenReturn("test");
    when(packager.project.getVersion()).thenReturn("1.0");
    when(packager.project.getBasedir()).thenReturn(fake);
    packager.buildDirectory = new File("target/junk");
    copy();
    packager.webjar = new WebJar();
    FileSet set = new FileSet();
    set.setDirectory(new File(classes, "assets").getAbsolutePath());
    set.setIncludes(ImmutableList.of("**/coffee/*"));
    packager.webjar.setFileset(set);

    packager.execute();
    final File wj = new File(packager.buildDirectory, "test-1.0-webjar.jar");
    assertThat(wj).isFile();
    JarFile jar = new JarFile(wj);
    assertThat(jar.getEntry(WebJarPackager.ROOT + "test/1.0/missing")).isNull();
    assertThat(jar.getEntry(WebJarPackager.ROOT + "test/1.0/coffee/script.coffee")).isNotNull();
    assertThat(jar.getEntry(WebJarPackager.ROOT + "test/1.0/less/style.less")).isNull();
}
 
Example #16
Source File: SetNextDevVersion.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void execute(ExecutionContext context) throws MojoExecutionException, MojoFailureException {
  this.log.info("Preparing project modules for next development cycle.");

  this.scmProvider = this.scmProviderRegistry.getProvider();
  this.cachedPOMs = Maps.newHashMap();

  for (MavenProject project : this.reactorProjects) {
    this.log.debug("\tPreparing module '" + ProjectToString.INSTANCE.apply(project) + "'.");
    this.cachedPOMs.put(ProjectToCoordinates.EMPTY_VERSION.apply(project), PomUtil.parsePOM(project).get());

    try {
      Document document = loadAndProcess(project);
      PomUtil.writePOM(document, project);
    } catch (Throwable t) {
      throw new MojoFailureException("Could not update versions for next development cycle.", t);
    }
  }

  this.util.commitChanges(true);
}
 
Example #17
Source File: UploadMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
public void execute()
		throws MojoExecutionException
{
	if (skip || skipUpload) {
		getLog().info("Skip upload");
		return;
	}
	getLog().info("Uploading to " + getHelmUploadUrl() + "\n");
	for (String chartPackageFile : getChartTgzs(getOutputDirectory())) {
		getLog().info("Uploading " + chartPackageFile + "...");
		try {
			uploadSingle(chartPackageFile);
		} catch (BadUploadException | IOException e) {
			getLog().error(e.getMessage());
			throw new MojoExecutionException("Error uploading " + chartPackageFile + " to " + getHelmUploadUrl(),
					e);
		}
	}
}
 
Example #18
Source File: StopMojoTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Mock project with one image, query service indicates running image, and it is labelled.
 * Removal should pass true for removeVolumes.
 *
 * @throws IOException
 * @throws MojoExecutionException
 * @throws ExecException
 */
@Test
public void stopWithSingleImageIsLabelledRemoveVolume() throws IOException, MojoExecutionException, ExecException {
    givenProjectWithResolvedImage(singleImageWithBuild());

    givenContainerIsRunningForImage("example:latest", "container-id", "example-1");
    givenContainerHasGavLabels();

    Deencapsulation.setField(stopMojo, "removeVolumes", true);

    whenMojoExecutes();

    thenContainerLookupByImageOccurs("example:latest");
    thenListContainersIsNotCalled();
    thenContainerIsStopped("container-id", false, true);
}
 
Example #19
Source File: XJC21Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected Outline generateCode(final Model model)
		throws MojoExecutionException {
	if (getVerbose()) {
		getLog().info("Compiling input schema(s)...");
	}

	final Outline outline = model.generateCode(model.options,
			new LoggingErrorReceiver("Error while generating code.",
					getLog(), getVerbose()));
	if (outline == null) {
		throw new MojoExecutionException(
				"Failed to compile input schema(s)!  Error messages should have been provided.");
	} else {
		return outline;
	}
}
 
Example #20
Source File: ConvertMojo.java    From props2yaml with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (properties == null || properties.isEmpty()) {
        throw new MojoExecutionException("Param 'properties' is required");
    }

    Path propertiesPath = propertiesPath();
    try {
        getLog().info("Properties to convert: " + propertiesPath);
        String content = new String(Files.readAllBytes(propertiesPath));
        String yaml = Props2YAML.fromContent(content).convert(useNumericKeysAsArrayIndexes);
        Path destinationPath = propertiesPath.getParent().resolve(getFileName());
        getLog().info("Write YAML to: " + destinationPath);
        try (BufferedWriter writer = Files.newBufferedWriter(destinationPath)) {
            writer.write(yaml);
        }
    } catch (IOException e) {
        getLog().error("Failed to convert properties", e);
    }
}
 
Example #21
Source File: DebugMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    List<String> debugOptions = computeDebugOptions();
    if (jvmArgs == null) {
        jvmArgs = new ArrayList<>();
    }
    jvmArgs.addAll(debugOptions);

    if (redeploy) {
        getLog().warn("Redeployment and Debug cannot be used together - disabling redeployment");
        redeploy = false;
    }

    getLog().info("The application will wait for a debugger to attach on debugPort " + debugPort);
    if (debugSuspend) {
        getLog().info("The application will wait for a debugger to attach");
    }

    super.execute();

}
 
Example #22
Source File: RDFToDMNMojo.java    From jdmn with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {
    checkMandatoryField(inputFileDirectory, "inputFileDirectory");
    checkMandatoryField(outputFileDirectory, "outputFileDirectory");

    this.getLog().info(String.format("Transforming '%s' to '%s' ...", this.inputFileDirectory, this.outputFileDirectory));

    MavenBuildLogger logger = new MavenBuildLogger(this.getLog());
    FileTransformer transformer = new RDFToDMNTransformer(
            inputParameters,
            logger
    );
    transformer.transform(inputFileDirectory.toPath(), outputFileDirectory.toPath());

    try {
        this.project.addCompileSourceRoot(this.outputFileDirectory.getCanonicalPath());
    } catch (IOException e) {
        throw new MojoExecutionException("", e);
    }
}
 
Example #23
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeTokenFile_devModePropertiesAreWritten()
        throws IOException, MojoExecutionException, MojoFailureException {

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, StandardCharsets.UTF_8);
    JsonObject buildInfo = JsonUtil.parse(json);

    Assert.assertTrue(
            Constants.SERVLET_PARAMETER_ENABLE_PNPM
                    + "should have been written",
            buildInfo.getBoolean(Constants.SERVLET_PARAMETER_ENABLE_PNPM));
    Assert.assertTrue(
            Constants.REQUIRE_HOME_NODE_EXECUTABLE
                    + "should have been written",
            buildInfo.getBoolean(Constants.REQUIRE_HOME_NODE_EXECUTABLE));

    Assert.assertFalse(buildInfo
            .hasKey(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE));
}
 
Example #24
Source File: DependencyBuildMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
public void execute()
		throws MojoExecutionException
{
	if (skip || skipDependencyBuild) {
		getLog().info("Skip dependency build");
		return;
	}
	for (String inputDirectory : getChartDirectories(getChartDirectory())) {
		getLog().info("Build chart dependencies for " + inputDirectory + "...");
		callCli(getHelmExecuteablePath()
				+ " dependency build "
				+ inputDirectory
				+ (StringUtils.isNotEmpty(getRegistryConfig()) ? " --registry-config=" + getRegistryConfig() : "")
				+ (StringUtils.isNotEmpty(getRepositoryCache()) ? " --repository-cache=" + getRepositoryCache() : "")
				+ (StringUtils.isNotEmpty(getRepositoryConfig()) ? " --repository-config=" + getRepositoryConfig() : ""),
				"Failed to resolve dependencies", true);
	}
}
 
Example #25
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
protected void writeMetadata(Log log) throws MojoExecutionException {
  writeTestMetadata();
  if (skipDockerInfo) {
    return;
  }
  final File jarFile = buildDockerInfoJar(log);
  attachJar(jarFile);
}
 
Example #26
Source File: StoreGraphDependencyMojo.java    From maven-dependency-mapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void execute() throws MojoExecutionException {
    final HashMap<String, String> config = new HashMap<String, String>();
    restAPI = new RestAPIFacade(neo4jServer + "/db/data");

    config.put("type", "exact");
    config.put("provider", "lucene");
    config.put("to_lower_case", "false");

    index = restAPI.createIndex(Node.class, ARTIFACT, config);

    getDependencies();
    getPlugins();
}
 
Example #27
Source File: EnhanceMojo.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
/**
 * Write a report on any meta data missing from components.
 */
private void writeMissingMetaDataReport(File aReportFile, Multimap<String, String> aReportData)
        throws MojoExecutionException {
  String[] classes = aReportData.keySet().toArray(new String[aReportData.keySet().size()]);
  Arrays.sort(classes);

  PrintWriter out = null;
  FileUtils.mkdir(aReportFile.getParent());
  try {
    out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(aReportFile), encoding));

    if (classes.length > 0) {
      for (String clazz : classes) {
        out.printf("%s %s%n", MARK_CLASS, clazz);
        Collection<String> messages = aReportData.get(clazz);
        if (messages.isEmpty()) {
          out.printf("  No problems");
        } else {
          for (String message : messages) {
            out.printf("  %s%n", message);
          }
        }
        out.printf("%n");
      }
    } else {
      out.printf("%s%n", MARK_NO_MISSING_META_DATA);
    }
  } catch (IOException e) {
    throw new MojoExecutionException("Unable to write missing meta data report to ["
            + aReportFile + "]" + ExceptionUtils.getRootCauseMessage(e), e);
  } finally {
    IOUtils.closeQuietly(out);
  }
}
 
Example #28
Source File: ScaffoldMojo.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        addCompileSourceRoots();
        generateModel();
    } catch (IOException e) {
        throw new MojoExecutionException("An I/O error occurred", e);
    }
}
 
Example #29
Source File: BaseMojo.java    From jax-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();
    log.info("Starting " + cmd + " mojo");

    List<File> outputDirectories = cmd. //
            getDirectoryParameters() //
            .stream() //
            .map(param -> Util.createOutputDirectoryIfSpecifiedOrDefault(log, param, arguments))
            .collect(Collectors.toList());
    try {
        List<String> command = createCommand();

        new ProcessExecutor() //
                .command(command) //
                .directory((project.getBasedir()))
                .exitValueNormal() //
                .redirectOutput(System.out) //
                .redirectError(System.out) //
                .execute();

        outputDirectories.forEach(buildContext::refresh);

        addSources(log);
        
        addResources(log);

    } catch (InvalidExitValueException | IOException | InterruptedException | TimeoutException
            | DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    log.info(cmd + " mojo finished");
}
 
Example #30
Source File: OpenEJBEmbeddedMojo.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    MavenLogStreamFactory.setLogger(getLog());
    final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(createClassLoader(oldCl));

    EJBContainer container = null;
    try {
        container = EJBContainer.createEJBContainer(map());
        if (await) {
            final CountDownLatch latch = new CountDownLatch(1);
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    latch.countDown();
                }
            }));
            try {
                latch.await();
            } catch (final InterruptedException e) {
                // ignored
            }
        }
    } finally {
        if (container != null) {
            container.close();
        }
        Thread.currentThread().setContextClassLoader(oldCl);
    }
}