Search in sources :

Example 31 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class InsightRequestLog method log.

@Override
public void log(Request request, Response response) {
    try {
        if (!enabled) {
            return;
        }
        StorageService s = storage.getService();
        if (s == null) {
            return;
        }
        if (ignorePathMap != null && ignorePathMap.getMatch(request.getRequestURI()) != null)
            return;
        String output = "{ " + "\"host\": \"" + host + "\", " + "\"@timestamp\": \"" + InsightUtils.formatDate(request.getTimeStamp()) + "\", " + "\"remote\": \"" + request.getRemoteAddr() + "\", " + "\"user\": \"" + (request.getAuthentication() instanceof Authentication.User ? ((Authentication.User) request.getAuthentication()).getUserIdentity().getUserPrincipal().getName() : "") + "\", " + "\"method\": \"" + request.getMethod() + "\", " + "\"uri\": \"" + request.getUri().toString() + "\", " + "\"protocol\": \"" + request.getProtocol() + "\", " + "\"status\": \"" + response.getStatus() + "\", " + "\"responseLength\": \"" + response.getContentCount() + "\" " + " }";
        s.store(type, request.getTimeStamp(), output);
    } catch (Exception e) {
        LOG.warn(e);
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) StorageService(io.fabric8.insight.storage.StorageService)

Example 32 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class Agent method provision.

public void provision(Map<String, Feature> allFeatures, Set<String> features, Set<String> bundles, Set<String> reqs, Set<String> overrides, Set<String> optionals, Map<String, Map<VersionRange, Map<String, String>>> metadata) throws Exception {
    Callable<Map<String, Resource>> res = loadResources(manager, metadata, optionals);
    // TODO: requirements should be able to be assigned to a region
    Map<String, Set<String>> requirements = new HashMap<>();
    for (String feature : features) {
        addToMapSet(requirements, ROOT_REGION, "feature:" + feature);
    }
    for (String bundle : bundles) {
        addToMapSet(requirements, ROOT_REGION, "bundle:" + bundle);
    }
    for (String req : reqs) {
        addToMapSet(requirements, ROOT_REGION, "req:" + req);
    }
    Deployer.DeploymentRequest request = new Deployer.DeploymentRequest();
    request.updateSnaphots = updateSnaphots;
    request.bundleUpdateRange = bundleUpdateRange;
    request.featureResolutionRange = featureResolutionRange;
    request.globalRepository = new StaticRepository(res.call().values());
    request.overrides = overrides;
    request.requirements = requirements;
    request.stateChanges = Collections.emptyMap();
    request.options = options;
    request.metadata = metadata;
    request.bundleStartTimeout = bundleStartTimeout;
    Deployer.DeploymentState dstate = new Deployer.DeploymentState();
    // Service bundle
    dstate.serviceBundle = serviceBundle;
    // Start level
    FrameworkStartLevel fsl = systemBundleContext.getBundle().adapt(FrameworkStartLevel.class);
    dstate.initialBundleStartLevel = fsl.getInitialBundleStartLevel();
    dstate.currentStartLevel = fsl.getStartLevel();
    // Bundles
    dstate.bundles = new HashMap<>();
    for (Bundle bundle : systemBundleContext.getBundles()) {
        dstate.bundles.put(bundle.getBundleId(), bundle);
    }
    // Features
    dstate.features = allFeatures;
    // Region -> bundles mapping
    // Region -> policy mapping
    dstate.bundlesPerRegion = new HashMap<>();
    dstate.filtersPerRegion = new HashMap<>();
    if (digraph == null) {
        for (Long id : dstate.bundles.keySet()) {
            addToMapSet(dstate.bundlesPerRegion, ROOT_REGION, id);
        }
    } else {
        RegionDigraph clone = digraph.copy();
        for (Region region : clone.getRegions()) {
            // Get bundles
            dstate.bundlesPerRegion.put(region.getName(), new HashSet<>(region.getBundleIds()));
            // Get policies
            Map<String, Map<String, Set<String>>> edges = new HashMap<>();
            for (RegionDigraph.FilteredRegion fr : clone.getEdges(region)) {
                Map<String, Set<String>> policy = new HashMap<>();
                Map<String, Collection<String>> current = fr.getFilter().getSharingPolicy();
                for (String ns : current.keySet()) {
                    for (String f : current.get(ns)) {
                        addToMapSet(policy, ns, f);
                    }
                }
                edges.put(fr.getRegion().getName(), policy);
            }
            dstate.filtersPerRegion.put(region.getName(), edges);
        }
    }
    final State state = new State();
    try {
        storage.load(state);
    } catch (IOException e) {
        LOGGER.warn("Error loading agent state", e);
    }
    if (state.managedBundles.isEmpty()) {
        for (Bundle b : systemBundleContext.getBundles()) {
            if (b.getBundleId() != 0) {
                addToMapSet(state.managedBundles, ROOT_REGION, b.getBundleId());
            }
        }
    }
    // corresponding jar url and use that one to compute the checksum of the bundle.
    for (Map.Entry<Long, Bundle> entry : dstate.bundles.entrySet()) {
        long id = entry.getKey();
        Bundle bundle = entry.getValue();
        if (id > 0 && isUpdateable(bundle) && !state.bundleChecksums.containsKey(id)) {
            try {
                URL url = bundle.getResource("META-INF/MANIFEST.MF");
                URLConnection con = url.openConnection();
                Method method = con.getClass().getDeclaredMethod("getLocalURL");
                method.setAccessible(true);
                String jarUrl = ((URL) method.invoke(con)).toExternalForm();
                if (jarUrl.startsWith("jar:")) {
                    String jar = jarUrl.substring("jar:".length(), jarUrl.indexOf("!/"));
                    jar = new URL(jar).getFile();
                    long checksum = ChecksumUtils.checksumFile(new File(jar));
                    state.bundleChecksums.put(id, checksum);
                }
            } catch (Throwable t) {
                LOGGER.debug("Error calculating checksum for bundle: %s", bundle, t);
            }
        }
    }
    dstate.state = state;
    Set<String> prereqs = new HashSet<>();
    while (true) {
        try {
            Deployer.DeployCallback callback = new BaseDeployCallback() {

                @Override
                public void phase(String message) {
                    Agent.this.updateStatus(message);
                }

                @Override
                public void saveState(State newState) {
                    state.replace(newState);
                    try {
                        Agent.this.saveState(newState);
                    } catch (IOException e) {
                        LOGGER.warn("Error storing agent state", e);
                    }
                }

                @Override
                public void provisionList(Set<Resource> resources) {
                    Agent.this.provisionList(resources);
                }

                @Override
                public void restoreConfigAdminIfNeeded() {
                    if (configInstaller != null) {
                        configInstaller.restoreConfigAdminIfNeeded();
                    }
                }

                @Override
                public boolean done(boolean agentStarted, List<String> urls) {
                    return Agent.this.done(agentStarted, urls);
                }
            };
            // FABRIC-790, FABRIC-981 - wait for ProfileUrlHandler before attempting to load bundles (in subsystem.resolve())
            // (which may be the case with bundle.xxx=blueprint:profile:xxx URLs in io.fabric8.agent PID)
            // https://developer.jboss.org/message/920681 - 30 seconds is too low sometimes
            // there was "url.handler.timeouts" option for agent, but it was removed during migration to karaf 4.x resolver
            // LOGGER.debug("Waiting for ProfileUrlHandler");
            // awaitService(URLStreamHandlerService.class, "(url.handler.protocol=profile)", 30, TimeUnit.SECONDS);
            // LOGGER.debug("Waiting for ProfileUrlHandler finished");
            Deployer deployer = new Deployer(manager, callback);
            deployer.setDeploymentAgentId(deploymentAgentId);
            deployer.deploy(dstate, request);
            break;
        } catch (Deployer.PartialDeploymentException e) {
            if (!prereqs.containsAll(e.getMissing())) {
                prereqs.addAll(e.getMissing());
            } else {
                throw new Exception("Deployment aborted due to loop in missing prerequisites: " + e.getMissing());
            }
        }
    }
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) MapUtils.addToMapSet(io.fabric8.agent.internal.MapUtils.addToMapSet) HashSet(java.util.HashSet) HashMap(java.util.HashMap) URL(java.net.URL) List(java.util.List) HashSet(java.util.HashSet) RegionDigraph(org.eclipse.equinox.region.RegionDigraph) Bundle(org.osgi.framework.Bundle) IOException(java.io.IOException) Method(java.lang.reflect.Method) FrameworkStartLevel(org.osgi.framework.startlevel.FrameworkStartLevel) URLConnection(java.net.URLConnection) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MultiException(io.fabric8.common.util.MultiException) Region(org.eclipse.equinox.region.Region) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) StaticRepository(io.fabric8.agent.repository.StaticRepository)

