Java Code Examples for org.sonatype.nexus.repository.view.Response#getPayload()

The following examples show how to use org.sonatype.nexus.repository.view.Response#getPayload() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NpmSearchGroupHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses a search response, returning the marshaled {@link NpmSearchResponse}.
 */
@Nullable
private NpmSearchResponse parseSearchResponse(final Repository repository, final Response response) {
  Payload payload = response.getPayload();
  if (response.getStatus().getCode() == HttpStatus.OK && payload != null) {
    try (InputStream in = payload.openInputStream()) {
      return npmSearchResponseMapper.readFromInputStream(in);
    }
    catch (IOException e) {
      if (log.isDebugEnabled()) {
        log.warn("Unable to process search response for repository {}, skipping", repository.getName(), e);
      }
      else {
        log.warn("Unable to process search response for repository {}, cause: {}, skipping", repository.getName(),
            e.getMessage());
      }
    }
  }
  return null;
}
 
Example 2
Source File: NpmAuditTarballFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public Optional<String> getTarballHashsum(final Context context) throws TarballLoadingException {
  DispatchedRepositories dispatched = context.getRequest().getAttributes()
      .getOrCreate(DispatchedRepositories.class);
  try {
    Response response = super.doGet(context, dispatched);
    if (response.getPayload() instanceof Content) {
      Content content = (Content) response.getPayload();
      return getHashsum(content.getAttributes());
    }
  }
  catch (Exception e) {
    throw new TarballLoadingException(e.getMessage());
  }

  return Optional.empty();
}
 
Example 3
Source File: OrientPyPiIndexGroupHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private String mergeResponses(final String name,
                              final AssetKind assetKind,
                              final Map<Repository, Response> remoteResponses) throws IOException
{
  Map<String, PyPiLink> results = new TreeMap<>();
  for (Entry<Repository, Response> entry : remoteResponses.entrySet()) {
    Response response = entry.getValue();
    if (response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null) {
      processResults(response, results);
    }
  }

  if (INDEX.equals(assetKind)) {
    return PyPiIndexUtils.buildIndexPage(templateHelper, name, results.values());
  }
  else {
    return PyPiIndexUtils.buildRootIndexPage(templateHelper, results.values());
  }
}
 
Example 4
Source File: OrientPyPiGroupFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Determines if the {@link Content} is stale, initially by assessing if there is
 * no lastModified time stamp associated with the content retrieved from cache then
 * checking if the {@link org.sonatype.nexus.repository.cache.CacheController} has been cleared.
 * Lastly, it should iterate over the members to see if any of the data has been modified since caching.
 * @param name of the cached asset
 * @param content of the asset
 * @param responses from all members
 * @return {@code true} if the content is considered stale.
 */
public boolean isStale(final String name, final Content content, final Map<Repository, Response> responses) {
  DateTime cacheModified = extractLastModified(content);
  if (cacheModified == null || isStale(content)) {
    return true;
  }

  for (Entry<Repository, Response> response : responses.entrySet()) {
    Response responseValue = response.getValue();
    if (responseValue.getStatus().getCode() == HttpStatus.OK) {
      Content responseContent = (Content) responseValue.getPayload();

      if (responseContent != null) {
        DateTime memberLastModified = responseContent.getAttributes().get(CONTENT_LAST_MODIFIED, DateTime.class);
        if (memberLastModified == null || memberLastModified.isAfter(cacheModified)) {
          log.debug("Found stale content while fetching {} from repository {}", name, response.getKey().getName());
          return true;
        }
      }
    }
  }
  return false;
}
 
Example 5
Source File: DescriptionHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public void describeResponse(final Description desc, final Response response) {
  desc.topic("Response");

  final Status status = response.getStatus();
  desc.addTable("Status", ImmutableMap.of(
      "Code", (Object) status.getCode(),
      "Message", nullToEmpty(status.getMessage())
  ));

  desc.addTable("Headers", toMap(response.getHeaders()));
  desc.addTable("Attributes", toMap(response.getAttributes()));

  Payload payload = response.getPayload();
  if (payload != null) {
    desc.addTable("Payload", toMap(payload));
  }
}
 
