org.jboss.shrinkwrap.api.importer.ZipImporter Java Examples

The following examples show how to use org.jboss.shrinkwrap.api.importer.ZipImporter. 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: AbstractExampleAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected static WebArchive exampleDeployment(String name, String contextPath, Consumer<WebArchive> additionalResources) throws IOException {
    URL webXML = Paths.get(EXAMPLES_WEB_XML).toUri().toURL();
    String webXmlContent = IOUtils.toString(webXML.openStream(), "UTF-8")
            .replace("%CONTEXT_PATH%", contextPath);
    WebArchive webArchive = ShrinkWrap.create(ZipImporter.class, name + ".war")
            .importFrom(new File(EXAMPLES_HOME + "/" + name + "-" + EXAMPLES_VERSION_SUFFIX + ".war"))
            .as(WebArchive.class)
            .addAsWebInfResource(jbossDeploymentStructure, JBOSS_DEPLOYMENT_STRUCTURE_XML)
            .add(new StringAsset(webXmlContent), "/WEB-INF/web.xml");

    additionalResources.accept(webArchive);

    modifyOIDCAdapterConfig(webArchive);

    return webArchive;
}
 
Example #2
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Import from file and make sure the file is closed.
 *
 * @param log  the logger
 * @param set  the dependency set
 * @param jar  the archive
 * @param file the file, must not be {@code null}
 */
private void embedDependency(Log log, DependencySet set, JavaArchive jar, File file) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        jar.as(ZipImporter.class).importFrom(fis, path -> {
            if (jar.contains(path)) {
                log.debug(path.get() + " already embedded in the jar");
                return false;
            }
            if (!toExclude(set, path)) {
                return true;
            } else {
                log.debug("Excluding " + path.get() + " from " + file.getName());
                return false;
            }
        });
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Unable to read the file " + file.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}
 
Example #3
Source File: BuildTool.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public void repackageWar(File file) throws IOException {
    if (!filterWebInfLib) {
        return;
    }

    this.log.info("Repackaging .war: " + file);

    Path backupPath = get(file);
    move(file, backupPath, this.log);

    Archive original = ShrinkWrap.create(JavaArchive.class);
    try (InputStream inputStream = Files.newInputStream(backupPath)) {
        original.as(ZipImporter.class).importFrom(inputStream);
    }

    Archive repackaged = new WebInfLibFilteringArchive(original, this.dependencyManager);
    repackaged.as(ZipExporter.class).exportTo(file, true);
    this.log.info("Repackaged .war: " + file);
}
 
Example #4
Source File: DefaultDeploymentFactory.java    From thorntail with Apache License 2.0 6 votes vote down vote up
protected boolean setupUsingAppPath(Archive<?> archive) throws IOException {
    final String appPath = System.getProperty(APP_PATH);

    if (appPath != null) {
        final Path path = Paths.get(appPath);
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Path simple = path.relativize(file);
                    archive.add(new FileAsset(file.toFile()), convertSeparators(simple));
                    return super.visitFile(file, attrs);
                }
            });
        } else {
            archive.as(ZipImporter.class)
                    .importFrom(path.toFile());
        }
        return true;
    }

    return false;
}
 
Example #5
Source File: FileAutomaticDeployment.java    From arquillian-container-chameleon with Apache License 2.0 6 votes vote down vote up
@Override
protected Archive<?> build(TestClass testClass) {

    if (testClass.isAnnotationPresent(File.class)) {
        final File file = testClass.getAnnotation(File.class);
        final String location = file.value();

        java.io.File archiveLocation = new java.io.File(location);
        if (!archiveLocation.isAbsolute()) {
            String rootPath = Paths.get(".").toAbsolutePath().toString();
            archiveLocation = new java.io.File(rootPath, location);
        }

        return ShrinkWrap
            .create(ZipImporter.class, getArchiveName(location))
            .importFrom(archiveLocation)
            .as(file.type());
    }

    return null;
}
 