Example 33 with Request

use of io.fabric8.insight.metrics.model.Request 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)

Example 34 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUploadWithMimeMultipartFormData.

@Test
public void testUploadWithMimeMultipartFormData() throws Exception {
    new File("target/maven/proxy/tmp/multipart").mkdirs();
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
    addEntry(jas, "META-INF/maven/io.fabric8/mybundle/pom.properties", "groupId=io.fabric8\nartifactId=mybundle\nversion=1.0\n".getBytes());
    jas.close();
    byte[] jarBytes = baos.toByteArray();
    RuntimeProperties props = new MockRuntimeProperties();
    MavenResolver resolver = EasyMock.createMock(MavenResolver.class);
    MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
    servlet.setFileItemFactory(new DiskFileItemFactory(0, new File("target/maven/proxy/tmp/multipart")));
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    FilePart part = new FilePart("file[]", new ByteArrayPartSource("mybundle-1.0.jar", jarBytes));
    MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { part }, new HttpMethodParams());
    final ByteArrayOutputStream requestBytes = new ByteArrayOutputStream();
    entity.writeRequest(requestBytes);
    final byte[] multipartRequestBytes = requestBytes.toByteArray();
    EasyMock.expect(request.getPathInfo()).andReturn("/mybundle-1.0.jar");
    EasyMock.expect(request.getHeader(MavenProxyServletSupport.LOCATION_HEADER)).andReturn(null);
    EasyMock.expect(request.getParameter("profile")).andReturn("my");
    EasyMock.expect(request.getParameter("version")).andReturn("1.0");
    EasyMock.expect(request.getContentType()).andReturn(entity.getContentType()).anyTimes();
    EasyMock.expect(request.getHeader("Content-length")).andReturn(Long.toString(entity.getContentLength())).anyTimes();
    EasyMock.expect(request.getContentLength()).andReturn((int) entity.getContentLength()).anyTimes();
    EasyMock.expect(request.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes();
    Capture<String> location = EasyMock.newCapture(CaptureType.ALL);
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
    EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

        private int pos = 0;

        @Override
        public int read() throws IOException {
            return pos >= multipartRequestBytes.length ? -1 : (multipartRequestBytes[pos++] & 0xFF);
        }

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

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

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    });
    Capture<ProjectRequirements> requirementsCapture = EasyMock.newCapture(CaptureType.FIRST);
    EasyMock.expect(projectDeployer.deployProject(EasyMock.capture(requirementsCapture), EasyMock.eq(true))).andReturn(null);
    EasyMock.replay(resolver, request, response, projectDeployer);
    servlet.doPut(request, response);
    FileInputStream fis = new FileInputStream("target/upload/io.fabric8/mybundle/1.0/mybundle-1.0.jar");
    ByteArrayOutputStream storedBundleBytes = new ByteArrayOutputStream();
    IOUtils.copy(fis, storedBundleBytes);
    fis.close();
    Assert.assertArrayEquals(jarBytes, storedBundleBytes.toByteArray());
    ProjectRequirements pr = requirementsCapture.getValue();
    List<String> bundles = pr.getBundles();
    assertThat(bundles.size(), equalTo(1));
    assertThat(bundles.get(0), equalTo("mvn:io.fabric8/mybundle/1.0"));
    assertThat(pr.getProfileId(), equalTo("my"));
    assertThat(pr.getVersion(), equalTo("1.0"));
    assertThat(pr.getGroupId(), nullValue());
    assertThat(pr.getArtifactId(), nullValue());
    EasyMock.verify(resolver, request, response, projectDeployer);
}
Also used : ReadListener(javax.servlet.ReadListener) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) ProjectRequirements(io.fabric8.deployer.dto.ProjectRequirements) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) JarOutputStream(java.util.jar.JarOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) FileInputStream(java.io.FileInputStream) File(java.io.File)

