Search in sources :

Example 1 with PluginCoordinates

use of io.apiman.common.plugin.PluginCoordinates in project apiman by apiman.

the class PluginResourceImpl method getPolicyForm.

/**
 * @see IPluginResource#getPolicyForm(java.lang.Long, java.lang.String)
 */
@Override
public String getPolicyForm(Long pluginId, String policyDefId) throws PluginNotFoundException, PluginResourceNotFoundException, PolicyDefinitionNotFoundException {
    // No permission check is needed
    PluginBean pbean;
    PolicyDefinitionBean pdBean;
    try {
        pbean = storage.getPlugin(pluginId);
        if (pbean == null) {
            throw ExceptionFactory.pluginNotFoundException(pluginId);
        }
        pdBean = storage.getPolicyDefinition(policyDefId);
    } catch (AbstractRestException e) {
        throw e;
    } catch (Exception e) {
        throw new SystemErrorException(e);
    }
    PluginCoordinates coordinates = new PluginCoordinates(pbean.getGroupId(), pbean.getArtifactId(), pbean.getVersion(), pbean.getClassifier(), pbean.getType());
    try {
        if (pdBean == null) {
            throw ExceptionFactory.policyDefNotFoundException(policyDefId);
        }
        if (pdBean.getPluginId() == null || !pdBean.getPluginId().equals(pbean.getId())) {
            throw ExceptionFactory.pluginNotFoundException(pluginId);
        }
        if (pdBean.getFormType() == PolicyFormType.JsonSchema && pdBean.getForm() != null) {
            String formPath = pdBean.getForm();
            if (!formPath.startsWith("/")) {
                // $NON-NLS-1$
                // $NON-NLS-1$
                formPath = "META-INF/apiman/policyDefs/" + formPath;
            } else {
                formPath = formPath.substring(1);
            }
            Plugin plugin = pluginRegistry.loadPlugin(coordinates);
            PluginClassLoader loader = plugin.getLoader();
            InputStream resource = null;
            try {
                resource = loader.getResourceAsStream(formPath);
                if (resource == null) {
                    throw ExceptionFactory.pluginResourceNotFoundException(formPath, coordinates);
                }
                StringWriter writer = new StringWriter();
                IOUtils.copy(resource, writer);
                return writer.toString();
            } finally {
                IOUtils.closeQuietly(resource);
            }
        } else {
            throw ExceptionFactory.pluginResourceNotFoundException(null, coordinates);
        }
    } catch (AbstractRestException e) {
        throw e;
    } catch (Throwable t) {
        throw new SystemErrorException(t);
    }
}
Also used : SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) PolicyDefinitionBean(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) PluginBean(io.apiman.manager.api.beans.plugins.PluginBean) NewPluginBean(io.apiman.manager.api.beans.plugins.NewPluginBean) AbstractRestException(io.apiman.manager.api.rest.exceptions.AbstractRestException) AbstractRestException(io.apiman.manager.api.rest.exceptions.AbstractRestException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) PluginNotFoundException(io.apiman.manager.api.rest.exceptions.PluginNotFoundException) PluginResourceNotFoundException(io.apiman.manager.api.rest.exceptions.PluginResourceNotFoundException) InvalidPluginException(io.apiman.manager.api.core.exceptions.InvalidPluginException) SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) IOException(java.io.IOException) PluginAlreadyExistsException(io.apiman.manager.api.rest.exceptions.PluginAlreadyExistsException) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) PolicyDefinitionNotFoundException(io.apiman.manager.api.rest.exceptions.PolicyDefinitionNotFoundException) Plugin(io.apiman.common.plugin.Plugin) PluginClassLoader(io.apiman.common.plugin.PluginClassLoader)

Example 2 with PluginCoordinates

use of io.apiman.common.plugin.PluginCoordinates in project apiman by apiman.

the class PolicyFactoryImpl method doLoadFromPlugin.

/**
 * Loads a policy from a plugin.
 * @param policyImpl
 * @param handler
 */
