Search in sources :

Example 16 with MavenResolver

use of io.fabric8.maven.MavenResolver in project fabric8 by jboss-fuse.

the class ArchetypeGenerateAction method fetchArchetype.

/**
 * Fetches archetype from the configured repositories
 * TODO: make this code available to hawt.io/JMX too
 */
private File fetchArchetype(Archetype archetype) throws IOException {
    MavenResolver resolver = MavenResolvers.createMavenResolver(new Hashtable<String, String>(), "org.ops4j.pax.url.mvn");
    DownloadManager dm = DownloadManagers.createDownloadManager(resolver, Executors.newSingleThreadScheduledExecutor());
    final AtomicReference<File> file = new AtomicReference<>();
    String url = String.format("mvn:%s/%s/%s", archetype.groupId, archetype.artifactId, archetype.version);
    Downloader downloader = dm.createDownloader();
    downloader.download(url, new DownloadCallback() {

        @Override
        public void downloaded(StreamProvider provider) throws Exception {
            file.set(provider.getFile());
        }
    });
    // wait for download
    try {
        boolean init = false;
        for (int i = 0; i < 2 * 60 && file.get() == null; i++) {
            // dont do anything in the first 3 seconds as we likely can download it faster
            if (i > 3) {
                if (!init) {
                    System.out.print("Downloading archetype in progress: ");
                    init = true;
                }
                System.out.print(".");
            }
            // only sleep 0.5 sec so we can react faster
            Thread.sleep(500);
        }
    } catch (InterruptedException e) {
        System.err.println("\nFailed to download " + archetype);
        throw new IOException(e.getMessage(), e);
    }
    try {
        downloader.await();
        return file.get();
    } catch (Exception e) {
        System.err.println("\nFailed to download archetype within 60 seconds: " + archetype);
        throw new IOException("Failed to download archetype within 60 seconds: " + archetype);
    }
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) DownloadManager(io.fabric8.agent.download.DownloadManager) IOException(java.io.IOException) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File)

Example 17 with MavenResolver

use of io.fabric8.maven.MavenResolver in project fabric8 by jboss-fuse.

the class DownloadManagerTest method createDownloadManager.

/**
 * Prepares DownloadManager to test
 *
 * @param remoteRepo
 * @param settingsFile
 * @param props
 * @return
 * @throws IOException
 */
private DownloadManager createDownloadManager(String remoteRepo, String settingsFile, Properties props) throws IOException {
    File mavenSettings = new File(karafHome, settingsFile);
    Hashtable<String, String> properties = new Hashtable<>();
    if (props != null) {
        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            properties.put(entry.getKey().toString(), entry.getValue().toString());
        }
    }
    properties.put("org.ops4j.pax.url.mvn.localRepository", systemRepoUri);
    properties.put("org.ops4j.pax.url.mvn.repositories", remoteRepo);
    properties.put("org.ops4j.pax.url.mvn.defaultRepositories", systemRepoUri);
    properties.put("org.ops4j.pax.url.mvn.settings", mavenSettings.toURI().toString());
    MavenResolver resolver = MavenResolvers.createMavenResolver(properties, "org.ops4j.pax.url.mvn");
    return DownloadManagers.createDownloadManager(resolver, Executors.newSingleThreadScheduledExecutor());
}
Also used : Hashtable(java.util.Hashtable) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File) Map(java.util.Map)

Example 18 with MavenResolver

use of io.fabric8.maven.MavenResolver in project fabric8 by jboss-fuse.

the class AgentTest method testAgent.