Example #6
Source File: Swarm.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private void createShrinkWrapDomain() {
    ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
    try {
        if (isFatJar()) {
            Module appModule = Module.getBootModuleLoader().loadModule(APPLICATION_MODULE_NAME);
            Thread.currentThread().setContextClassLoader(appModule.getClassLoader());
        }
        Domain domain = ShrinkWrap.getDefaultDomain();
        domain.getConfiguration().getExtensionLoader().addOverride(ZipExporter.class, ZipExporterImpl.class);
        domain.getConfiguration().getExtensionLoader().addOverride(ZipImporter.class, ZipImporterImpl.class);
        domain.getConfiguration().getExtensionLoader().addOverride(ExplodedExporter.class, ExplodedExporterImpl.class);
        domain.getConfiguration().getExtensionLoader().addOverride(ExplodedImporter.class, ExplodedImporterImpl.class);
        domain.getConfiguration().getExtensionLoader().addOverride(JavaArchive.class, JavaArchiveImpl.class);
        domain.getConfiguration().getExtensionLoader().addOverride(WebArchive.class, WebArchiveImpl.class);
    } catch (Exception e) {
        SwarmMessages.MESSAGES.shrinkwrapDomainSetupFailed(e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalCl);
    }
}
 
Example #7
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Import from file and make sure the file is closed.
 *
 * @param log  the logger
 * @param set  the dependency set
 * @param jar  the archive
 * @param file the file, must not be {@code null}
 */
private void embedDependency(Log log, DependencySet set, JavaArchive jar, File file) {
    try (FileInputStream fis = new FileInputStream(file)) {
        jar.as(ZipImporter.class).importFrom(fis, path -> {
            if (jar.contains(path)) {
                log.debug(path.get() + " already embedded in the jar");
                return false;
            }
            if (!toExclude(set, path)) {
                return true;
            } else {
                log.debug("Excluding " + path.get() + " from " + file.getName());
                return false;
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Unable to read the file " + file.getAbsolutePath(), e);
    }
}
 
Example #8
Source File: DefaultDeploymentFactory.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
protected boolean setupUsingAppPath(Archive<?> archive) throws IOException {
    final String appPath = System.getProperty(BootstrapProperties.APP_PATH);

    if (appPath != null) {
        final Path path = Paths.get(appPath);
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Path simple = path.relativize(file);
                    archive.add(new FileAsset(file.toFile()), convertSeparators(simple));
                    return super.visitFile(file, attrs);
                }
            });
        } else {
            archive.as(ZipImporter.class)
                    .importFrom(path.toFile());
        }
        return true;
    }

    return false;
}
 
Example #9
Source File: RuntimeDeployer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
protected static Stream<Archive> archives(Collection<Path> paths) {
    return paths.stream()
            .map(path -> {
                String simpleName = path.getFileName().toString();
                Archive archive = ShrinkWrap.create(JavaArchive.class, simpleName);
                archive.as(ZipImporter.class).importFrom(path.toFile());
                return archive;
            });
}
 
Example #10
Source File: AbstractExampleAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected static WebArchive exampleDeployment(String name, Consumer<WebArchive> additionalResources) {
    WebArchive webArchive = ShrinkWrap.create(ZipImporter.class, name + ".war")
            .importFrom(new File(EXAMPLES_HOME + "/" + name + "-" + EXAMPLES_VERSION_SUFFIX + ".war"))
            .as(WebArchive.class)
            .addAsWebInfResource(jbossDeploymentStructure, JBOSS_DEPLOYMENT_STRUCTURE_XML);

    additionalResources.accept(webArchive);

    modifyOIDCAdapterConfig(webArchive);

    return webArchive;
}
 
Example #11
Source File: AuthServerTestEnricher.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void deployProviders(@Observes(precedence = -1) AfterStart event) throws DeploymentException {
    if (isAuthServerRemote() && currentContainerName.contains("auth-server")) {
        this.testsuiteProvidersArchive = ShrinkWrap.create(ZipImporter.class, "testsuiteProviders.jar")
                .importFrom(Maven.configureResolverViaPlugin()
                    .resolve("org.keycloak.testsuite:integration-arquillian-testsuite-providers")
                    .withoutTransitivity()
                    .asSingleFile()
                ).as(JavaArchive.class)
                .addAsManifestResource("jboss-deployment-structure.xml");
                
        event.getDeployableContainer().deploy(testsuiteProvidersArchive);
    }
}
 