Example 6
Source File: LastDownloadedHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Response handle(final Context context) throws Exception {
  Response response = context.proceed();

  try {
    if (isSuccessfulRequestWithContent(context, response)) {
      Content content = (Content) response.getPayload();
      maybeUpdateLastDownloaded(content.getAttributes());
    }
  }
  catch (Exception e) {
    log.error("Failed to update last downloaded time for request {}", context.getRequest().getPath(), e);
  }

  return response;
}
 
Example 7
Source File: LastDownloadedHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Response handle(final Context context) throws Exception {
  Response response = context.proceed();

  try {
    if (isSuccessfulRequestWithContent(context, response)) {
      Content content = (Content) response.getPayload();
      maybeUpdateLastDownloaded(content.getAttributes());
    }
  }
  catch (Exception e) {
    log.error("Failed to update last downloaded time for request {}", context.getRequest().getPath(), e);
  }

  return response;
}
 
Example 8
Source File: ContentHeadersHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  final Response response = context.proceed();
  Payload payload = response.getPayload();

  if (response.getStatus().isSuccessful() && payload instanceof Content) {
    final Content content = (Content) payload;
    final DateTime lastModified = content.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
    if (lastModified != null) {
      response.getHeaders().set(HttpHeaders.LAST_MODIFIED, formatDateTime(lastModified));
    }
    final String etag = content.getAttributes().get(Content.CONTENT_ETAG, String.class);
    if (etag != null) {
      response.getHeaders().set(HttpHeaders.ETAG, ETagHeaderUtils.quote(etag));
    }
  }
  return response;
}
 
Example 9
Source File: ComposerProviderHandler.java    From nexus-repository-composer with Eclipse Public License 1.0 5 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  Response response = context.proceed();
  if (!Boolean.parseBoolean(context.getRequest().getAttributes().get(DO_NOT_REWRITE, String.class))) {
    if (response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null) {
      response = HttpResponses
          .ok(composerJsonProcessor.rewriteProviderJson(context.getRepository(), response.getPayload()));
    }
  }
  return response;
}
 
Example 10
Source File: DefaultHttpResponseSender.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void send(@Nullable final Request request, final Response response, final HttpServletResponse httpResponse)
    throws ServletException, IOException
{
  log.debug("Sending response: {}", response);

  // add response headers
  for (Map.Entry<String, String> header : response.getHeaders()) {
    httpResponse.addHeader(header.getKey(), header.getValue());
  }

  // add status followed by payload if we have one
  Status status = response.getStatus();
  String statusMessage = status.getMessage();
  try (Payload payload = response.getPayload()) {
    if (status.isSuccessful() || payload != null) {

      if (statusMessage == null) {
        httpResponse.setStatus(status.getCode());
      }
      else {
        httpResponse.setStatus(status.getCode(), statusMessage);
      }

      if (payload != null) {
        log.trace("Attaching payload: {}", payload);

        if (payload.getContentType() != null) {
          httpResponse.setContentType(payload.getContentType());
        }
        if (payload.getSize() != Payload.UNKNOWN_SIZE) {
          httpResponse.setContentLengthLong(payload.getSize());
        }

        if (request != null && !HttpMethods.HEAD.equals(request.getAction())) {
          try (InputStream input = payload.openInputStream(); OutputStream output = httpResponse.getOutputStream()) {
            payload.copy(input, output);
          }
        }
      }
    }
    else {
      httpResponse.sendError(status.getCode(), statusMessage);
    }
  }
}
 