Example 35 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testDownloadMetadata.

@Test(timeout = 30000)
public void testDownloadMetadata() 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 {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n" + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n" + "  <versioning>\n" + "    <latest>2.14.0</latest>\n" + "    <release>2.14.0</release>\n" + "    <versions>\n" + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n" + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n" + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n" + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n" + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n" + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n" + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n" + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n" + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n" + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n" + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n" + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n" + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n" + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n" + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n" + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n" + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n" + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n" + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n" + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n" + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n" + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n" + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n" + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n" + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n" + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n" + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n" + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n" + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n" + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n" + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n" + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n" + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n" + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n" + "      <version>2.10.0.redhat-60074</version>\n" + "      <version>2.12.0.redhat-610312</version>\n" + "      <version>2.12.0.redhat-610328</version>\n" + "      <version>2.12.0.redhat-610355</version>\n" + "      <version>2.12.0.redhat-610378</version>\n" + "      <version>2.12.0.redhat-610396</version>\n" + "      <version>2.12.0.redhat-610399</version>\n" + "      <version>2.12.0.redhat-610401</version>\n" + "      <version>2.12.0.redhat-610402</version>\n" + "      <version>2.12.0.redhat-611403</version>\n" + "      <version>2.12.0.redhat-611405</version>\n" + "      <version>2.12.0.redhat-611406</version>\n" + "      <version>2.12.0.redhat-611408</version>\n" + "      <version>2.12.0.redhat-611409</version>\n" + "      <version>2.12.0.redhat-611410</version>\n" + "      <version>2.12.0.redhat-611411</version>\n" + "      <version>2.12.0.redhat-611412</version>\n" + "      <version>2.14.0.redhat-620031</version>\n" + "      <version>2.14.0.redhat-620033</version>\n" + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n" + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n" + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5, 0);
        AsyncContext context = EasyMock.createMock(AsyncContext.class);
        EasyMock.makeThreadSafe(context, true);
        final Map<String, Object> attributes = new HashMap<>();
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {

            @Override
            public Object getAttribute(String name) {
                return attributes.get(name);
            }

            @Override
            public void setAttribute(String name, Object o) {
                attributes.put(name, o);
            }
        };
        EasyMock.makeThreadSafe(request, true);
        EasyMock.expect(request.getMethod()).andReturn("GET");
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        EasyMock.makeThreadSafe(response, true);
        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();
        response.flushBuffer();
        EasyMock.expectLastCall().anyTimes();
        final CountDownLatch latchDispatch = new CountDownLatch(1);
        context.dispatch();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchDispatch.countDown();
                return null;
            }
        });
        EasyMock.replay(request, response, context);
        servlet.start();
        servlet.doGet(requestWrapper, response);
        latchDispatch.await();
        EasyMock.verify(request, response, context);
        EasyMock.reset(request, response, context);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

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

            @Override
            public void setWriteListener(WriteListener writeListener) {
            }
        }).anyTimes();
        response.flushBuffer();
        EasyMock.expectLastCall().anyTimes();
        final CountDownLatch latchComplete = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchComplete.countDown();
                return null;
            }
        });
        EasyMock.replay(request, response, context);
        servlet.doGet(requestWrapper, response);
        EasyMock.verify(request, response, context);
        org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader().read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));
        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) ServletOutputStream(javax.servlet.ServletOutputStream) MetadataXpp3Reader(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader) AsyncContext(javax.servlet.AsyncContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) MavenResolver(io.fabric8.maven.MavenResolver) WriteListener(javax.servlet.WriteListener) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File)

Aggregations

IOException (java.io.IOException)17 HashMap (java.util.HashMap)9 File (java.io.File)8 Test (org.junit.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MalformedURLException (java.net.MalformedURLException)5 Map (java.util.Map)5 FabricService (io.fabric8.api.FabricService)4 RuntimeProperties (io.fabric8.api.RuntimeProperties)4 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)4 MavenResolver (io.fabric8.maven.MavenResolver)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Date (java.util.Date)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Container (io.fabric8.api.Container)3 NameValidator (io.fabric8.api.NameValidator)3 FileInputStream (java.io.FileInputStream)3