Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

In this page you can find the example usage for java.net URI toASCIIString.

Prototype

public String toASCIIString() 

Source Link

Document

Returns the content of this URI as a US-ASCII string.

Usage

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns the delta resource identified by deltaId that is associated with model identified by id within the Resource
 * Manager.//from   w  w w .  java2s  .c  om
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding.
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param encode
 * @param model This versions detailed topology model in the requested format (TURTLE, etc.). To optimize transfer
 * the contents of this model element should be gzipped (contentType="application/x-gzip") and base64 encoded
 * (contentTransferEncoding="base64"). This will reduce the transfer size and encapsulate the original model contents.
 * @param id Identifier of the target topology model resource.
 * @param deltaId Identifier of the target delta resource.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a specific SENSE topology model resource.", notes = "Returns SENSE topology model resource corresponding to the specified resource id.", response = DeltaResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTA_MSG, response = DeltaResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models/{" + HttpConstants.ID_NAME + "}/deltas/{" + HttpConstants.DELTAID_NAME
        + "}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getModelDelta(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, defaultValue = HttpConstants.IF_MODIFIED_SINCE_DEFAULT) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id,
        @PathVariable(HttpConstants.DELTAID_NAME) @ApiParam(value = HttpConstants.DELTAID_MSG, required = true) String deltaId) {

    // Get the requested resource URL.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info(
            "[SenseRmController] operation = {}, id = {}, deltaId = {}, accept = {}, ifModifiedSince = {}, model = {}",
            location, id, deltaId, accept, ifModifiedSince, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        DeltaResponse response = driver.getDelta(deltaId, model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        DeltaResource d = response.getDelta().get();

        log.info("[SenseRmController] deltaId = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                d.getLastModified(), ifModifiedSince);

        long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                .getTimeInMillis();

        d.setHref(location.toASCIIString());
        if (encode) {
            d.setAddition(Encoder.encode(d.getAddition()));
            d.setReduction(Encoder.encode(d.getReduction()));
            d.setResult(Encoder.encode(d.getResult()));
        }

        headers.setLastModified(lastModified);

        log.info(
                "[SenseRmController] getDelta returning id = {}, creationTime = {}, queried If-Modified-Since = {}.",
                d.getId(), d.getLastModified(), ifModifiedSince);

        return new ResponseEntity<>(d, headers, HttpStatus.OK);
    } catch (InterruptedException | ExecutionException | IOException | DatatypeConfigurationException ex) {
        log.error("getDelta failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns the SENSE topology model identified by id.
 *
 * Operation: GET /api/sense/v1/models/{id}
 *
 * @param accept Provides media types that are acceptable for the response. At the moment
 *    'application/json' is the supported response encoding.
 *
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting
 *    all models with creationTime after the specified date. The date must be specified in
 *    RFC 1123 format./* www  .  j  a v a2 s.c  o m*/
 *
 * @param encode Transfer size of the model element contents can be optimized by gzip/base64
 *    encoding the contained model.  If encode=true then returned model will be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding= "base64")
 *    to reduce transfer size. Default value is encode=false.
 *
 * @param model This versions detailed topology model in the requested format (TURTLE, etc.).
 *    To optimize transfer the contents of this model element should be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding="base64").
 *    This will reduce the transfer size and encapsulate the original model contents.
 *
 * @param id Identifier of the target topology model resource.
 *
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a specific SENSE topology model resource.", notes = "Returns SENSE topology model resource corresponding to the specified resource id.", response = ModelResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_TOPOLOGIES_MSG, response = ModelResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models/{" + HttpConstants.ID_NAME + "}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getModel(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        /*
          @RequestHeader(
                value = HttpConstants.IF_MODIFIED_SINCE_NAME,
                defaultValue = HttpConstants.IF_MODIFIED_SINCE_DEFAULT)
          @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        */
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id) {

    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] operation = {}, id = {}, accept = {}, ifModifiedSince = {}, model = {}",
            location, id, accept, ifModifiedSince, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Return the local in HTTP header.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Retrieve the model if newer than specified If-Modified-Since header.
        ModelResponse response = driver.getModel(id, model, ifms).get();

        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        ModelResource m = response.getModel().get();

        // Get the creation time for HTTP header.
        long creationTime = XmlUtilities.xmlGregorianCalendar(m.getCreationTime()).toGregorianCalendar()
                .getTimeInMillis();
        headers.setLastModified(creationTime);

        log.info("[SenseRmController] returning id = {}, creationTime = {}, queried If-Modified-Since = {}\n{}",
                m.getId(), m.getCreationTime(), ifModifiedSince, Encoder.encode(m.getModel()));

        // Update the HREF to point to the absolute URL for the resource.
        m.setHref(location.toASCIIString());
        if (encode) {
            m.setModel(Encoder.encode(m.getModel()));
        }

        return new ResponseEntity<>(m, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | ExecutionException ex) {
        log.error("[SenseRmController] getModel failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns the delta resource identified by deltaId.
 *
 * Operation: GET /api/sense/v1/deltas/{deltaId}
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding./* w  w  w  .ja v  a2 s  .  c o  m*/
 * @param summary
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param encode
 * @param model Specifies the model encoding to use (i.e. turtle, ttl, json-ld, etc).
 * @param deltaId Identifier of the target delta resource.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a specific SENSE topology model resource.", notes = "Returns SENSE topology model resource corresponding to the specified resource id.", response = DeltaResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTA_MSG, response = DeltaResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/deltas/{" + HttpConstants.DELTAID_NAME + "}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getDelta(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @PathVariable(HttpConstants.DELTAID_NAME) @ApiParam(value = HttpConstants.DELTAID_MSG, required = true) String deltaId) {

    // Get the requested resource URL.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] operation = {}, id = {}, accept = {}, ifModifiedSince = {}, model = {}",
            location, deltaId, accept, ifModifiedSince, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // We need to return the current location of this resource in the response header.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Query for the requested delta.
        DeltaResponse response = driver.getDelta(deltaId, model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        DeltaResource d = response.getDelta().get();

        log.info("[SenseRmController] deltaId = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                d.getLastModified(), ifModifiedSince);

        // Determine when this was last modified.
        long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                .getTimeInMillis();
        headers.setLastModified(lastModified);

        // Do we need to return this delta?
        if (lastModified <= ifms) {
            log.info("[SenseRmController] returning not modified, deltaId = {}", d.getId());
            return new ResponseEntity<>(headers, HttpStatus.NOT_MODIFIED);
        }

        d.setHref(location.toASCIIString());
        if (summary) {
            // If a summary resource view was requested we do not send back any models.
            d.setAddition(null);
            d.setReduction(null);
            d.setResult(null);
        } else if (encode) {
            // Compress and base64 encode the model contents if requested.
            d.setAddition(Encoder.encode(d.getAddition()));
            d.setReduction(Encoder.encode(d.getReduction()));
            d.setResult(Encoder.encode(d.getResult()));
        }

        log.info(
                "[SenseRmController] getDelta returning id = {}, creationTime = {}, queried If-Modified-Since = {}.",
                d.getId(), d.getLastModified(), ifModifiedSince);
        return new ResponseEntity<>(d, headers, HttpStatus.OK);
    } catch (InterruptedException | ExecutionException | IOException | DatatypeConfigurationException ex) {
        log.error("[SenseRmController] getDelta failed, deltaId = {}, ex = {}", deltaId, ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();

        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a collection of delta resources.
 *
 * Operation: GET /api/sense/v1/deltas/*from w w w . ja v  a2  s . co  m*/
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding.
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param summary If summary=true then a summary collection of delta resources will be returned including the delta
meta-data while excluding the addition, reduction, and m elements. Default value is summary=true.
 * @param encode
 * @param model If model=turtle then the returned addition, reduction, and m elements will contain the full
topology model in a TURTLE representation. Default value is model=turtle.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a collection of accepted delta resources.", notes = "Returns a collection of available delta resources.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTAS_MSG, response = DeltaResource.class, responseContainer = "List", responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/deltas", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
@ResourceAnnotation(name = "deltas", version = "v1")
public ResponseEntity<?> getDeltas(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, defaultValue = HttpConstants.IF_MODIFIED_SINCE_DEFAULT) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode) {

    // We need the request URL to build fully qualified resource URLs.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] GET operation = {}, accept = {}, If-Modified-Since = {}, current = {}, "
            + "summary = {}, model = {}", location, accept, ifModifiedSince, summary, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Populate the content location header with our URL location.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Track matching deltas here.
        List<DeltaResource> deltas = new ArrayList<>();

        // Keep track of the most recently updated delta date.
        long newest = 0;

        // Query the driver for a list of deltas.
        DeltasResponse response = driver.getDeltas(model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        // The requester asked for a list of models so apply any filtering criteria.
        for (DeltaResource d : response.getDeltas()) {
            long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                    .getTimeInMillis();

            log.info("[SenseRmController] delta id = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                    d.getLastModified(), ifModifiedSince);

            // Create the unique resource URL.
            d.setHref(UrlHelper.append(location.toASCIIString(), d.getId()));

            // If summary results are requested we do not return the model.
            if (summary) {
                d.setAddition(null);
                d.setReduction(null);
                d.setResult(null);
            } else {
                // If they requested an encoded transfer we will encode the model contents.
                if (encode) {
                    d.setAddition(Encoder.encode(d.getAddition()));
                    d.setReduction(Encoder.encode(d.getReduction()));
                    d.setResult(Encoder.encode(d.getResult()));
                }
            }

            // Save this model and update If-Modified-Since with the creation time.
            deltas.add(d);

            if (lastModified > newest) {
                newest = lastModified;
            }
        }

        // Update the LastModified header with the value of the newest model.
        headers.setLastModified(newest);

        // We have success so return the models we have found.
        return new ResponseEntity<>(deltas, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | IllegalArgumentException
            | ExecutionException ex) {
        log.error("[SenseRmController] getDeltas failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of available SENSE topology models.
 *
 * Operation: GET /api/sense/v1/models/*from   ww w  .  ja v a  2s .com*/
 *
 * @param accept Provides media types that are acceptable for the response.
 *    At the moment 'application/json' is the supported response encoding.
 *
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since
 *    header requesting all models with creationTime after the specified
 *    date. The date must be specified in RFC 1123 format.
 *
 * @param current If current=true then a collection of models containing only
 *    the most recent model will be returned. Default value is current=false.
 *
 * @param encode Transfer size of the model element contents can be optimized
 *    by gzip/base64 encoding the contained model.  If encode=true the
 *    returned model will be gzipped (contentType="application/x-gzip") and
 *    base64 encoded (contentTransferEncoding= "base64") to reduce transfer
 *    size. Default value is encode=false.
 *
 * @param summary If summary=true then a summary collection of models will be
 *    returned including the model meta-data while excluding the model
 *    element. Default value is summary=true.
 *
 * @param model Specify the model schema format (TURTLE, JSON-LD, etc.).
 *
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a collection of available model resources.", notes = "Returns a list of available SENSE topology model resources.", response = ModelResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_TOPOLOGIES_MSG, response = ModelResource.class, responseContainer = "List", responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.UNAUTHORIZED_CODE, message = HttpConstants.UNAUTHORIZED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
@ResourceAnnotation(name = "models", version = "v1")
public ResponseEntity<?> getModels(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.CURRENT_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.CURRENT_MSG, required = false) boolean current,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model) {

    // We need the request URL to build fully qualified resource URLs.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] GET operation = {}, accept = {}, If-Modified-Since = {}, current = {}, "
            + "summary = {}, model = {}", location, accept, ifModifiedSince, current, summary, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Populate the content location header with our URL location.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Track matching models here.
        List<ModelResource> models = new ArrayList<>();

        // Keep track of the most recently updated model date.
        long newest = 0;

        // Query the driver for a list of models.
        Collection<ModelResource> result = new ArrayList<>();

        // First case is to handle a targeted request for the current model.
        if (current) {
            ModelResponse response = driver.getCurrentModel(model, ifms).get();
            if (response == null || response.getStatus() != Status.OK) {
                return toResponseEntity(headers, response);
            }

            response.getModel().ifPresent(m -> result.add(m));
        } else {
            ModelsResponse response = driver.getModels(model, ifms).get();
            if (response == null || response.getStatus() != Status.OK) {
                return toResponseEntity(headers, response);
            }

            result.addAll(response.getModels());
        }

        // The requester asked for a list of models so apply any filtering criteria.
        for (ModelResource m : result) {
            long creationTime = XmlUtilities.xmlGregorianCalendar(m.getCreationTime()).toGregorianCalendar()
                    .getTimeInMillis();

            log.info(
                    "[SenseRmController] returning model id = {}, creationTime = {}, If-Modified-Since = {}\n{}",
                    m.getId(), m.getCreationTime(), ifModifiedSince, Encoder.encode(m.getModel()));

            // Create the unique resource URL.
            m.setHref(UrlHelper.append(location.toASCIIString(), m.getId()));

            // If summary results are requested we do not return the model.
            if (summary) {
                m.setModel(null);
            } else {
                // If they requested an encoded transfer we will encode the model contents.
                if (encode) {
                    m.setModel(Encoder.encode(m.getModel()));
                }
            }

            // Save this model and update If-Modified-Since with the creation time.
            models.add(m);

            if (creationTime > newest) {
                newest = creationTime;
            }
        }

        // Update the LastModified header with the value of the newest model.
        headers.setLastModified(newest);

        // We have success so return the models we have found.
        return new ResponseEntity<>(models, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | IllegalArgumentException
            | ExecutionException ex) {
        log.error("[SenseRmController] getModels failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreClient.java

public void open(URI store) throws TException {
    this.open = false;
    if (store.getScheme().equals("thrift")) {
        transport = new TSocket(store.getHost(), store.getPort());
        ((TSocket) transport).setTimeout(2000);
        TProtocol protocol = new TBinaryProtocol(transport);
        client = new ThriftMetaStore.Client(protocol);

        for (int i = 0; i < retries && !this.open; ++i) {
            try {
                transport.open();//from   w w w.  jav  a 2  s  .  c  o m
                this.open = true;
            } catch (TTransportException e) {
                System.err.println("WARN: failed to connect to MetaStore, re-trying...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {
                }
            }
        }
        if (!open) {
            throw new TException("could not connect to meta store");
        }
    } else if (store.getScheme().equals("file")) {
        client = new MetaStoreServer.ThriftMetaStoreHandler("temp_server", this.conf);
        try {
            // for some reason setOption in FB303 doesn't allow one to throw a TException,
            // so I'm having it throw a RuntimeException since that doesn't require changing
            // the method signature.
            client.setOption("metastore.path", store.toASCIIString());
        } catch (RuntimeException e) {
            System.err.println("Could not setoption metastore.path to " + store.getPath());
            throw new TException("could not set metastore path to: " + store.getPath());
        }
    } else {
        throw new TException("Unknown scheme to connect to MetaStore: " + store.getScheme());
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of accepted delta resources associated with the specified SENSE topology model.
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding.//from w  w  w .  j  a  v  a 2 s .c o  m
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param summary If summary=true then a summary collection of delta resources will be returned including the delta
meta-data while excluding the addition, reduction, and m elements. Default value is summary=true.
*
 * @param encode Transfer size of the model element contents can be optimized by gzip/base64
 *    encoding the contained model.  If encode=true then returned model will be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding= "base64")
 *    to reduce transfer size. Default value is encode=false.
 *
 * @param model If model=turtle then the returned addition, reduction, and m elements will contain the full
topology model in a TURTLE representation. Default value is model=turtle.
 * @param id The UUID uniquely identifying the topology model resource.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a collection of delta resources associated with the model resource "
        + "identified by id.", notes = "Returns a collection of delta resources associated with a model resource.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTAS_MSG, response = DeltaResource.class, responseContainer = "List", responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models/{" + HttpConstants.ID_NAME
        + "}/deltas", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getModelDeltas(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id) {

    // We need the request URL to build fully qualified resource URLs.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info(
            "[SenseRmController] GET operation = {}, accept = {}, If-Modified-Since = {}, current = {}, "
                    + "summary = {}, model = {}, modelId = {}",
            location, accept, ifModifiedSince, summary, model, id);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Populate the content location header with our URL location.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Track matching deltas here.
        List<DeltaResource> deltas = new ArrayList<>();

        // Keep track of the most recently updated delta date.
        long newest = 0;

        // Query the driver for a list of deltas.
        DeltasResponse response = driver.getDeltas(model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        // The requester asked for a list of models so apply any filtering criteria.
        for (DeltaResource d : response.getDeltas()) {
            long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                    .getTimeInMillis();

            log.info("[SenseRmController] delta id = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                    d.getLastModified(), ifModifiedSince);

            // Create the unique resource URL.
            d.setHref(UrlHelper.append(location.toASCIIString(), d.getId()));

            // If summary results are requested we do not return the model.
            if (summary) {
                d.setAddition(null);
                d.setReduction(null);
                d.setResult(null);
            } else {
                // If they requested an encoded transfer we will encode the model contents.
                if (encode) {
                    d.setAddition(Encoder.encode(d.getAddition()));
                    d.setReduction(Encoder.encode(d.getReduction()));
                    d.setResult(Encoder.encode(d.getResult()));
                }
            }

            // Save this model and update If-Modified-Since with the creation time.
            deltas.add(d);

            if (lastModified > newest) {
                newest = lastModified;
            }
        }

        // Update the LastModified header with the value of the newest model.
        headers.setLastModified(newest);

        // We have success so return the models we have found.
        return new ResponseEntity<>(deltas, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | IllegalArgumentException
            | ExecutionException ex) {
        log.error("[SenseRmController] getDeltas failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.taverna.prov.W3ProvenanceExport.java

public void writeBundle(WorkflowBundle wfBundle) throws IOException {

    Bundle dataBundle = getBundle();/*from ww  w.  j  ava 2  s . co  m*/

    // Workflow
    DataBundles.setWorkflowBundle(dataBundle, wfBundle);

    // Generate Manifest
    // TODO: This should be done automatically on close/save
    Manifest manifest = new Manifest(dataBundle);
    manifest.populateFromBundle();

    Path workflowRunProvenance = DataBundles.getWorkflowRunProvenance(dataBundle);
    // Additional metadata
    manifest.getAggregation(workflowRunProvenance).setMediatype("text/turtle");

    Agent provPlugin = new Agent();
    provPlugin.setName(
            "Taverna-PROV plugin, " + applicationConfig.getTitle() + " " + applicationConfig.getName());
    provPlugin.setUri(getPluginIdentifier(getClass()));
    manifest.getAggregation(workflowRunProvenance).setCreatedBy(provPlugin);
    manifest.setCreatedBy(provPlugin);

    // Media types:
    for (Entry<URI, String> e : mediaTypes.entrySet()) {
        URI uri = e.getKey();
        String mediatype = e.getValue();
        PathMetadata aggregation = manifest.getAggregation(uri);
        if (aggregation == null) {
            // An external reference? Add it.
            aggregation = manifest.getAggregation(uri);
            //aggregation = new PathMetadata();
            //aggregation.setUri(uri);
            //manifest.getAggregates().add(aggregation);
        }
        aggregation.setMediatype(mediatype);
    }

    // Add annotations

    // This RO Bundle is about a run
    PathAnnotation bundleAboutRun = new PathAnnotation();
    bundleAboutRun.setAbout(runURI);
    bundleAboutRun.setContent(URI.create("/"));
    manifest.getAnnotations().add(bundleAboutRun);

    // Also aggregate the run by ID, and that it was done by taverna
    Agent taverna = new Agent();
    taverna.setName(applicationConfig.getTitle());
    taverna.setUri(getTavernaVersion());
    manifest.getAggregation(runURI).setCreatedBy(taverna);

    // TODO: Do we need both the "history" link and the annotation below?
    manifest.setHistory(Arrays.asList(workflowRunProvenance));

    // This RO Bundle is described in the provenance file
    PathAnnotation provenanceAboutBundle = new PathAnnotation();
    provenanceAboutBundle.setAbout(URI.create("/"));
    provenanceAboutBundle.setContent(URI.create(workflowRunProvenance.toUri().getPath()));
    manifest.getAnnotations().add(provenanceAboutBundle);

    // The wfdesc is about the workflow definition
    Path workflow = DataBundles.getWorkflow(dataBundle);
    // String workflowType = Files.probeContentType(workflow);
    manifest.getAggregation(workflow).setMediatype(WORKFLOW_BUNDLE);
    Path wfdesc = DataBundles.getWorkflowDescription(dataBundle);
    if (Files.exists(wfdesc)) {
        PathAnnotation wfdescAboutWfBundle = new PathAnnotation();
        wfdescAboutWfBundle.setAbout(URI.create(workflow.toUri().getPath()));
        wfdescAboutWfBundle.setContent(URI.create(wfdesc.toUri().getPath()));
        manifest.getAnnotations().add(wfdescAboutWfBundle);
    }

    // And the workflow definition is about the workflow
    PathAnnotation wfBundleAboutWf = new PathAnnotation();
    URITools uriTools = new URITools();
    URI mainWorkflow = uriTools.uriForBean(wfBundle.getMainWorkflow());
    wfBundleAboutWf.setAbout(mainWorkflow);
    URI wfBundlePath = URI.create(workflow.toUri().getPath());
    wfBundleAboutWf.setContent(wfBundlePath);
    manifest.getAnnotations().add(wfBundleAboutWf);
    manifest.getAggregation(mainWorkflow);

    // hasWorkflowDefinition
    PathAnnotation hasWorkflowDefinition = new PathAnnotation();
    hasWorkflowDefinition.setAbout(wfBundlePath);
    UUID uuid = UUID.randomUUID();
    hasWorkflowDefinition.setUri(URI.create("urn:uuid:" + uuid));
    Path annotationBody = DataBundles.getAnnotations(dataBundle).resolve(uuid + ".ttl");
    hasWorkflowDefinition.setContent(URI.create(annotationBody.toUri().getPath()));
    Model model = ModelFactory.createDefaultModel();
    URI relPathToWfBundle = uriTools.relativePath(annotationBody.toUri(), workflow.toUri());
    model.setNsPrefix("wfdesc", WFDESC);
    model.add(model.createResource(mainWorkflow.toASCIIString()),
            model.createProperty(WFDESC + "hasWorkflowDefinition"),
            model.createResource(relPathToWfBundle.toASCIIString()));
    try (OutputStream out = Files.newOutputStream(annotationBody)) {
        model.write(out, "TURTLE", annotationBody.toUri().toASCIIString());
    }
    manifest.getAnnotations().add(hasWorkflowDefinition);

    PathAnnotation wfBundleAboutWfB = new PathAnnotation();
    wfBundleAboutWfB.setAbout(wfBundle.getGlobalBaseURI());
    wfBundleAboutWfB.setContent(URI.create(workflow.toUri().getPath()));
    manifest.getAnnotations().add(wfBundleAboutWfB);

    manifest.writeAsJsonLD();

    // // Saving a data bundle:
    // Path bundleFile = runPath.getParent().resolve(runPath.getFileName() +
    // ".bundle.zip");
    // DataBundles.closeAndSaveBundle(dataBundle, bundleFile);
    // NOTE: From now dataBundle and its Path's are CLOSED
    // and can no longer be accessed

}

From source file:org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl.java

private String generateProxyUriWithScheme() {
    this.readLock.lock();
    try {/* w  w w . j a v  a  2s  .c  om*/
        final String scheme = WebAppUtils.getHttpSchemePrefix(conf);
        String proxy = WebAppUtils.getProxyHostAndPort(conf);
        URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy);
        URI result = ProxyUriUtils.getProxyUri(null, proxyUri, applicationAttemptId.getApplicationId());
        return result.toASCIIString();
    } catch (URISyntaxException e) {
        LOG.warn("Could not proxify the uri for " + applicationAttemptId.getApplicationId(), e);
        return null;
    } finally {
        this.readLock.unlock();
    }
}

From source file:org.apache.hc.core5.benchmark.HttpBenchmark.java

private Results doExecute(final HttpAsyncRequester requester, final Stats stats) throws Exception {

    final URI requestUri = config.getUri();
    final HttpHost host = new HttpHost(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort());

    final AtomicLong requestCount = new AtomicLong(config.getRequests());

    final HttpVersion version = HttpVersion.HTTP_1_1;

    final CountDownLatch completionLatch = new CountDownLatch(config.getConcurrencyLevel());
    final BenchmarkWorker[] workers = new BenchmarkWorker[config.getConcurrencyLevel()];
    for (int i = 0; i < workers.length; i++) {
        final HttpCoreContext context = HttpCoreContext.create();
        context.setProtocolVersion(version);
        final BenchmarkWorker worker = new BenchmarkWorker(requester, host, context, requestCount,
                completionLatch, stats, config);
        workers[i] = worker;/*from   w w  w. j a  v a 2  s .  c  om*/
    }

    final long deadline = config.getTimeLimit() != null ? config.getTimeLimit().toMillis() : Long.MAX_VALUE;

    final long startTime = System.currentTimeMillis();

    for (int i = 0; i < workers.length; i++) {
        workers[i].execute();
    }

    completionLatch.await(deadline, TimeUnit.MILLISECONDS);

    if (config.getVerbosity() >= 3) {
        System.out.println("...done");
    }

    final long endTime = System.currentTimeMillis();

    for (int i = 0; i < workers.length; i++) {
        workers[i].releaseResources();
    }

    return new Results(stats.getServerName(), stats.getVersion(), host.getHostName(),
            host.getPort() > 0 ? host.getPort() : host.getSchemeName().equalsIgnoreCase("https") ? 443 : 80,
            requestUri.toASCIIString(), stats.getContentLength(), config.getConcurrencyLevel(),
            endTime - startTime, stats.getSuccessCount(), stats.getFailureCount(), stats.getKeepAliveCount(),
            stats.getTotalBytesRecv(), stats.getTotalBytesSent(), stats.getTotalContentLength());
}