private void doLoadFromPlugin(final String policyImpl, final IAsyncResultHandler<IPolicy> handler) {
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(policyImpl);
    if (coordinates == null) {
        handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl)));
        return;
    }
    int ssidx = policyImpl.indexOf('/');
    if (ssidx == -1) {
        handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl)));
        return;
    }
    final String classname = policyImpl.substring(ssidx + 1);
    this.pluginRegistry.loadPlugin(coordinates, new IAsyncResultHandler<Plugin>() {

        @Override
        public void handle(IAsyncResult<Plugin> result) {
            if (result.isSuccess()) {
                IPolicy rval;
                Plugin plugin = result.getResult();
                PluginClassLoader pluginClassLoader = plugin.getLoader();
                ClassLoader oldCtxLoader = Thread.currentThread().getContextClassLoader();
                try {
                    Thread.currentThread().setContextClassLoader(pluginClassLoader);
                    Class<?> c = pluginClassLoader.loadClass(classname);
                    rval = (IPolicy) c.newInstance();
                } catch (Exception e) {
                    handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, e)));
                    return;
                } finally {
                    Thread.currentThread().setContextClassLoader(oldCtxLoader);
                }
                policyCache.put(policyImpl, rval);
                handler.handle(AsyncResultImpl.create(rval));
            } else {
                handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, result.getError())));
            }
        }
    });
}
Also used : PolicyNotFoundException(io.apiman.gateway.engine.beans.exceptions.PolicyNotFoundException) PolicyNotFoundException(io.apiman.gateway.engine.beans.exceptions.PolicyNotFoundException) PluginClassLoader(io.apiman.common.plugin.PluginClassLoader) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) Plugin(io.apiman.common.plugin.Plugin) PluginClassLoader(io.apiman.common.plugin.PluginClassLoader)

Example 3 with PluginCoordinates

use of io.apiman.common.plugin.PluginCoordinates in project apiman by apiman.

the class AbstractPluginRegistryTest method testLoadPlugin.

/**
 * Test method for {@link io.apiman.manager.api.core.plugin.AbstractPluginRegistry#loadPlugin(io.apiman.common.plugin.PluginCoordinates)}.
 * @throws Exception any exception
 */
@Test
public void testLoadPlugin() throws Exception {
    File targetDir = new File("target").getAbsoluteFile();
    File tmpDir = new File(targetDir, "_plugintmp");
    AbstractPluginRegistry registry = new TestPluginRegistry(tmpDir);
    PluginCoordinates coords = new PluginCoordinates("io.apiman.test", "apiman-test-plugin", "1.0");
    Plugin plugin = registry.loadPlugin(coords);
    Assert.assertNotNull(plugin);
    ;
    Assert.assertEquals("Test Plugin", plugin.getName());
    Assert.assertEquals("The first ever plugin for testing.", plugin.getDescription());
}
Also used : PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) File(java.io.File) Plugin(io.apiman.common.plugin.Plugin) Test(org.junit.Test)

Example 4 with PluginCoordinates

use of io.apiman.common.plugin.PluginCoordinates in project apiman by apiman.

the class PluginResourceImpl method create.

/**
 * @see IPluginResource#create(io.apiman.manager.api.beans.plugins.NewPluginBean)
 */
