Search in sources :

Example 1 with RestService

use of au.gov.asd.tac.constellation.webserver.restapi.RestService in project constellation by constellation-app.

the class GetServiceDescription method callService.

@Override
public void callService(final PluginParameters parameters, InputStream in, OutputStream out) throws IOException {
    final String serviceName = parameters.getStringValue(SERVICE_NAME_PARAMETER_ID);
    final HttpMethod httpMethod = HttpMethod.getValue(parameters.getStringValue(METHOD_NAME_PARAMETER_ID));
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode root = mapper.createObjectNode();
        final RestService rs = RestServiceRegistry.get(serviceName, httpMethod);
        root.put("name", rs.getName());
        root.put("http_method", httpMethod.name());
        root.put("description", rs.getDescription());
        root.put("mimetype", rs.getMimeType());
        final ArrayNode tags = root.putArray("tags");
        for (final String tag : rs.getTags()) {
            tags.add(tag);
        }
        final ObjectNode params = root.putObject("parameters");
        rs.createParameters().getParameters().entrySet().forEach(entry -> {
            final PluginParameter<?> pp = entry.getValue();
            final ObjectNode param = params.putObject(entry.getKey());
            param.put("name", pp.getName());
            param.put("type", pp.getType().getId());
            param.put("description", pp.getDescription());
            if (pp.getObjectValue() != null) {
                param.put("value", pp.getObjectValue().toString());
            }
        });
        mapper.writeValue(out, root);
    } catch (final IllegalArgumentException ex) {
        throw new RestServiceException(HTTP_UNPROCESSABLE_ENTITY, ex.getMessage());
    }
}
Also used : RestServiceException(au.gov.asd.tac.constellation.webserver.restapi.RestServiceException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) RestService(au.gov.asd.tac.constellation.webserver.restapi.RestService) HttpMethod(au.gov.asd.tac.constellation.webserver.restapi.RestServiceUtilities.HttpMethod) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with RestService

use of au.gov.asd.tac.constellation.webserver.restapi.RestService in project constellation by constellation-app.

the class RestServiceServlet method callService.

private void callService(final HttpMethod httpMethod, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    // Which service is being called?
    // 
    final String serviceName = request.getPathInfo().substring(1);
    // Get an instance of the service (if it exists).
    // 
    final RestService rs = RestServiceRegistry.get(serviceName, httpMethod);
    // Convert the arguments in the URL of the request to PluginParameters.
    // 
    final PluginParameters parameters = rs.createParameters();
    final Map<String, String[]> paramMap = request.getParameterMap();
    paramMap.entrySet().forEach(entry -> {
        final String parameterName = entry.getKey();
        if (parameters.hasParameter(parameterName)) {
            final PluginParameter<?> param = parameters.getParameters().get(parameterName);
            if (entry.getValue().length == 1) {
                param.setStringValue(entry.getValue()[0]);
            } else {
                throw new RestServiceException("Service parameters do not accept multiple values");
            }
        } else {
            throw new RestServiceException(String.format("Service '%s' has no parameter '%s'", serviceName, parameterName));
        }
    });
    // 
    try {
        response.setContentType(rs.getMimeType());
        response.setStatus(HttpServletResponse.SC_OK);
        rs.callService(parameters, request.getInputStream(), response.getOutputStream());
    } catch (final RestServiceException ex) {
        throw ex;
    } catch (final IOException | RuntimeException ex) {
        throw new ServletException(ex);
    }
}
Also used : RestServiceException(au.gov.asd.tac.constellation.webserver.restapi.RestServiceException) ServletException(jakarta.servlet.ServletException) PluginParameters(au.gov.asd.tac.constellation.plugins.parameters.PluginParameters) IOException(java.io.IOException) RestService(au.gov.asd.tac.constellation.webserver.restapi.RestService)

Example 3 with RestService

use of au.gov.asd.tac.constellation.webserver.restapi.RestService in project constellation by constellation-app.