@Test
public void testAgent() throws Exception {
    System.setProperty("karaf.data", new File("target/karaf/data").getAbsolutePath());
    System.setProperty("karaf.home", new File("target/karaf").getAbsolutePath());
    Dictionary<String, String> resolverProps = new Hashtable<>();
    resolverProps.put(ServiceConstants.PROPERTY_REPOSITORIES, "http://repository.jboss.org/nexus/content/repositories/fs-public/@id=jboss.fs.public," + "https://repository.jboss.org/nexus/content/groups/ea/@id=jboss.ea.repo," + "http://repo1.maven.org/maven2@id=maven.central.repo," + "http://download.eng.bos.redhat.com/brewroot/repos/jb-fuse-6.2-build/latest/maven@id=brew");
    MavenResolver mavenResolver = MavenResolvers.createMavenResolver(resolverProps, null);
    DownloadManager manager = DownloadManagers.createDownloadManager(mavenResolver, Executors.newScheduledThreadPool(8));
    BundleContext systemBundleContext = createMock(BundleContext.class);
    TestSystemBundle systemBundle = createTestSystemBundle("/common", "system-bundle");
    systemBundle.setBundleContext(systemBundleContext);
    Bundle serviceBundle = createTestBundle(1l, Bundle.ACTIVE, "/common", "fabric-agent");
    expect(systemBundleContext.getBundle()).andReturn(systemBundle).anyTimes();
    expect(systemBundleContext.getBundles()).andReturn(new Bundle[] { systemBundle }).anyTimes();
    long nextBundleId = 2;
    List<Bundle> mockBundles = new ArrayList<>();
    String karafVersion = System.getProperty("karaf-version");
    String[] bundles = { "mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.api/1.0.1", "mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.cm/1.1.0", "mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.core/1.8.0", "mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.core.compatibility/1.0.0", "mvn:org.apache.aries.proxy/org.apache.aries.proxy/1.1.1", "mvn:org.apache.aries/org.apache.aries.util/1.1.3", "mvn:org.apache.felix/org.apache.felix.configadmin/1.8.12", "mvn:org.apache.karaf.jaas/org.apache.karaf.jaas.command/" + karafVersion, "mvn:org.apache.karaf.jaas/org.apache.karaf.jaas.config/" + karafVersion, "mvn:org.apache.karaf.jaas/org.apache.karaf.jaas.modules/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.commands/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.console/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.dev/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.log/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.osgi/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.packages/" + karafVersion, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.ssh/" + karafVersion, "mvn:org.apache.mina/mina-core/2.0.13", "mvn:org.apache.sshd/sshd-core/0.14.0.redhat-001", "mvn:org.ow2.asm/asm-all/5.0.4", "mvn:org.ops4j.pax.logging/pax-logging-api/1.9.1", "mvn:org.ops4j.pax.logging/pax-logging-service/1.9.1" };
    for (String bundleUri : bundles) {
        File file = mavenResolver.download(bundleUri);
        Hashtable<String, String> headers = doGetMetadata(file);
        TestBundle bundle = new TestBundle(++nextBundleId, bundleUri, Bundle.INSTALLED, headers) {

            @Override
            public void setStartLevel(int startlevel) {
            }

            @Override
            public void start() throws BundleException {
            }
        };
        expect(systemBundleContext.installBundle(EasyMock.eq(bundleUri), EasyMock.<InputStream>anyObject())).andReturn(bundle);
    }
    ServiceRegistration registration = EasyMock.createMock(ServiceRegistration.class);
    expect(systemBundleContext.registerService(EasyMock.eq(ResolverHookFactory.class), EasyMock.<ResolverHookFactory>anyObject(), EasyMock.<Dictionary>isNull())).andReturn(registration);
    registration.unregister();
    replay(systemBundleContext, registration);
    for (Bundle bundle : mockBundles) {
        replay(bundle);
    }
    Agent agent = new Agent(serviceBundle, systemBundleContext, manager) {

        @Override
        protected <T> void awaitService(Class<T> serviceClass, String filterspec, int timeout, TimeUnit timeUnit) {
        }
    };
    String karafFeaturesUrl = "mvn:org.apache.karaf.assemblies.features/standard/" + System.getProperty("karaf-version") + "/xml/features";
    agent.provision(Collections.singleton(karafFeaturesUrl), Collections.singleton("ssh"), Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.<String>emptySet(), new HashSet<>(Arrays.asList("mvn:org.ops4j.pax.logging/pax-logging-api/1.9.1", "mvn:org.ops4j.pax.logging/pax-logging-service/1.9.1", "mvn:org.apache.felix/org.apache.felix.configadmin/1.8.12")), Collections.<String, Map<VersionRange, Map<String, String>>>emptyMap());
}
Also used : ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) Bundle(org.osgi.framework.Bundle) VersionRange(org.apache.felix.utils.version.VersionRange) DownloadManager(io.fabric8.agent.download.DownloadManager) MavenResolver(io.fabric8.maven.MavenResolver) TimeUnit(java.util.concurrent.TimeUnit) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 19 with MavenResolver

