Search in sources :

Example 11 with ConfigurationProviderException

use of org.apache.nifi.minifi.c2.api.ConfigurationProviderException in project nifi-minifi by apache.

the class DelegatingConfigurationProviderTest method testGetConfigurationExistsWithNoVersion.

@Test
public void testGetConfigurationExistsWithNoVersion() throws ConfigurationProviderException {
    parameters.remove("version");
    endpointPath = "/c2/config?class=raspi3&net=edge";
    initMocks();
    ConfigurationCacheFileInfo configurationCacheFileInfo = mock(ConfigurationCacheFileInfo.class);
    WriteableConfiguration configuration = mock(WriteableConfiguration.class);
    when(httpURLConnection.getHeaderField("X-Content-Version")).thenReturn("2");
    when(configurationCache.getCacheFileInfo(contentType, parameters)).thenReturn(configurationCacheFileInfo);
    when(configurationCacheFileInfo.getConfiguration(version)).thenReturn(configuration);
    when(configuration.exists()).thenReturn(true);
    assertEquals(configuration, delegatingConfigurationProvider.getConfiguration(contentType, null, parameters));
}
Also used : WriteableConfiguration(org.apache.nifi.minifi.c2.api.cache.WriteableConfiguration) ConfigurationCacheFileInfo(org.apache.nifi.minifi.c2.api.cache.ConfigurationCacheFileInfo) Test(org.junit.Test)

Example 12 with ConfigurationProviderException

use of org.apache.nifi.minifi.c2.api.ConfigurationProviderException in project nifi-minifi by apache.

the class NiFiRestConfigurationProvider method getIdAndVersionStream.

private Pair<Stream<Pair<String, Integer>>, Closeable> getIdAndVersionStream(String filenamePattern) throws ConfigurationProviderException, IOException {
    Pattern filename = Pattern.compile(filenamePattern);
    Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream();
    return new Pair<>(streamCloseablePair.getFirst().map(p -> {
        Matcher matcher = filename.matcher(p.getSecond());
        if (!matcher.matches()) {
            return null;
        }
        return new Pair<>(p.getFirst(), Integer.parseInt(matcher.group(1)));
    }).filter(Objects::nonNull), streamCloseablePair.getSecond());
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Closeable(java.io.Closeable) Stream(java.util.stream.Stream) InputStream(java.io.InputStream) Pair(org.apache.nifi.minifi.c2.api.util.Pair)

Example 13 with ConfigurationProviderException

use of org.apache.nifi.minifi.c2.api.ConfigurationProviderException in project nifi-minifi by apache.

the class NiFiRestConfigurationProvider method getConfiguration.

@Override
public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters) throws ConfigurationProviderException {
    if (!CONTENT_TYPE.equals(contentType)) {
        throw new ConfigurationProviderException("Unsupported content type: " + contentType + " supported value is " + CONTENT_TYPE);
    }
    String filename = templateNamePattern;
    for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
        if (entry.getValue().size() != 1) {
            throw new InvalidParameterException("Multiple values for same parameter not supported in this provider.");
        }
        filename = filename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0));
    }
    int index = filename.indexOf("${");
    while (index != -1) {
        int endIndex = filename.indexOf("}", index);
        if (endIndex == -1) {
            break;
        }
        String variable = filename.substring(index + 2, endIndex);
        if (!"version".equals(variable)) {
            throw new InvalidParameterException("Found unsubstituted parameter " + variable);
        }
        index = endIndex + 1;
    }
    String id = null;
    if (version == null) {
        String filenamePattern = Arrays.stream(filename.split(Pattern.quote("${version}"), -1)).map(Pattern::quote).collect(Collectors.joining("([0-9+])"));
        Pair<String, Integer> maxIdAndVersion = getMaxIdAndVersion(filenamePattern);
        id = maxIdAndVersion.getFirst();
        version = maxIdAndVersion.getSecond();
    }
    filename = filename.replaceAll(Pattern.quote("${version}"), Integer.toString(version));
    WriteableConfiguration configuration = configurationCache.getCacheFileInfo(contentType, parameters).getConfiguration(version);
    if (configuration.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Configuration " + configuration + " exists and can be served from configurationCache.");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Configuration " + configuration + " doesn't exist, will need to download and convert template.");
        }
        if (id == null) {
            try {
                String tmpFilename = templateNamePattern;
                for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
                    if (entry.getValue().size() != 1) {
                        throw new InvalidParameterException("Multiple values for same parameter not supported in this provider.");
                    }
                    tmpFilename = tmpFilename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0));
                }
                Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream();
                try {
                    String finalFilename = filename;
                    id = streamCloseablePair.getFirst().filter(p -> finalFilename.equals(p.getSecond())).map(Pair::getFirst).findFirst().orElseThrow(() -> new InvalidParameterException("Unable to find template named " + finalFilename));
                } finally {
                    streamCloseablePair.getSecond().close();
                }
            } catch (IOException | TemplatesIteratorException e) {
                throw new ConfigurationProviderException("Unable to retrieve template list", e);
            }
        }
        HttpURLConnection urlConnection = httpConnector.get("/templates/" + id + "/download");
        try (InputStream inputStream = urlConnection.getInputStream()) {
            ConfigSchema configSchema = ConfigMain.transformTemplateToSchema(inputStream);
            SchemaSaver.saveConfigSchema(configSchema, configuration.getOutputStream());
        } catch (IOException e) {
            throw new ConfigurationProviderException("Unable to download template from url " + urlConnection.getURL(), e);
        } catch (JAXBException e) {
            throw new ConfigurationProviderException("Unable to convert template to yaml", e);
        } finally {
            urlConnection.disconnect();
        }
    }
    return configuration;
}
Also used : InputStream(java.io.InputStream) Closeable(java.io.Closeable) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) InvalidParameterException(org.apache.nifi.minifi.c2.api.InvalidParameterException) HttpURLConnection(java.net.HttpURLConnection) WriteableConfiguration(org.apache.nifi.minifi.c2.api.cache.WriteableConfiguration) List(java.util.List) Stream(java.util.stream.Stream) InputStream(java.io.InputStream) Map(java.util.Map) ConfigSchema(org.apache.nifi.minifi.commons.schema.ConfigSchema)