Example #12
Source File: DistributionController.java    From arquillian-container-chameleon with Apache License 2.0 5 votes vote down vote up
private File downloadUsingHttp() {
    final String distribution = targetAdapter.distribution();
    final String serverName = new FileNameFromUrlExtractor(distribution).extract();
    final File targetDirectory = new File(new File(distributionDownloadFolder, "server"),
        serverName);

    if (serverAlreadyDownloaded(targetDirectory)) {
        return getDistributionHome(targetDirectory);
    }

    System.out.println("Arquillian Chameleon: downloading distribution from " + distribution);
    final String targetArchive = targetDirectory + "/" + serverName + ".zip";
    final Execution<File> download =
        Spacelift.task(DownloadTool.class).from(distribution).to(targetArchive).execute();
    try {
        while (!download.isFinished()) {
            System.out.print(PROGRESS_INDICATOR);
            Thread.sleep(HALF_A_SECOND);
        }
        System.out.print(PROGRESS_INDICATOR);

        final File compressedServer = download.await();
        ShrinkWrap.create(ZipImporter.class, serverName)
            .importFrom(compressedServer)
            .as(ExplodedExporter.class)
            .exportExploded(targetDirectory, ".");
        compressedServer.delete();
        return getDistributionHome(targetDirectory);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: AbstractBootstrapIntegrationTestCase.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
protected JavaArchive createBootstrapArchive(String mainClassName, String appArtifact) throws IOException {
    JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
    archive.as(ZipImporter.class).importFrom(new JarFile(findBootstrapJar()));


    Properties props = new Properties();
    if (appArtifact != null) {
        props.put(BootstrapProperties.APP_ARTIFACT, appArtifact);
    }
    ByteArrayOutputStream propsOut = new ByteArrayOutputStream();
    props.store(propsOut, "");
    propsOut.close();
    archive.addAsManifestResource(new ByteArrayAsset(propsOut.toByteArray()), "wildfly-swarm.properties");

    if (appArtifact != null) {
        String conf = "path:" + appArtifact + "\n";
        archive.addAsManifestResource(new ByteArrayAsset(conf.getBytes()), "wildfly-swarm-application.conf");
    }

    if (mainClassName != null) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(new Attributes.Name("Wildfly-Swarm-Main-Class"), mainClassName);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        manifest.write(out);
        out.close();
        archive.addAsManifestResource(new ByteArrayAsset(out.toByteArray()), "MANIFEST.MF");
    }
    return archive;
}
 
Example #14
Source File: DefaultDeploymentFactory.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
protected boolean setupUsingAppArtifact(Archive<?> archive) throws IOException {
    final String appArtifact = System.getProperty(BootstrapProperties.APP_ARTIFACT);

    if (appArtifact != null) {
        try (InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("_bootstrap/" + appArtifact)) {
            archive.as(ZipImporter.class)
                    .importFrom(in);
        }
        return true;
    }

    return false;
}
 
Example #15
Source File: ArtifactManager.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
public JavaArchive artifact(String gav, String asName) throws IOException, ModuleLoadException {
    final File file = findFile(gav);

    if (file == null) {
        throw new RuntimeException("Artifact not found.");
    }

    return ShrinkWrap.create(ZipImporter.class, asName == null ? file.getName() : asName)
            .importFrom(file)
            .as(JavaArchive.class);
}
 
Example #16
Source File: FilteredProjectAsset.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream openStream() {
    return filter(ShrinkWrap.create(ZipImporter.class)
            .importFrom(this.delegate.openStream())
            .as(JavaArchive.class))
            .as(ZipExporter.class)
            .exportAsInputStream();
}
 
Example #17
Source File: ArtifactManager.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public List<JavaArchive> allArtifacts(String... groupIdExclusions) throws IOException {
    Map<String, JavaArchive> archives = new HashMap<>();
    Set<String> archivesPaths;

    final List<String> exclusions = Arrays.asList(groupIdExclusions);

    ApplicationEnvironment env = ApplicationEnvironment.get();
    archivesPaths = env.resolveDependencies(exclusions);

    // package the shrinkwrap bits
    for (final String element : archivesPaths) {

        final File artifact = new File(element);

        if (artifact.isFile()) {
            archives.put(artifact.getName(), ShrinkWrap.create(ZipImporter.class, artifact.getName())
                    .importFrom(artifact)
                    .as(JavaArchive.class));
        } else {

            final String archiveName = FileSystemLayout.archiveNameForClassesDir(artifact.toPath());

            // pack resources and classes of the same project into one archive
            if (archives.containsKey(archiveName)) {
                archives.get(archiveName).as(ExplodedImporter.class).importDirectory(artifact);
            } else {
                archives.put(archiveName, ShrinkWrap.create(ExplodedImporter.class, archiveName)
                        .importDirectory(artifact)
                        .as(JavaArchive.class));
            }
        }
    }

    return new ArrayList<>(archives.values());
}
 
Example #18
Source File: ArtifactManager.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public JavaArchive artifact(String gav, String asName) throws IOException, ModuleLoadException {
    final File file = findFile(gav);

    if (file == null) {
        throw SwarmMessages.MESSAGES.artifactNotFound(gav);
    }

    return ShrinkWrap.create(ZipImporter.class, asName == null ? file.getName() : asName)
            .importFrom(file)
            .as(JavaArchive.class);
}
 
Example #19
Source File: DefaultDeploymentFactory.java    From thorntail with Apache License 2.0 5 votes vote down vote up
protected boolean setupUsingAppArtifact(Archive<?> archive) throws IOException {
    final String appArtifact = System.getProperty(APP_ARTIFACT);

    if (appArtifact != null) {
        try (InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("_bootstrap/" + appArtifact)) {
            archive.as(ZipImporter.class)
                    .importFrom(in);
        }
        return true;
    }

    return false;
}
 
Example #20
Source File: SecuredArchivePreparer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private static InputStream getKeycloakJsonFromClasspath(String resourceName) {
    InputStream keycloakJson = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
    if (keycloakJson == null) {

        String appArtifact = System.getProperty(BootstrapProperties.APP_ARTIFACT);

        if (appArtifact != null) {
            try (InputStream in = loadAppArtifact(appArtifact)) {
                Archive<?> tmpArchive = ShrinkWrap.create(JARArchive.class);
                tmpArchive.as(ZipImporter.class).importFrom(in);
                Node jsonNode = tmpArchive.get(resourceName);
                if (jsonNode == null) {
                    jsonNode = getKeycloakJsonNodeFromWebInf(tmpArchive, resourceName, true);
                }
                if (jsonNode == null) {
                    jsonNode = getKeycloakJsonNodeFromWebInf(tmpArchive, resourceName, false);
                }
                if (jsonNode != null && jsonNode.getAsset() != null) {
                    keycloakJson = jsonNode.getAsset().openStream();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return keycloakJson;
}
 
Example #21
Source File: ArchiveUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Indexes the given archive.
 * 
 * @param config
 * @param indexer
 * @param archive
 */
private static void indexArchive(OpenApiConfig config, Indexer indexer, Archive<?> archive) {
    FilteredIndexView filter = new FilteredIndexView(null, config);
    Map<ArchivePath, Node> c = archive.getContent();
    try {
        for (Map.Entry<ArchivePath, Node> each : c.entrySet()) {
            ArchivePath archivePath = each.getKey();
            if (archivePath.get().endsWith(OpenApiConstants.CLASS_SUFFIX)
                    && acceptClassForScanning(filter, archivePath.get())) {
                try (InputStream contentStream = each.getValue().getAsset().openStream()) {
                    TckLogging.log.indexing(archivePath.get(), archive.getName());
                    indexer.index(contentStream);
                }
                continue;
            }
            if (archivePath.get().endsWith(OpenApiConstants.JAR_SUFFIX)
                    && acceptJarForScanning(config, archivePath.get())) {
                try (InputStream contentStream = each.getValue().getAsset().openStream()) {
                    JavaArchive jarArchive = ShrinkWrap.create(JavaArchive.class, archivePath.get())
                            .as(ZipImporter.class).importFrom(contentStream).as(JavaArchive.class);
                    indexArchive(config, indexer, jarArchive);
                }
                continue;
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: GradleBuildAutomaticDeployment.java    From arquillian-container-chameleon with Apache License 2.0 4 votes vote down vote up
private Archive<?> runBuild(GradleBuild conf) {
  	
  	ProjectConnection projectConnector = GradleConnector
  		.newConnector()
  		.forProjectDirectory(new File(conf.path()))
  		.connect();
  	
  	BuildLauncher launcher = projectConnector
  		.newBuild()
  		.forTasks(conf.tasks())
  		.withArguments("-x", "test");
  	
  	if (!conf.quiet()) {
   	launcher.withArguments("--info", "--stacktrace");
   	launcher.setStandardOutput(System.out);
       launcher.setStandardError(System.err);
  	}
  	launcher.run();
  	
  	GradleProject projectModel = projectConnector.getModel(GradleProject.class);
final Path artifactDir = projectModel.getBuildDirectory().toPath().resolve("libs");

Path artifactPath = null;
try (DirectoryStream<Path> filesInArtifactDir = Files.newDirectoryStream(artifactDir)) {
	for (Path file : filesInArtifactDir) {
              if (file.toString().endsWith(".war")) {
              	artifactPath = file;
              	break;
              }
          }
} catch (Exception e) {
	throw new RuntimeException(e);
}
	
if (artifactPath == null) {
	throw new RuntimeException("No .war-file found in " + artifactDir.toString() + ".");
}

return ShrinkWrap
		  .create(ZipImporter.class, artifactPath.getFileName().toString())
		  .importFrom(artifactPath.toFile())
		  .as(WebArchive.class);

  }
 
Example #23
Source File: SwaggerWebAppDeploymentProducer.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Produces
public Archive swaggerWebApp() throws ModuleLoadException, IOException {

    // Load the swagger-ui webjars.
    Module module = Module.getBootModuleLoader().loadModule("org.webjars.swagger-ui");
    URL resource = module.getExportedResource("swagger-ui.jar");
    JARArchive webJar = ShrinkWrap.create(JARArchive.class);
    webJar.as(ZipImporter.class).importFrom(resource.openStream());


    JARArchive relocatedJar = ShrinkWrap.create(JARArchive.class);

    Map<ArchivePath, Node> content = webJar.getContent();

    // relocate out the webjars/swagger-ui/${VERISON}

    for (ArchivePath path : content.keySet()) {
        Node node = content.get(path);
        Asset asset = node.getAsset();
        if (asset != null) {
            Matcher matcher = PATTERN.matcher(path.get());
            if (matcher.matches()) {
                MatchResult result = matcher.toMatchResult();
                String newPath = "/META-INF/resources/" + result.group(2);
                relocatedJar.add(asset, newPath);
            }
        }
    }

    WARArchive war = ShrinkWrap.create(WARArchive.class, "swagger-ui.war")
            .addAsLibrary(relocatedJar)
            .setContextRoot(this.fraction.getContext());
    war.addClass(SwaggerDefaultUrlChangerServlet.class);

    // If any user content has been provided, merge that with the swagger-ui bits
    Archive<?> userContent = this.fraction.getWebContent();
    if (userContent != null) {
        war.merge(userContent);
    }

    return war;
}
 
Example #24
Source File: MicroOuterDeployer.java    From piranha with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Helper method that gets and imports a ZipFileEntry resource from a ShrinkWrapResource as
 * another ShrinkWrapResource.
 * 
 * @param resource the ShrinkWrapResource used as the source
 * @param location the location of the target resource within the resource
 * @return a ShrinkWrapResource version of the target resource
 */
private ShrinkWrapResource importAsShrinkWrapResource(ShrinkWrapResource resource, String location) {
    return new ShrinkWrapResource(
        ShrinkWrap.create(ZipImporter.class, location.substring(1))
                  .importFrom(
                      resource.getResourceAsStreamByLocation(location))
                  .as(JavaArchive.class));
}