Search in sources :

Example 51 with Path

use of io.fabric8.annotations.Path in project fabric8 by jboss-fuse.

the class MappingConfigurationTest method addService.

protected void addService(String path, String service, String version) {
    Map<String, String> params = new HashMap<String, String>();
    params.put("version", version);
    String container = path.contains("HelloWorld") ? "soapy" : "resty";
    params.put("container", container);
    ServiceDTO serviceDetails = new ServiceDTO();
    serviceDetails.setContainer(container);
    serviceDetails.setVersion(version);
    config.updateMappingRules(false, path, Arrays.asList(service), params, serviceDetails);
}
Also used : HashMap(java.util.HashMap) ServiceDTO(io.fabric8.gateway.ServiceDTO)

Example 52 with Path

use of io.fabric8.annotations.Path in project fabric8 by jboss-fuse.

the class Utils method unpack.

/**
 * Unpacks a ZIP file to targetDirectory
 * @param zipFile
 * @param targetDirectory
 * @param skipInitialDirectories how many levels of a path to skip when unpacking (like skipping base directory inside ZIP)
 * @throws IOException
 */
public static void unpack(File zipFile, File targetDirectory, int skipInitialDirectories) throws IOException {
    ZipFile zf = new ZipFile(zipFile);
    try {
        for (Enumeration<ZipArchiveEntry> e = zf.getEntries(); e.hasMoreElements(); ) {
            ZipArchiveEntry entry = e.nextElement();
            String name = entry.getName();
            int skip = skipInitialDirectories;
            while (skip-- > 0) {
                name = name.substring(name.indexOf('/') + 1);
            }
            if (entry.isDirectory()) {
                new File(targetDirectory, name).mkdirs();
            } else /*if (!entry.isUnixSymlink())*/
            {
                File file = new File(targetDirectory, name);
                file.getParentFile().mkdirs();
                FileOutputStream output = new EOLFixingFileOutputStream(targetDirectory, file);
                IOUtils.copyLarge(zf.getInputStream(entry), output);
                IOUtils.closeQuietly(output);
                if (Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class) != null) {
                    Files.setPosixFilePermissions(file.toPath(), getPermissionsFromUnixMode(file, entry.getUnixMode()));
                }
            }
        }
    } finally {
        zf.close();
    }
}
Also used : ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) EOLFixingFileOutputStream(io.fabric8.patch.management.io.EOLFixingFileOutputStream) FileOutputStream(java.io.FileOutputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) EOLFixingFileOutputStream(io.fabric8.patch.management.io.EOLFixingFileOutputStream) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Example 53 with Path

use of io.fabric8.annotations.Path in project fabric8 by jboss-fuse.

the class HttpMappingRuleBase method updateMappingRules.

/**
 * Given a path being added or removed, update the services.
 *
 * @param remove        whether to remove (if true) or add (if false) this mapping
 * @param path          the path that this mapping is bound
 * @param services      the HTTP URLs of the services to map to
 * @param defaultParams the default parameters to use in the URI templates such as for version and container
 * @param serviceDetails
 */
