Search in sources :

Example 91 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.

the class MetricsEndpoint method getMetricsData.

/**
     * Retrieve data for the specified metric over the given time range. The URL to access this
     * method is of the form http://<host>:<port>/<metricName>.<outputFormat> So the desired metric
     * filename is specified in the URL, e.g., catalogQueryCount.png, where the filename extension
     * defines the desired output format returned for the metric's data. Currently supported formats
     * are png, csv, xls, ppt, xml, and json.
     * <p>
     * Note that the time range can be specified as either a start and end date (in RFC3339 format,
     * i.e., YYYY-MM-DD'T'hh:mm:ssZ), or as an offset in seconds from the current time. These 2 time
     * range mechanisms cannot be combined, e.g., you cannot specify an end date and an offset to be
     * applied from that end date.
     * <p>
     * By default, the metric's name will be used for the y-axis label on the PNG graph, and the
     * metric name and time range will be used for the graph's title. Both of these can be
     * optionally specified with the yAxisLabel and title parameters. These 2 parameters do not
     * apply for the other formats.
     *
     * @param metricName   Name of the metric being graphed, e.g., queryCount
     * @param outputFormat output format of the metric, e.g. csv
     * @param startDate    Specifies the start of the time range of the search on the metric's data (RFC-3339
     *                     - Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Cannot be used with dateOffset
     *                     parameter.
     * @param endDate      Specifies the end of the time range of the search on the metric's data (RFC-3339 -
     *                     Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Cannot be used with dateOffset
     *                     parameter.
     * @param dateOffset   Specifies an offset, backwards from the current time, to search on the modified
     *                     time field for entries. Defined in seconds. Cannot be used with startDate and
     *                     endDate parameters.
     * @param yAxisLabel   (optional) the label to apply to the graph's y-axis
     * @param title        (optional) the title to be applied to the graph
     * @param uriInfo
     * @return Response containing the metric's data in the specified outputFormat
     * @throws MetricsEndpointException
     */