use of io.fabric8.maven.MavenResolver in project fabric8 by jboss-fuse.

the class MavenProxyResolutionTest method releaseIsAvailableInRemoteRepositoryUpdatingRelease.

@Test
public void releaseIsAvailableInRemoteRepositoryUpdatingRelease() throws IOException, InvalidMavenArtifactRequest {
    File remoteRepository = initFileRepository("rr");
    MavenResolver resolver = new ResolverBuilder().withRemoteRepositories(Collections.singletonList(remoteRepository)).withReleaseUpdates().withUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS).build();
    MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, runtime, null, 1, 0);
    mvnInstall(remoteRepository, "io.fabric8.test", "universalis-api", "0.1.0", at("10:00"), "a");
    File file = servlet.download("io/fabric8/test/universalis-api/0.1.0/universalis-api-0.1.0.jar");
    // first resolution
    assertThat(FileUtils.readFileToString(file), equalTo("a"));
    // don't do that, it's not proper use of maven. But sometimes we just have another deployment to public repository...
    mvnInstall(remoteRepository, "io.fabric8.test", "universalis-api", "0.1.0", at("11:00"), "b");
    // second resolution
    file = servlet.download("io/fabric8/test/universalis-api/0.1.0/universalis-api-0.1.0.jar");
    assertThat("Artifact will be updated though it's not proper usage of Maven", FileUtils.readFileToString(file), equalTo("b"));
}
Also used : MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File) Test(org.junit.Test)

Example 20 with MavenResolver

use of io.fabric8.maven.MavenResolver in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUpload.

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getContentType()).andReturn("text/plain").anyTimes();
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
        EasyMock.expect(request.getParameter("profile")).andReturn(profile);
        EasyMock.expect(request.getParameter("version")).andReturn(version);
        final Map<String, String> headers = new HashMap<>();
        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {

            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        EasyMock.replay(request, rm);
        servlet.start();
        servlet.doPut(request, response);
        EasyMock.verify(request, rm);
        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));
        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ReadListener(javax.servlet.ReadListener) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties)

Aggregations

MavenResolver (io.fabric8.maven.MavenResolver)23 File (java.io.File)18 Test (org.junit.Test)11 IOException (java.io.IOException)9 Metadata (org.apache.maven.artifact.repository.metadata.Metadata)6 Hashtable (java.util.Hashtable)5 DownloadManager (io.fabric8.agent.download.DownloadManager)4 RuntimeProperties (io.fabric8.api.RuntimeProperties)4 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)4 MavenConfigurationImpl (io.fabric8.maven.util.MavenConfigurationImpl)4 HashMap (java.util.HashMap)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Server (org.eclipse.jetty.server.Server)3 ServerConnector (org.eclipse.jetty.server.ServerConnector)3 DictionaryPropertyResolver (org.ops4j.util.property.DictionaryPropertyResolver)3 DownloadCallback (io.fabric8.agent.download.DownloadCallback)2 Downloader (io.fabric8.agent.download.Downloader)2 StreamProvider (io.fabric8.agent.download.StreamProvider)2