the class SwaggerServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
    final String requestPath = request.getPathInfo();
    final String fileName = request.getServletPath().substring(1) + requestPath;
    try {
        final InputStream in = SwaggerServlet.class.getResourceAsStream(fileName);
        if ("swagger/constellation.json".equals(fileName)) {
            // The file constellation.json contains our swagger info.
            // Dynamically add data and services.
            final ObjectMapper mapper = new ObjectMapper();
            final ObjectNode root = (ObjectNode) mapper.readTree(in);
            // Get the hostname:port right.
            final Preferences prefs = NbPreferences.forModule(ApplicationPreferenceKeys.class);
            final int port = prefs.getInt(ApplicationPreferenceKeys.WEBSERVER_PORT, ApplicationPreferenceKeys.WEBSERVER_PORT_DEFAULT);
            final ArrayNode servers = root.putArray("servers");
            final ObjectNode server = servers.addObject();
            server.put("url", String.format("http://localhost:%d", port));
            // Add the REST services.
            final ObjectNode paths = (ObjectNode) root.get("paths");
            RestServiceRegistry.getServices().forEach(serviceKey -> {
                final ObjectNode path = paths.putObject(String.format(SERVICE_PATH, serviceKey.name));
                final ObjectNode httpMethod = path.putObject(serviceKey.httpMethod.name().toLowerCase(Locale.ENGLISH));
                final RestService rs = RestServiceRegistry.get(serviceKey);
                httpMethod.put("summary", rs.getDescription());
                if (rs.getTags().length > 0) {
                    final ArrayNode tags = httpMethod.putArray("tags");
                    for (final String tag : rs.getTags()) {
                        tags.add(tag);
                    }
                }
                // Most parameters are passed in the URL query.
                // Some parameters are passed in the body of the request.
                // Since PluginParameter doesn't have an option to specify
                // this, we'll improvise and look for "(body)" in the
                // parameter name. These will be dummy parameters,
                // unused except for their swagger description.
                final ArrayNode params = httpMethod.putArray("parameters");
                rs.createParameters().getParameters().entrySet().forEach(entry -> {
                    final PluginParameter<?> pp = entry.getValue();
                    if (pp.getName().toLowerCase(Locale.ENGLISH).contains("(body)")) {
                        final ObjectNode requestBody = httpMethod.putObject("requestBody");
                        requestBody.put(DESCRIPTION, pp.getName().replace("(body)", " - ") + pp.getDescription());
                        requestBody.put(REQUIRED, pp.isRequired());
                        final ObjectNode content = requestBody.putObject("content");
                        final ObjectNode mime = content.putObject(RestServiceUtilities.APPLICATION_JSON);
                        final ObjectNode schema = mime.putObject(SCHEMA);
                        schema.put("$ref", pp.getRequestBodyExampleJson());
                    } else {
                        final ObjectNode param = params.addObject();
                        param.put("name", pp.getId());
                        param.put("in", "query");
                        param.put(REQUIRED, pp.isRequired());
                        param.put(DESCRIPTION, pp.getDescription());
                        final ObjectNode schema = param.putObject(SCHEMA);
                        schema.put("type", pp.getType().getId());
                    }
                });
                // Add the required CONSTELLATION secret header parameter.
                final ObjectNode secretParam = params.addObject();
                secretParam.put("name", "X-CONSTELLATION-SECRET");
                secretParam.put("in", "header");
                secretParam.put(REQUIRED, true);
                secretParam.put(DESCRIPTION, "CONSTELLATION secret");
                final ObjectNode secretSchema = secretParam.putObject(SCHEMA);
                secretSchema.put("type", "string");
                final ObjectNode responses = httpMethod.putObject("responses");
                final ObjectNode success = responses.putObject("200");
                success.put(DESCRIPTION, rs.getDescription());
                if (rs.getMimeType().equals(RestServiceUtilities.APPLICATION_JSON)) {
                    final ObjectNode content = success.putObject("content");
                    final ObjectNode mime = content.putObject(rs.getMimeType());
                    final ObjectNode schema = mime.putObject(SCHEMA);
                    // Make a wild guess about the response.
                    if (serviceKey.name.toLowerCase(Locale.ENGLISH).startsWith("list")) {
                        schema.put("type", "array");
                        final ObjectNode items = schema.putObject("items");
                        items.put("type", OBJECT);
                    } else {
                        schema.put("type", OBJECT);
                    }
                } else {
                // Do nothing
                }
            });
            final OutputStream out = response.getOutputStream();
            mapper.writeValue(out, root);
        } else {
            if (fileName.endsWith(FileExtensionConstants.JAVASCRIPT)) {
                response.setContentType("text/javascript");
            }
            // This is every other file, just transfer the bytes.
            try (final OutputStream out = response.getOutputStream()) {
                final byte[] buf = new byte[8192];
                while (true) {
                    final int len = in.read(buf);
                    if (len == -1) {
                        break;
                    }
                    out.write(buf, 0, len);
                }
            }
        }
    } catch (final IOException ex) {
        throw new ServletException(ex);
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Preferences(java.util.prefs.Preferences) NbPreferences(org.openide.util.NbPreferences) RestService(au.gov.asd.tac.constellation.webserver.restapi.RestService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with RestService

use of au.gov.asd.tac.constellation.webserver.restapi.RestService in project constellation by constellation-app.

the class FileListener method parseAndExecute.

/**
 * Execute a REST endpoint.
 *
 * @param node A JSON node representing the input parameters.
 *
 * @throws Exception because of AutoCloseable
 */
private void parseAndExecute(final String verb, final String endpoint, final String path, final JsonNode args) throws Exception {
    if ("/v2/service".equals(endpoint)) {
        final HttpMethod httpMethod = HttpMethod.getValue(verb);
        // Get an instance of the service (if it exists).
        // 
        final RestService rs = RestServiceRegistry.get(path, httpMethod);
        // Convert the arguments to PluginParameters.
        // 
        final PluginParameters parameters = rs.createParameters();
        RestServiceUtilities.parametersFromJson((ObjectNode) args, parameters);
        try (final InStream ins = new InStream(restPath, CONTENT_IN, true);
            final OutputStream out = outStream(restPath, CONTENT_OUT)) {
            rs.callService(parameters, ins.in, out);
        } catch (final IOException | RuntimeException ex) {
            throw new RestServiceException(ex);
        }
    } else {
        unrec(ENDPOINT, endpoint);
    }
}
Also used : RestServiceException(au.gov.asd.tac.constellation.webserver.restapi.RestServiceException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) PluginParameters(au.gov.asd.tac.constellation.plugins.parameters.PluginParameters) IOException(java.io.IOException) RestService(au.gov.asd.tac.constellation.webserver.restapi.RestService) HttpMethod(au.gov.asd.tac.constellation.webserver.restapi.RestServiceUtilities.HttpMethod)

Aggregations

RestService (au.gov.asd.tac.constellation.webserver.restapi.RestService)4 RestServiceException (au.gov.asd.tac.constellation.webserver.restapi.RestServiceException)3 IOException (java.io.IOException)3 PluginParameters (au.gov.asd.tac.constellation.plugins.parameters.PluginParameters)2 HttpMethod (au.gov.asd.tac.constellation.webserver.restapi.RestServiceUtilities.HttpMethod)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 ServletException (jakarta.servlet.ServletException)2 OutputStream (java.io.OutputStream)2 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 Preferences (java.util.prefs.Preferences)1 NbPreferences (org.openide.util.NbPreferences)1