public void updateMappingRules(boolean remove, String path, List<String> services, Map<String, String> defaultParams, ServiceDetails serviceDetails) {
    SimplePathTemplate pathTemplate = getUriTemplate();
    if (pathTemplate != null) {
        boolean versionSpecificUri = pathTemplate.getParameterNames().contains("version");
        String versionId = defaultParams.get("version");
        if (!remove && Strings.isNotBlank(versionId) && !versionSpecificUri && gatewayVersion != null) {
            // lets ignore this mapping if the version does not match
            if (!gatewayVersion.equals(versionId)) {
                remove = true;
            }
        }
        Map<String, String> params = new HashMap<String, String>();
        if (defaultParams != null) {
            params.putAll(defaultParams);
        }
        params.put("servicePath", path);
        if (!versionSpecificUri && Strings.isNotBlank(this.enabledVersion)) {
            if (!serviceDetails.getVersion().equals(this.enabledVersion)) {
                remove = true;
            }
        }
        for (String service : services) {
            populateUrlParams(params, service);
            String fullPath = pathTemplate.bindByNameNonStrict(params);
            if (remove) {
                MappedServices rule = mappingRules.get(fullPath);
                if (rule != null) {
                    List<String> serviceUrls = rule.getServiceUrls();
                    serviceUrls.remove(service);
                    if (serviceUrls.isEmpty()) {
                        mappingRules.remove(fullPath);
                    }
                }
            } else {
                MappedServices mappedServices = new MappedServices(service, serviceDetails, loadBalancer, reverseHeaders);
                MappedServices oldRule = mappingRules.put(fullPath, mappedServices);
                if (oldRule != null) {
                    mappedServices.getServiceUrls().addAll(oldRule.getServiceUrls());
                }
            }
        }
    }
    fireMappingRulesChanged();
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MappedServices(io.fabric8.gateway.handlers.http.MappedServices) SimplePathTemplate(io.fabric8.zookeeper.internal.SimplePathTemplate)

Example 54 with Path

use of io.fabric8.annotations.Path in project fabric8 by jboss-fuse.

the class HttpMappingZooKeeperTreeCache method treeCacheEvent.

protected void treeCacheEvent(PathChildrenCacheEvent event) {
    String zkPath = zooKeeperPath;
    ChildData childData = event.getData();
    if (childData == null) {
        return;
    }
    String path = childData.getPath();
    Type type = event.getType();
    byte[] data = childData.getData();
    if (data == null || data.length == 0 || path == null) {
        return;
    }
    if (path.startsWith(zkPath)) {
        path = path.substring(zkPath.length());
    }
    // TODO should we remove the version too and pick that one?
    // and include the version in the service chooser?
    boolean remove = false;
    switch(type) {
        case CHILD_ADDED:
        case CHILD_UPDATED:
            break;
        case CHILD_REMOVED:
            remove = true;
            break;
        default:
            return;
    }
    ServiceDTO dto = null;
    try {
        dto = mapper.readValue(data, ServiceDTO.class);
        expandPropertyResolvers(dto);
        List<String> services = dto.getServices();
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", paramValue(dto.getId()));
        params.put("container", paramValue(dto.getContainer()));
        params.put("version", paramValue(dto.getVersion()));
        params.put("bundleName", paramValue(dto.getBundleName()));
        params.put("bundleVersion", paramValue(dto.getBundleVersion()));
        mappingRuleConfiguration.updateMappingRules(remove, path, services, params, dto);
    } catch (IOException e) {
        LOG.warn("Failed to parse the JSON: " + new String(data) + ". Reason: " + e, e);
    } catch (URISyntaxException e) {
        LOG.warn("Failed to update URI for dto: " + dto + ", .Reason: " + e, e);
    }
}
Also used : Type(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type) ChildData(org.apache.curator.framework.recipes.cache.ChildData) ServiceDTO(io.fabric8.gateway.ServiceDTO) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException)

Example 55 with Path

use of io.fabric8.annotations.Path in project fabric8 by jboss-fuse.

the class JsonRuleBaseReader method parseJson.

/**
 * Will try to parse the {@link InputStream} which is expected to be in the following
 * JSON format:
 * <pre>
 * { "rulebase" : [
 *    { "rule": "/foo/{path}", "to": "https://foo.com/cheese/{path}"},
 *    { "rule": "/customers/{id}/address/{addressId}", "to": "http://another.com/addresses/{addressId}/customer/{id}"}
 *  ]
 * }
 * </pre>
 *
 * <strong>Note that the passed-in {@link InputStream} will be closed by this method</strong>. This
 * is a little unusual as normally the closing is the responsibility of the party that created the
 * InputStream, but in this case we decided handling this is more user friendly.
 *
 * @param in the {@link InputStream} stream to read.
 * @return {@code Map} where the key maps to the 'rule' in the JSON, and the value maps to 'to'.
 */
public static Map<String, HttpProxyRule> parseJson(InputStream in) {
    chechNotNull(in);
    HashMap<String, HttpProxyRule> map = new HashMap<String, HttpProxyRule>();
    try {
        JsonNode config = OM.readTree(in);
        JsonNode globalCookiePath = config.get("cookiePath");
        JsonNode globalDomain = config.get("cookieDomain");
        for (JsonNode entry : getRuleBase(config)) {
            String rule = entry.get("rule").asText();
            map.put(rule, new HttpProxyRule(rule).to(entry.get("to").asText()).setCookiePath(getGlobal(entry, globalCookiePath, "cookiePath")).setCookieDomain(getGlobal(entry, globalDomain, "cookieDomain")));
        }
        return map;
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        safeClose(in);
    }
}
Also used : HashMap(java.util.HashMap) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Aggregations

Test (org.junit.Test)45 File (java.io.File)41 IOException (java.io.IOException)34 ArrayList (java.util.ArrayList)18 PathTestUtil.createTmpFile (io.fabric8.maven.docker.util.PathTestUtil.createTmpFile)17 HashMap (java.util.HashMap)12 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)11 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)11 Path (java.nio.file.Path)11 FabricService (io.fabric8.api.FabricService)10 RuntimeProperties (io.fabric8.api.RuntimeProperties)9 Properties (java.util.Properties)9 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)8 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)8 InputStream (java.io.InputStream)8 Path (javax.ws.rs.Path)8 HttpProxyRule (io.fabric8.gateway.model.HttpProxyRule)7 NodeState (io.fabric8.groups.NodeState)7 URISyntaxException (java.net.URISyntaxException)7 List (java.util.List)6