@GET
@Path("/{metricName}.{outputFormat}")
public Response getMetricsData(@PathParam("metricName") String metricName, @PathParam("outputFormat") String outputFormat, @QueryParam("startDate") String startDate, @QueryParam("endDate") String endDate, @QueryParam("dateOffset") String dateOffset, @QueryParam("yAxisLabel") String yAxisLabel, @QueryParam("title") String title, @Context UriInfo uriInfo) throws MetricsEndpointException {
    LOGGER.trace("ENTERING: getMetricsData  -  metricName = {},    outputFormat = {}", metricName, outputFormat);
    LOGGER.trace("request url: {}", uriInfo.getRequestUri());
    LOGGER.trace("startDate = {},     endDate = {}", startDate, endDate);
    LOGGER.trace("dateOffset = {}", dateOffset);
    Response response = null;
    // Client must specify *either* startDate and/or endDate *OR* dateOffset
    if (!StringUtils.isBlank(dateOffset) && (!StringUtils.isBlank(startDate) || !StringUtils.isBlank(endDate))) {
        throw new MetricsEndpointException("Cannot specify dateOffset and startDate or endDate, must specify either dateOffset only or startDate and/or endDate", Response.Status.BAD_REQUEST);
    }
    long endTime;
    if (!StringUtils.isBlank(endDate)) {
        endTime = parseDate(endDate);
        LOGGER.trace("Parsed endTime = {}", endTime);
    } else {
        // Default end time for metrics graphing to now (in seconds)
        Calendar now = getCalendar();
        endTime = now.getTimeInMillis() / MILLISECONDS_PER_SECOND;
        LOGGER.trace("Defaulted endTime to {}", endTime);
        // Set endDate to new calculated endTime (so that endDate is displayed properly
        // in graph's title)
        endDate = dateFormatter.format(now.getTime());
    }
    long startTime;
    if (!StringUtils.isBlank(startDate)) {
        startTime = parseDate(startDate);
        LOGGER.trace("Parsed startTime = {}", startTime);
    } else if (!StringUtils.isBlank(dateOffset)) {
        startTime = endTime - Long.parseLong(dateOffset);
        LOGGER.trace("Offset-computed startTime = {}", startTime);
        // Set startDate to new calculated startTime (so that startDate is displayed properly
        // in graph's title)
        Calendar cal = getCalendar();
        cal.setTimeInMillis(startTime * MILLISECONDS_PER_SECOND);
        startDate = dateFormatter.format(cal.getTime());
    } else {
        // Default start time for metrics graphing to end time last 24 hours (in seconds)
        startTime = endTime - ONE_DAY_IN_SECONDS;
        LOGGER.trace("Defaulted startTime to {}", startTime);
        // Set startDate to new calculated startTime (so that startDate is displayed properly
        // in graph's title)
        Calendar cal = getCalendar();
        cal.setTimeInMillis(startTime * MILLISECONDS_PER_SECOND);
        startDate = dateFormatter.format(cal.getTime());
    }
    LOGGER.trace("startDate = {},   endDate = {}", startDate, endDate);
    if (StringUtils.isBlank(yAxisLabel)) {
        yAxisLabel = RrdMetricsRetriever.convertCamelCase(metricName);
    }
    if (StringUtils.isBlank(title)) {
        title = RrdMetricsRetriever.convertCamelCase(metricName) + " for " + startDate + " to " + endDate;
    }
    // Convert metric filename to rrd filename (because RRD file required by MetricRetriever to
    // generate graph)
    String rrdFilename = metricsDir + metricName + RRD_FILE_EXTENSION;
    if (outputFormat.equalsIgnoreCase(PNG_FORMAT)) {
        LOGGER.trace("Retrieving PNG-formatted data for metric {}", metricName);
        try {
            byte[] metricsGraphBytes = metricsRetriever.createGraph(metricName, rrdFilename, startTime, endTime, yAxisLabel, title);
            ByteArrayInputStream bis = new ByteArrayInputStream(metricsGraphBytes);
            response = Response.ok(bis, PNG_MIME_TYPE).build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create graph for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create metrics graph for specified metric.", Response.Status.BAD_REQUEST);
        }
    } else if (outputFormat.equalsIgnoreCase("csv")) {
        try {
            String csv = metricsRetriever.createCsvData(rrdFilename, startTime, endTime);
            ResponseBuilder responseBuilder = Response.ok(csv);
            responseBuilder.type("text/csv");
            response = responseBuilder.build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create CSV data for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create CSV data for specified metric.", Response.Status.BAD_REQUEST);
        }
    } else if (outputFormat.equalsIgnoreCase("xls")) {
        LOGGER.trace("Retrieving XLS-formatted data for metric {}", metricName);
        try {
            OutputStream os = metricsRetriever.createXlsData(metricName, rrdFilename, startTime, endTime);
            InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
            ResponseBuilder responseBuilder = Response.ok(is);
            responseBuilder.type("application/vnd.ms-excel");
            response = responseBuilder.build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create XLS data for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create XLS data for specified metric.", Response.Status.BAD_REQUEST);
        }
    } else if (outputFormat.equalsIgnoreCase("ppt")) {
        LOGGER.trace("Retrieving PPT-formatted data for metric {}", metricName);
        try {
            OutputStream os = metricsRetriever.createPptData(metricName, rrdFilename, startTime, endTime);
            InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
            ResponseBuilder responseBuilder = Response.ok(is);
            responseBuilder.type("application/vnd.ms-powerpoint");
            response = responseBuilder.build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create PPT data for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create PPT data for metric for specified metric.", Response.Status.BAD_REQUEST);
        }
    } else if (outputFormat.equalsIgnoreCase("xml")) {
        LOGGER.trace("Retrieving XML-formatted data for metric {}", metricName);
        try {
            String xmlData = metricsRetriever.createXmlData(metricName, rrdFilename, startTime, endTime);
            ResponseBuilder responseBuilder = Response.ok(xmlData);
            responseBuilder.type("text/xml");
            response = responseBuilder.build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create XML data for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create XML data for specified metric.", Response.Status.BAD_REQUEST);
        }
    } else if (outputFormat.equalsIgnoreCase("json")) {
        LOGGER.trace("Retrieving JSON-formatted data for metric {}", metricName);
        try {
            String jsonData = metricsRetriever.createJsonData(metricName, rrdFilename, startTime, endTime);
            ResponseBuilder responseBuilder = Response.ok(jsonData);
            responseBuilder.type("application/json");
            response = responseBuilder.build();
        } catch (IOException | MetricsGraphException e) {
            LOGGER.info("Could not create JSON data for metric {}", metricName);
            throw new MetricsEndpointException("Cannot create JSON data for specified metric.", Response.Status.BAD_REQUEST);
        }
    }
    LOGGER.trace("EXITING: getMetricsData");
    return response;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MetricsEndpointException(ddf.metrics.reporting.internal.MetricsEndpointException) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) MetricsGraphException(ddf.metrics.reporting.internal.MetricsGraphException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 92 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.

the class MetricsEndpoint method getMetricsReport.

/**
     * Retrieve data for the all metrics over the given time range. The URL to access this method is
     * of the form http://<host>:<port>/report.<outputFormat> The filename extension defines the
     * desired output format returned for the report's data. Currently supported formats are xls and
     * ppt.
     * <p>
     * The XLS-formatted report will be one spreadsheet (workbook) with a worksheet per metric. The
     * PPT-formatted report will be one PowerPoint slide deck with a slide per metric. Each slide
     * will contain the metric's PNG graph.
     * <p>
     * If a summary interval is requested, the XSL report will instead contain a single table, with
     * the summarized values for each interval and metric. Cannot be used with PPT format.
     * <p>
     * Note that the time range can be specified as either a start and end date (in RFC3339 format,
     * i.e., YYYY-MM-DD'T'hh:mm:ssZ), or as an offset in seconds from the current time. These 2 time
     * range mechanisms cannot be combined, e.g., you cannot specify an end date and an offset to be
     * applied from that end date.
     * <p>
     * By default, the metric's name will be used for the y-axis label, and the metric name and time
     * range will be used for the graph's title for the report in PPT format.
     *
     * @param startDate       Specifies the start of the time range of the search on the metric's data (RFC-3339
     *                        - Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Cannot be used with dateOffset
     *                        parameter.
     * @param endDate         Specifies the end of the time range of the search on the metric's data (RFC-3339 -
     *                        Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Cannot be used with dateOffset
     *                        parameter.
     * @param dateOffset      Specifies an offset, backwards from the current time, to search on the modified
     *                        time field for entries. Defined in seconds. Cannot be used with startDate or
     *                        endDate parameters.
     * @param summaryInterval One of {@link ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.SUMMARY_INTERVALS}
     * @param uriInfo
     * @return Response containing the report as a stream in either XLS or PPT format
     * @throws MetricsEndpointException
     */
@GET
@Path("/report.{outputFormat}")
public Response getMetricsReport(@PathParam("outputFormat") String outputFormat, @QueryParam("startDate") String startDate, @QueryParam("endDate") String endDate, @QueryParam("dateOffset") String dateOffset, @QueryParam("summaryInterval") String summaryInterval, @Context UriInfo uriInfo) throws MetricsEndpointException {
    LOGGER.debug("ENTERING: getMetricsReport  -  outputFormat = {}", outputFormat);
    LOGGER.debug("request url: {}", uriInfo.getRequestUri());
    LOGGER.debug("startDate = {},     endDate = {}", startDate, endDate);
    LOGGER.debug("dateOffset = {}", dateOffset);
    Response response = null;
    // Client must specify *either* startDate and/or endDate *OR* dateOffset
    if (!StringUtils.isBlank(dateOffset) && (!StringUtils.isBlank(startDate) || !StringUtils.isBlank(endDate))) {
        throw new MetricsEndpointException("Cannot specify dateOffset and startDate or endDate, must specify either dateOffset only or startDate and/or endDate", Response.Status.BAD_REQUEST);
    }
    long endTime;
    if (!StringUtils.isBlank(endDate)) {
        endTime = parseDate(endDate);
        LOGGER.debug("Parsed endTime = {}", endTime);
    } else {
        // Default end time for metrics graphing to now (in seconds)
        Calendar now = getCalendar();
        endTime = now.getTimeInMillis() / MILLISECONDS_PER_SECOND;
        LOGGER.debug("Defaulted endTime to {}", endTime);
        // Set endDate to new calculated endTime (so that endDate is displayed properly
        // in graph's title)
        endDate = dateFormatter.format(now.getTime());
    }
    long startTime;
    if (!StringUtils.isBlank(startDate)) {
        startTime = parseDate(startDate);
        LOGGER.debug("Parsed startTime = {}", startTime);
    } else if (!StringUtils.isBlank(dateOffset)) {
        startTime = endTime - Long.parseLong(dateOffset);
        LOGGER.debug("Offset-computed startTime = {}", startTime);
        // Set startDate to new calculated startTime (so that startDate is displayed properly
        // in graph's title)
        Calendar cal = getCalendar();
        cal.setTimeInMillis(startTime * MILLISECONDS_PER_SECOND);
        startDate = dateFormatter.format(cal.getTime());
    } else {
        // Default start time for metrics graphing to end time last 24 hours (in seconds)
        startTime = endTime - ONE_DAY_IN_SECONDS;
        LOGGER.debug("Defaulted startTime to {}", startTime);
        // Set startDate to new calculated startTime (so that startDate is displayed properly
        // in graph's title)
        Calendar cal = getCalendar();
        cal.setTimeInMillis(startTime * MILLISECONDS_PER_SECOND);
        startDate = dateFormatter.format(cal.getTime());
    }
    LOGGER.debug("startDate = {},   endDate = {}", startDate, endDate);
    List<String> metricNames = getMetricsNames();
    // Generated name for metrics file (<DDF Sitename>_<Startdate>_<EndDate>.outputFormat)
    String dispositionString = "attachment; filename=" + SystemInfo.getSiteName() + "_" + startDate.substring(0, 10) + "_" + endDate.substring(0, 10) + "." + outputFormat;
    try {
        if (outputFormat.equalsIgnoreCase("xls")) {
            OutputStream os = metricsRetriever.createXlsReport(metricNames, metricsDir, startTime, endTime, summaryInterval);
            InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
            ResponseBuilder responseBuilder = Response.ok(is);
            responseBuilder.type("application/vnd.ms-excel");
            responseBuilder.header("Content-Disposition", dispositionString);
            response = responseBuilder.build();
        } else if (outputFormat.equalsIgnoreCase("ppt")) {
            if (StringUtils.isNotEmpty(summaryInterval)) {
                throw new MetricsEndpointException("Summary interval not allowed for ppt format", Response.Status.BAD_REQUEST);
            }
            OutputStream os = metricsRetriever.createPptReport(metricNames, metricsDir, startTime, endTime);
            InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
            ResponseBuilder responseBuilder = Response.ok(is);
            responseBuilder.type("application/vnd.ms-powerpoint");
            responseBuilder.header("Content-Disposition", dispositionString);
            response = responseBuilder.build();
        }
    } catch (IOException | MetricsGraphException e) {
        LOGGER.debug("Could not create {} report", outputFormat, e);
        throw new MetricsEndpointException("Could not create report in specified output format.", Response.Status.BAD_REQUEST);
    }
    LOGGER.debug("EXITING: getMetricsReport");
    return response;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MetricsEndpointException(ddf.metrics.reporting.internal.MetricsEndpointException) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) MetricsGraphException(ddf.metrics.reporting.internal.MetricsGraphException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 93 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.

the class FeatureCollectionMessageBodyReaderWfs10 method readFrom.

@Override
public WfsFeatureCollection readFrom(Class<WfsFeatureCollection> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream inStream) throws IOException, WebApplicationException {
    // Save original input stream for any exception message that might need to be
    // created
    String originalInputStream = IOUtils.toString(inStream, StandardCharsets.UTF_8.name());
    // Re-create the input stream (since it has already been read for potential
    // exception message creation)
    inStream = new ByteArrayInputStream(originalInputStream.getBytes(StandardCharsets.UTF_8.name()));
    WfsFeatureCollection featureCollection = null;
    try {
        featureCollection = (WfsFeatureCollection) xstream.fromXML(inStream);
    } catch (XStreamException e) {
        // If a ServiceExceptionReport is sent from the remote WFS site it will be sent with an
        // JAX-RS "OK" status, hence the ErrorResponse exception mapper will not fire.
        // Instead the ServiceExceptionReport will come here and be treated like a GetFeature
        // response, resulting in an XStreamException since ExceptionReport cannot be
        // unmarshalled. So this catch clause is responsible for catching that XStream
        // exception and creating a JAX-RS response containing the original stream
        // (with the ExceptionReport) and rethrowing it as a WebApplicationException,
        // which CXF will wrap as a ClientException that the WfsSource catches, converts
        // to a WfsException, and logs.
        LOGGER.debug("Exception unmarshalling", e);
        ByteArrayInputStream bis = new ByteArrayInputStream(originalInputStream.getBytes(StandardCharsets.UTF_8));
        ResponseBuilder responseBuilder = Response.ok(bis);
        responseBuilder.type("text/xml");
        Response response = responseBuilder.build();
        throw new WebApplicationException(e, response);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return featureCollection;
}
Also used : Response(javax.ws.rs.core.Response) XStreamException(com.thoughtworks.xstream.XStreamException) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) WfsFeatureCollection(org.codice.ddf.spatial.ogc.wfs.catalog.common.WfsFeatureCollection) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 94 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.

the class TestWfsResponseExceptionMapper method createWfsException.

// //////////////////////////////////////////////////////////////
private WfsException createWfsException(String serviceExceptionReportXml) {
    ByteArrayInputStream bis = new ByteArrayInputStream(serviceExceptionReportXml.getBytes());
    ResponseBuilder responseBuilder = Response.ok(bis);
    responseBuilder.type("text/xml");
    Response response = responseBuilder.build();
    return new WfsResponseExceptionMapper().fromResponse(response);
}
Also used : Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 95 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project hbase by apache.

the class RootResource method get.

@GET
@Produces({ MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF })
public Response get(@Context final UriInfo uriInfo) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("GET " + uriInfo.getAbsolutePath());
    }
    servlet.getMetrics().incrementRequests(1);
    try {
        ResponseBuilder response = Response.ok(getTableList());
        response.cacheControl(cacheControl);
        servlet.getMetrics().incrementSucessfulGetRequests(1);
        return response.build();
    } catch (Exception e) {
        servlet.getMetrics().incrementFailedGetRequests(1);
        return processException(e);
    }
}
Also used : ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) IOException(java.io.IOException) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)175 GET (javax.ws.rs.GET)84 Produces (javax.ws.rs.Produces)81 Path (javax.ws.rs.Path)69 WebApplicationException (javax.ws.rs.WebApplicationException)47 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)40 IOException (java.io.IOException)30 MediaType (javax.ws.rs.core.MediaType)29 POST (javax.ws.rs.POST)23 IRI (org.semanticweb.owlapi.model.IRI)22 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)21 Response (javax.ws.rs.core.Response)20 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)19 URI (java.net.URI)18 Consumes (javax.ws.rs.Consumes)18 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)18 ByteArrayInputStream (java.io.ByteArrayInputStream)16 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)16 HashSet (java.util.HashSet)14 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)12