@Override
public PluginBean create(NewPluginBean bean) throws PluginAlreadyExistsException, PluginNotFoundException, NotAuthorizedException {
    securityContext.checkAdminPermissions();
    PluginCoordinates coordinates = new PluginCoordinates(bean.getGroupId(), bean.getArtifactId(), bean.getVersion(), bean.getClassifier(), bean.getType());
    boolean isSnapshot = PluginUtils.isSnapshot(coordinates);
    if (isSnapshot) {
        // $NON-NLS-1$
        LOGGER.debug("Loading a snapshot version of plugin: " + coordinates);
    }
    boolean isUpgrade = isSnapshot || bean.isUpgrade();
    Plugin plugin;
    try {
        plugin = pluginRegistry.loadPlugin(coordinates);
        bean.setName(plugin.getName());
        bean.setDescription(plugin.getDescription());
    } catch (InvalidPluginException e) {
        throw new PluginNotFoundException(coordinates.toString(), e);
    }
    PluginBean pluginBean = new PluginBean();
    pluginBean.setGroupId(bean.getGroupId());
    pluginBean.setArtifactId(bean.getArtifactId());
    pluginBean.setVersion(bean.getVersion());
    pluginBean.setClassifier(bean.getClassifier());
    pluginBean.setType(bean.getType());
    pluginBean.setName(bean.getName());
    pluginBean.setDescription(bean.getDescription());
    pluginBean.setCreatedBy(securityContext.getCurrentUser());
    pluginBean.setCreatedOn(new Date());
    try {
        PluginBean existingPlugin = storage.getPlugin(bean.getGroupId(), bean.getArtifactId());
        boolean hasExistingPlugin = existingPlugin != null && !existingPlugin.isDeleted();
        boolean isUpdatePolicyDefs = false;
        if (hasExistingPlugin && !isUpgrade) {
            throw ExceptionFactory.pluginAlreadyExistsException();
        } else if (hasExistingPlugin && isUpgrade) {
            isUpdatePolicyDefs = true;
            existingPlugin.setName(pluginBean.getName());
            existingPlugin.setDescription(pluginBean.getDescription());
            existingPlugin.setVersion(pluginBean.getVersion());
            existingPlugin.setClassifier(pluginBean.getClassifier());
            existingPlugin.setType(pluginBean.getType());
            pluginBean.setId(existingPlugin.getId());
            storage.updatePlugin(existingPlugin);
        } else if (!hasExistingPlugin && existingPlugin != null) {
            isUpdatePolicyDefs = true;
            existingPlugin.setName(pluginBean.getName());
            existingPlugin.setDescription(pluginBean.getDescription());
            existingPlugin.setVersion(pluginBean.getVersion());
            existingPlugin.setClassifier(pluginBean.getClassifier());
            existingPlugin.setType(pluginBean.getType());
            existingPlugin.setCreatedOn(new Date());
            existingPlugin.setCreatedBy(securityContext.getCurrentUser());
            existingPlugin.setDeleted(false);
            pluginBean.setId(existingPlugin.getId());
            storage.updatePlugin(existingPlugin);
        } else {
            if (bean.isUpgrade()) {
                throw ExceptionFactory.pluginNotFoundException(0L);
            }
            storage.createPlugin(pluginBean);
        }
        // Process any contributed policy definitions.
        List<URL> policyDefs = plugin.getPolicyDefinitions();
        int createdPolicyDefCounter = 0;
        int updatedPolicyDefCounter = 0;
        for (URL url : policyDefs) {
            PolicyDefinitionBean policyDef = (PolicyDefinitionBean) MAPPER.reader(PolicyDefinitionBean.class).readValue(url);
            if (policyDef.getId() == null || policyDef.getId().trim().isEmpty()) {
                // $NON-NLS-1$
                throw ExceptionFactory.policyDefInvalidException(Messages.i18n.format("PluginResourceImpl.MissingPolicyDefId", policyDef.getName()));
            }
            policyDef.setPluginId(pluginBean.getId());
            if (policyDef.getId() == null) {
                policyDef.setId(BeanUtils.idFromName(policyDef.getName()));
            } else {
                policyDef.setId(BeanUtils.idFromName(policyDef.getId()));
            }
            if (policyDef.getFormType() == null) {
                policyDef.setFormType(PolicyFormType.Default);
            }
            PolicyDefinitionBean existingPolicyDef = storage.getPolicyDefinition(policyDef.getId());
            if (existingPolicyDef == null) {
                storage.createPolicyDefinition(policyDef);
                createdPolicyDefCounter++;
            } else if (isUpdatePolicyDefs) {
                existingPolicyDef.setName(policyDef.getName());
                existingPolicyDef.setDescription(policyDef.getDescription());
                existingPolicyDef.setIcon(policyDef.getIcon());
                existingPolicyDef.getTemplates().clear();
                existingPolicyDef.getTemplates().addAll(policyDef.getTemplates());
                existingPolicyDef.setFormType(policyDef.getFormType());
                existingPolicyDef.setForm(policyDef.getForm());
                existingPolicyDef.setDeleted(false);
                existingPolicyDef.setPolicyImpl(policyDef.getPolicyImpl());
                storage.updatePolicyDefinition(existingPolicyDef);
                updatedPolicyDefCounter++;
            } else {
                // $NON-NLS-1$
                throw ExceptionFactory.policyDefInvalidException(Messages.i18n.format("PluginResourceImpl.DuplicatePolicyDef", policyDef.getId()));
            }
        }
        LOGGER.info(// $NON-NLS-1$
        String.format(// $NON-NLS-1$
        "Created plugin mvn:%s:%s:%s", // $NON-NLS-1$
        pluginBean.getGroupId(), // $NON-NLS-1$
        pluginBean.getArtifactId(), pluginBean.getVersion()));
        // $NON-NLS-1$
        LOGGER.info(String.format("\tCreated %s policy definitions from plugin.", String.valueOf(createdPolicyDefCounter)));
        if (isUpdatePolicyDefs) {
            // $NON-NLS-1$
            LOGGER.info(String.format("\tUpdated %s policy definitions from plugin.", String.valueOf(updatedPolicyDefCounter)));
        }
    } catch (AbstractRestException e) {
        throw e;
    } catch (Exception e) {
        throw new SystemErrorException(e);
    }
    return pluginBean;
}
Also used : SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) PluginNotFoundException(io.apiman.manager.api.rest.exceptions.PluginNotFoundException) Date(java.util.Date) URL(java.net.URL) AbstractRestException(io.apiman.manager.api.rest.exceptions.AbstractRestException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) PluginNotFoundException(io.apiman.manager.api.rest.exceptions.PluginNotFoundException) PluginResourceNotFoundException(io.apiman.manager.api.rest.exceptions.PluginResourceNotFoundException) InvalidPluginException(io.apiman.manager.api.core.exceptions.InvalidPluginException) SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) IOException(java.io.IOException) PluginAlreadyExistsException(io.apiman.manager.api.rest.exceptions.PluginAlreadyExistsException) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) PolicyDefinitionNotFoundException(io.apiman.manager.api.rest.exceptions.PolicyDefinitionNotFoundException) PolicyDefinitionBean(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) InvalidPluginException(io.apiman.manager.api.core.exceptions.InvalidPluginException) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) PluginBean(io.apiman.manager.api.beans.plugins.PluginBean) NewPluginBean(io.apiman.manager.api.beans.plugins.NewPluginBean) AbstractRestException(io.apiman.manager.api.rest.exceptions.AbstractRestException) Plugin(io.apiman.common.plugin.Plugin)