Example 11
Source File: OrientMavenGroupFacet.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Nullable
private <T extends Closeable> Content merge(final MavenPath mavenPath,
                                            final Map<Repository, Response> responses,
                                            final Function<InputStream, T> streamFunction,
                                            final ContentFunction<T> contentFunction)
    throws IOException
{
  checkMergeHandled(mavenPath);
  // we do not cache subordinates/hashes, they are created as side-effect of cache
  checkArgument(!mavenPath.isSubordinate(), "Only main content handled, not hash or signature: %s", mavenPath);
  LinkedHashMap<Repository, Content> contents = Maps.newLinkedHashMap();
  for (Map.Entry<Repository, Response> entry : responses.entrySet()) {
    if (entry.getValue().getStatus().getCode() == HttpStatus.OK) {
      Response response = entry.getValue();
      if (response.getPayload() instanceof Content) {
        contents.put(entry.getKey(), (Content) response.getPayload());
      }
    }
  }

  if (contents.isEmpty()) {
    log.trace("No 200 OK responses to merge");
    return null;
  }

  T data = null;

  try {
    String contentType = null;
    if (mavenFacet.getMavenPathParser().isRepositoryMetadata(mavenPath)) {
      data = merge(repositoryMetadataMerger::merge, mavenPath, contents, streamFunction);
      contentType = MavenMimeRulesSource.METADATA_TYPE;
    }
    else if (mavenPath.getFileName().equals(Constants.ARCHETYPE_CATALOG_FILENAME)) {
      data = merge(archetypeCatalogMerger::merge, mavenPath, contents, streamFunction);
      contentType = ContentTypes.APPLICATION_XML;
    }

    if (data == null) {
      log.trace("No content resulted out of merge");
      return null;
    }

    return contentFunction.apply(data, contentType);
  }
  finally {
    if (data != null) {
      data.close();
    }
  }
}
 
Example 12
Source File: LastDownloadedHandler.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isSuccessfulRequestWithContent(final Context context, final Response response) {
  return isGetOrHeadRequest(context)
      && isSuccessfulOrNotModified(response)
      && response.getPayload() != null
      && response.getPayload() instanceof Content;
}
 
Example 13
Source File: LastDownloadedHandler.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isSuccessfulRequestWithContent(final Context context, final Response response) {
  return isGetOrHeadRequest(context)
      && isSuccessfulOrNotModified(response.getStatus())
      && response.getPayload() instanceof Content;
}
 
Example 14
Source File: PartialFetchHandler.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  final Response response = context.proceed();

  // Range requests only apply to GET
  if (!HttpMethods.GET.equals(context.getRequest().getAction())) {
    return response;
  }

  if (response.getStatus().getCode() != HttpStatus.OK) {
    // We don't interfere with any non-200 responses
    return response;
  }

  final Payload payload = response.getPayload();
  if (payload == null) {
    return response;
  }

  if (payload.getSize() == Payload.UNKNOWN_SIZE) {
    // We can't do much if we don't know how big the payload is
    return response;
  }

  final String rangeHeader = getHeaderValue(context.getRequest(), HttpHeaders.RANGE);
  if (rangeHeader == null) {
    return response;
  }

  final List<Range<Long>> ranges = rangeParser.parseRangeSpec(rangeHeader, payload.getSize());

  if (ranges == null) {
    // The ranges were not satisfiable
    return HttpResponses.rangeNotSatisfiable(payload.getSize());
  }

  if (ranges.isEmpty()) {
    // No ranges were specified, or they could not be parsed
    return response;
  }

  if (ranges.size() > 1) {
    return HttpResponses.notImplemented("Multiple ranges not supported.");
  }

  final String ifRangeHeader = getHeaderValue(context.getRequest(), HttpHeaders.IF_RANGE);
  if (ifRangeHeader != null && !ifRangeHeaderMatches(response, ifRangeHeader)) {
    return response;
  }

  Range<Long> requestedRange = ranges.get(0);

  // Mutate the response
  return partialResponse(response, payload, requestedRange);
}