Example 14 with ConfigurationProviderException

use of org.apache.nifi.minifi.c2.api.ConfigurationProviderException in project nifi-minifi by apache.

the class TemplatesIteratorTest method setup.

@Before
public void setup() throws ConfigurationProviderException {
    jsonFactory = new JsonFactory();
    httpURLConnection = mock(HttpURLConnection.class);
    httpConnector = mock(HttpConnector.class);
    when(httpConnector.get(TemplatesIterator.FLOW_TEMPLATES)).thenReturn(httpURLConnection);
}
Also used : HttpConnector(org.apache.nifi.minifi.c2.provider.util.HttpConnector) HttpURLConnection(java.net.HttpURLConnection) JsonFactory(com.fasterxml.jackson.core.JsonFactory) Before(org.junit.Before)

Example 15 with ConfigurationProviderException

use of org.apache.nifi.minifi.c2.api.ConfigurationProviderException in project nifi-minifi by apache.

the class ConfigService method getConfig.

@GET
public Response getConfig(@Context HttpServletRequest request, @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo) {
    try {
        authorizer.authorize(SecurityContextHolder.getContext().getAuthentication(), uriInfo);
    } catch (AuthorizationException e) {
        logger.warn(HttpRequestUtil.getClientString(request) + " not authorized to access " + uriInfo, e);
        return Response.status(403).build();
    }
    Map<String, List<String>> parameters = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    List<MediaType> acceptValues = httpHeaders.getAcceptableMediaTypes();
    boolean defaultAccept = false;
    if (acceptValues.size() == 0) {
        acceptValues = Arrays.asList(MediaType.WILDCARD_TYPE);
        defaultAccept = true;
    }
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Handling request from ").append(HttpRequestUtil.getClientString(request)).append(" with parameters ").append(parameters).append(" and Accept");
        if (defaultAccept) {
            builder = builder.append(" default value");
        }
        builder = builder.append(": ").append(acceptValues.stream().map(Object::toString).collect(Collectors.joining(", ")));
        logger.debug(builder.toString());
    }
    try {
        ConfigurationProviderValue configurationProviderValue = configurationCache.get(new ConfigurationProviderKey(acceptValues, parameters));
        Configuration configuration = configurationProviderValue.getConfiguration();
        Response.ResponseBuilder ok = Response.ok();
        ok = ok.header("X-Content-Version", configuration.getVersion());
        ok = ok.type(configurationProviderValue.getMediaType());
        byte[] buffer = new byte[1024];
        int read;
        try (InputStream inputStream = configuration.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            while ((read = inputStream.read(buffer)) >= 0) {
                outputStream.write(buffer, 0, read);
                md5.update(buffer, 0, read);
                sha256.update(buffer, 0, read);
            }
            ok = ok.header("Content-MD5", bytesToHex(md5.digest()));
            ok = ok.header("X-Content-SHA-256", bytesToHex(sha256.digest()));
            ok = ok.entity(outputStream.toByteArray());
        } catch (ConfigurationProviderException | IOException | NoSuchAlgorithmException e) {
            logger.error("Error reading or checksumming configuration file", e);
            throw new WebApplicationException(500);
        }
        return ok.build();
    } catch (AuthorizationException e) {
        logger.warn(HttpRequestUtil.getClientString(request) + " not authorized to access " + uriInfo, e);
        return Response.status(403).build();
    } catch (InvalidParameterException e) {
        logger.info(HttpRequestUtil.getClientString(request) + " made invalid request with " + HttpRequestUtil.getQueryString(request), e);
        return Response.status(400).entity("Invalid request.").build();
    } catch (ConfigurationProviderException e) {
        logger.warn("Unable to get configuration.", e);
        return Response.status(500).build();
    } catch (ExecutionException | UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof WebApplicationException) {
            throw (WebApplicationException) cause;
        }
        logger.error(HttpRequestUtil.getClientString(request) + " made request with " + HttpRequestUtil.getQueryString(request) + " that caused error.", cause);
        return Response.status(500).entity("Internal error").build();
    }
}
Also used : Configuration(org.apache.nifi.minifi.c2.api.Configuration) WebApplicationException(javax.ws.rs.WebApplicationException) AuthorizationException(org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException) HashMap(java.util.HashMap) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) InvalidParameterException(org.apache.nifi.minifi.c2.api.InvalidParameterException) MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) MessageDigest(java.security.MessageDigest) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) HashMap(java.util.HashMap) Map(java.util.Map) GET(javax.ws.rs.GET)

Aggregations

WriteableConfiguration (org.apache.nifi.minifi.c2.api.cache.WriteableConfiguration)11 ConfigurationCacheFileInfo (org.apache.nifi.minifi.c2.api.cache.ConfigurationCacheFileInfo)10 ConfigurationProviderException (org.apache.nifi.minifi.c2.api.ConfigurationProviderException)9 List (java.util.List)8 Test (org.junit.Test)8 IOException (java.io.IOException)7 InputStream (java.io.InputStream)5 HttpURLConnection (java.net.HttpURLConnection)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 HashMap (java.util.HashMap)4 InvalidParameterException (org.apache.nifi.minifi.c2.api.InvalidParameterException)4 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 MediaType (javax.ws.rs.core.MediaType)3 ConfigurationProvider (org.apache.nifi.minifi.c2.api.ConfigurationProvider)3 AuthorizationException (org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException)3 FileSystemConfigurationCache (org.apache.nifi.minifi.c2.cache.filesystem.FileSystemConfigurationCache)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Closeable (java.io.Closeable)2 OutputStream (java.io.OutputStream)2