Example 5 with PluginCoordinates

use of io.apiman.common.plugin.PluginCoordinates in project apiman by apiman.

the class VertxPluginRegistryTest method getFakePluginFromCustomRegistry.

/**
 * Test with custom configuration (pluginRepositories and pluginsDir) to download a fake plugin from a fake Maven repo
 *
 * @param context
 * @throws java.io.IOException
 */
@Test
public void getFakePluginFromCustomRegistry(TestContext context) throws java.io.IOException {
    Async waitForPlugin = context.async();
    // Preparing JSON config Object
    List<String> pluginRepositories = Arrays.asList(mavenServerUri.toString());
    String pluginsDir = "/tmp/plugins-test2";
    JsonObject jsonObject = new JsonObject(getJsonConfig(pluginRepositories, pluginsDir));
    // Delete temp folder
    File TempDir = new File(pluginsDir);
    if (TempDir.exists())
        FileUtils.deleteDirectory(TempDir);
    // Referenced values to test
    Map<String, String> expected = new LinkedHashMap<String, String>() {

        {
            put("pluginRepositories", String.join(",", pluginRepositories));
            put("pluginsDir", pluginsDir);
        }
    };
    // Loading VertX configuration
    VertxEngineConfig config = new VertxEngineConfig(jsonObject);
    Map<String, String> pluginRegistryConfig = config.getPluginRegistryConfig();
    // Assert that JSON config object contains the rights parameters
    Assert.assertThat(pluginRegistryConfig, is(expected));
    // Create a fake engine for test plugins loading
    TestVerticle v = new TestVerticle(config);
    // Get pluginRegistry from engine
    IPluginRegistry pluginRegistry = v.createPluginRegistry();
    // Define simple header policy plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);
    // Download the plugin
    pluginRegistry.loadPlugin(coordinates, result -> {
        if (result.isSuccess()) {
            // Get downloaded plugin
            Plugin plugin = result.getResult();
            // Assert that's the right plugin
            context.assertEquals(plugin.getCoordinates(), coordinates);
            // Assert plugin is in the right dir
            Path pluginPath = Paths.get(pluginsDir + "/io.apiman.test/testPlugin/1.0.0.Final/testPlugin.war");
            context.assertTrue(Files.exists(pluginPath));
            waitForPlugin.complete();
        } else {
            context.fail(result.getError());
        }
    });
    waitForPlugin.awaitSuccess();
}
Also used : IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) Path(java.nio.file.Path) JsonObject(io.vertx.core.json.JsonObject) Async(io.vertx.ext.unit.Async) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) File(java.io.File) Plugin(io.apiman.common.plugin.Plugin) Test(org.junit.Test)

Aggregations

PluginCoordinates (io.apiman.common.plugin.PluginCoordinates)9 Plugin (io.apiman.common.plugin.Plugin)8 File (java.io.File)6 Test (org.junit.Test)5 IPluginRegistry (io.apiman.gateway.engine.IPluginRegistry)4 VertxEngineConfig (io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig)4 JsonObject (io.vertx.core.json.JsonObject)4 Async (io.vertx.ext.unit.Async)4 Path (java.nio.file.Path)4 PluginClassLoader (io.apiman.common.plugin.PluginClassLoader)2 NewPluginBean (io.apiman.manager.api.beans.plugins.NewPluginBean)2 PluginBean (io.apiman.manager.api.beans.plugins.PluginBean)2 PolicyDefinitionBean (io.apiman.manager.api.beans.policies.PolicyDefinitionBean)2 InvalidPluginException (io.apiman.manager.api.core.exceptions.InvalidPluginException)2 StorageException (io.apiman.manager.api.core.exceptions.StorageException)2 AbstractRestException (io.apiman.manager.api.rest.exceptions.AbstractRestException)2 NotAuthorizedException (io.apiman.manager.api.rest.exceptions.NotAuthorizedException)2 PluginAlreadyExistsException (io.apiman.manager.api.rest.exceptions.PluginAlreadyExistsException)2 PluginNotFoundException (io.apiman.manager.api.rest.exceptions.PluginNotFoundException)2 PluginResourceNotFoundException (io.apiman.manager.api.rest.exceptions.PluginResourceNotFoundException)2