org.sonatype.nexus.repository.view.Context Java Examples

The following examples show how to use org.sonatype.nexus.repository.view.Context. 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: OrientPyPiProxyFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Content store(final Context context, final Content content) throws IOException {
  AssetKind assetKind = context.getAttributes().require(AssetKind.class);
  if (assetKind.equals(AssetKind.SEARCH)) {
    return content;  // we do not store search results
  }
  TokenMatcher.State state = matcherState(context);
  switch (assetKind) {
    case ROOT_INDEX:
      return putRootIndex(content);
    case INDEX:
      String name = name(state);
      return putIndex(name, content);
    case PACKAGE:
      return putPackage(path(state), content);
    default:
      throw new IllegalStateException();
  }
}
 
Example #2
Source File: CocoapodsProxyFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Content getCachedContent(final Context context) {
  final String path = removeInitialSlashFromPath(context.getRequest().getPath());
  Content ret;
  AssetKind assetKind = context.getAttributes().require(AssetKind.class);
  switch (assetKind) {
    case CDN_METADATA:
      if (!path.startsWith(CDN_METADATA_PREFIX)) {
        ret = facet(CocoapodsFacet.class).get(CDN_METADATA_PREFIX + path);
        break;
      }
    case SPEC:
    case POD:
      ret = facet(CocoapodsFacet.class).get(extractPodPath(context));
      break;
    default:
      throw new IllegalStateException(ASSET_KIND_ERROR + assetKind.name());
  }
  return ret;
}
 
Example #3
Source File: ConcurrentProxyTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Content fetch(final String url, final Context context, final Content stale) throws IOException {
  upstreamRequestLog.add(url);

  if (url.startsWith(META_PREFIX)) {
    // wait until the test releases the download
    metaDownloadPermits.acquireUninterruptibly();
    return metaContent;
  }

  if (url.startsWith(ASSET_PREFIX)) {
    // wait until the test releases the download
    assetDownloadPermits.acquireUninterruptibly();
    if (url.contains("broken")) {
      throw new IOException("oops");
    }
    return assetContent;
  }

  return null;
}
 
Example #4
Source File: NpmSearchGroupHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Response doGet(@Nonnull final Context context,
                         @Nonnull final DispatchedRepositories dispatched)
    throws Exception
{
  checkNotNull(context);
  checkNotNull(dispatched);

  Request request = context.getRequest();
  Parameters parameters = request.getParameters();
  String text = npmSearchParameterExtractor.extractText(parameters);

  NpmSearchResponse response;
  if (text.isEmpty()) {
    response = npmSearchResponseFactory.buildEmptyResponse();
  }
  else {
    response = searchMembers(context, dispatched, parameters);
  }

  String content = npmSearchResponseMapper.writeString(response);
  return HttpResponses.ok(new StringPayload(content, ContentTypes.APPLICATION_JSON));
}
 
Example #5
Source File: NpmAuditTarballFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Optional<String> getComponentHashsumForProxyRepo(final Repository repository, final Context context)
    throws TarballLoadingException
{
  try {
    UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
    Content content = repository.facet(ProxyFacet.class).get(context);
    if (content != null) {
      return getHashsum(content.getAttributes());
    }
  }
  catch (IOException e) {
    throw new TarballLoadingException(e.getMessage());
  }
  finally {
    UnitOfWork.end();
  }

  return Optional.empty();
}
 
Example #6
Source File: OrientVersionPolicyHandler.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 {
  String httpMethod = context.getRequest().getAction();
  if (GET.equals(httpMethod) || HEAD.equals(httpMethod)) {
    return context.proceed();
  }
  final MavenPath path = context.getAttributes().require(MavenPath.class);
  final MavenFacet mavenFacet = context.getRepository().facet(MavenFacet.class);
  final VersionPolicy versionPolicy = mavenFacet.getVersionPolicy();
  if (path.getCoordinates() != null && !versionPolicyValidator.validArtifactPath(versionPolicy, path.getCoordinates())) {
    return HttpResponses.badRequest("Repository version policy: " + versionPolicy + " does not allow version: " +
        path.getCoordinates().getVersion());
  }
  if (!versionPolicyValidator.validMetadataPath(versionPolicy, path.main().getPath())) {
    return HttpResponses.badRequest("Repository version policy: " + versionPolicy +
        " does not allow metadata in path: " + path.getPath());
  }
  return context.proceed();
}
 
Example #7
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private <X extends Throwable> void logContentOrThrow(@Nullable final Content content,
                                                     final Context context,
                                                     @Nullable final StatusLine statusLine,
                                                     final X exception) throws X
{
  String logMessage = buildLogContentMessage(content, statusLine);
  String repositoryName = context.getRepository().getName();
  String contextUrl = getUrl(context);

  if (content != null) {
    log.debug(logMessage, exception, repositoryName, contextUrl, statusLine);
  }
  else {
    if (exception instanceof RemoteBlockedIOException) {
      // trace because the blocked status of a repo is typically discoverable in the UI and other log messages
      log.trace(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else if (log.isDebugEnabled()) {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine);
    }
    throw exception;
  }
}
 
Example #8
Source File: SearchGroupHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Builds a context that contains a request that can be "replayed" with its post body content. Since we're repeating
 * the same post request to all the search endpoints, we need to have a new request instance with a payload we can
 * read multiple times.
 */
private Context buildReplayableContext(final Context context) throws IOException {
  checkNotNull(context);
  Request request = checkNotNull(context.getRequest());
  Payload payload = checkNotNull(request.getPayload());
  try (InputStream in = payload.openInputStream()) {
    byte[] content = ByteStreams.toByteArray(in);
    Context replayableContext = new Context(context.getRepository(),
        new Builder()
            .attributes(request.getAttributes())
            .headers(request.getHeaders())
            .action(request.getAction())
            .path(request.getPath())
            .parameters(request.getParameters())
            .payload(new BytesPayload(content, payload.getContentType()))
            .build());

    copyLocalContextAttributes(context, replayableContext);

    return replayableContext;
  }
}
 
Example #9
Source File: VersionPolicyHandler.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 {
  String httpMethod = context.getRequest().getAction();
  if (GET.equals(httpMethod) || HEAD.equals(httpMethod)) {
    return context.proceed();
  }
  final MavenPath path = context.getAttributes().require(MavenPath.class);
  final MavenContentFacet mavenFacet = context.getRepository().facet(MavenContentFacet.class);
  final VersionPolicy versionPolicy = mavenFacet.getVersionPolicy();
  final Coordinates coordinates = path.getCoordinates();
  if (coordinates != null && !versionPolicyValidator.validArtifactPath(versionPolicy, coordinates)) {
    return HttpResponses.badRequest("Repository version policy: " + versionPolicy + " does not allow version: " +
        coordinates.getVersion());
  }
  if (!versionPolicyValidator.validMetadataPath(versionPolicy, path.main().getPath())) {
    return HttpResponses.badRequest("Repository version policy: " + versionPolicy +
        " does not allow metadata in path: " + path.getPath());
  }
  return context.proceed();
}
 
Example #10
Source File: NpmTokenFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Response login(final Context context) {
  final Payload payload = context.getRequest().getPayload();
  if (payload == null) {
    return NpmResponses.badRequest("Missing body");
  }
  StorageFacet storageFacet = facet(StorageFacet.class);
  try (TempBlob tempBlob = storageFacet.createTempBlob(payload, NpmFacetUtils.HASH_ALGORITHMS)) {
    NestedAttributesMap request = NpmJsonUtils.parse(tempBlob);
    String token = npmTokenManager.login(request.get("name", String.class), request.get("password", String.class));
    if (null != token) {
      NestedAttributesMap response = new NestedAttributesMap("response", Maps.newHashMap());
      response.set("ok", Boolean.TRUE.toString());
      response.set("rev", "_we_dont_use_revs_any_more");
      response.set("id", "org.couchdb.user:undefined");
      response.set("token", token);
      return HttpResponses.created(new BytesPayload(NpmJsonUtils.bytes(response), ContentTypes.APPLICATION_JSON));
    }
    else {
      return NpmResponses.badCredentials("Bad username or password");
    }
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #11
Source File: CocoapodsProxyFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Content store(final Context context, final Content content) throws IOException {
  final String path = removeInitialSlashFromPath(context.getRequest().getPath());
  Content ret;
  AssetKind assetKind = context.getAttributes().require(AssetKind.class);
  boolean toAttachComponent = isComponentSupported(assetKind);
  switch (assetKind) {
    case CDN_METADATA:
      ret = facet(CocoapodsFacet.class).getOrCreateAsset(CDN_METADATA_PREFIX + path, content, toAttachComponent);
      cacheControllerHolder.getMetadataCacheController().invalidateCache();
      break;
    case SPEC:
      ret = facet(CocoapodsFacet.class).getOrCreateAsset(path, content, toAttachComponent);
      cacheControllerHolder.getMetadataCacheController().invalidateCache();
      break;
    case POD:
      ret = facet(CocoapodsFacet.class).getOrCreateAsset(extractPodPath(context), content, toAttachComponent);
      break;
    default:
      throw new IllegalStateException(ASSET_KIND_ERROR + assetKind.name());
  }
  return ret;
}
 
Example #12
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 #13
Source File: NpmSearchIndexFacetProxy.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public Content searchIndex(@Nullable final DateTime since) throws IOException {
  try {
    final Request getRequest = new Request.Builder()
        .action(GET)
        .path("/" + NpmFacetUtils.REPOSITORY_ROOT_ASSET)
        .build();
    Context context = new Context(getRepository(), getRequest);
    context.getAttributes().set(ProxyTarget.class, ProxyTarget.SEARCH_INDEX);
    Content fullIndex = getRepository().facet(ProxyFacet.class).get(context);
    if (fullIndex == null) {
      throw new IOException("Could not retrieve registry root");
    }
    return NpmSearchIndexFilter.filterModifiedSince(fullIndex, since);
  }
  catch (Exception e) {
    throw new IOException(e);
  }
}
 
Example #14
Source File: OrientPyPiHostedHandlers.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Utility method to extract the uploaded content. Populates the attributes map with any other metadata. One and only
 * one file upload with a field name of "content" should be present in the upload, or {@link IllegalStateException}
 * is thrown to indicate unexpected input.
 */
private SignablePyPiPackage extractPayloads(final Context context) throws IOException {
  checkNotNull(context);
  Map<String, String> attributes = new LinkedHashMap<>();
  Request request = context.getRequest();
  TempBlobPartPayload contentBlob = null;
  TempBlobPartPayload signatureBlob = null;

  for (PartPayload payload : checkNotNull(request.getMultiparts())) {
    if (payload.isFormField()) {
      addAttribute(attributes, payload);
    }
    else if (FIELD_CONTENT.equals(payload.getFieldName())) {
      checkState(contentBlob == null);
      contentBlob = createBlobFromPayload(payload, context.getRepository());
    } else if (GPG_SIGNATURE.equals(payload.getFieldName())) {
      checkState(signatureBlob == null);
      signatureBlob = createBlobFromPayload(payload, context.getRepository());
    }
  }
  checkState (contentBlob != null);
  return new SignablePyPiPackage(contentBlob, attributes, signatureBlob);
}
 
Example #15
Source File: ConanHostedFacet.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
public Response get(final Context context) {
  log.debug("Request {}", context.getRequest().getPath());

  TokenMatcher.State state = context.getAttributes().require(TokenMatcher.State.class);
  ConanCoords coord = ConanHostedHelper.convertFromState(state);
  AssetKind assetKind = context.getAttributes().require(AssetKind.class);
  String assetPath = ConanHostedHelper.getHostedAssetPath(coord, assetKind);

  Content content = doGet(assetPath);
  if (content == null) {
    return HttpResponses.notFound();
  }

  return new Response.Builder()
      .status(success(OK))
      .payload(new StreamPayload(
          new InputStreamSupplier()
          {
            @Nonnull
            @Override
            public InputStream get() throws IOException {
              return content.openInputStream();
            }
          },
          content.getSize(),
          content.getContentType()))
      .build();
}
 
Example #16
Source File: SuffixMatcher.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean matches(final Context context) {
  checkNotNull(context);
  String path = context.getRequest().getPath();
  log.debug("Matching: {} ends-with={} ignore-case: {}", path, suffix, ignoreCase);
  if (ignoreCase) {
    return Strings2.lower(path).endsWith(Strings2.lower(suffix));
  }
  else {
    return path.endsWith(suffix);
  }
}
 
Example #17
Source File: LiteralMatcher.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean matches(final Context context) {
  checkNotNull(context);
  String path = context.getRequest().getPath();
  log.debug("Matching: {}={} ignore-case: {}", path, literal, ignoreCase);
  if (ignoreCase) {
    return path.equalsIgnoreCase(literal);
  }
  else {
    return path.equals(literal);
  }
}
 
Example #18
Source File: PyPiProxyHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Nullable
protected Response buildMethodNotAllowedResponse(final Context context) {
  if (isSearchRequest(context.getRequest())) {
    return null;
  }
  return super.buildMethodNotAllowedResponse(context);
}
 
Example #19
Source File: AptHostedHandler.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response handle(Context context) throws Exception {
  String path = assetPath(context);
  String method = context.getRequest().getAction();

  AptFacet aptFacet = context.getRepository().facet(AptFacet.class);
  AptHostedFacet hostedFacet = context.getRepository().facet(AptHostedFacet.class);

  switch (method) {
    case GET:
    case HEAD: {
      return doGet(path, aptFacet);
    }

    case POST: {
      if (path.equals("rebuild-indexes")) {
        hostedFacet.rebuildIndexes();
        return HttpResponses.ok();
      }
      else if (path.equals("")) {
        hostedFacet.ingestAsset(context.getRequest().getPayload());
        return HttpResponses.created();
      }
      else {
        return HttpResponses.methodNotAllowed(method, GET, HEAD);
      }
    }

    default:
      return HttpResponses.methodNotAllowed(method, GET, HEAD, POST);
  }
}
 
Example #20
Source File: NpmTokenFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response logout(final Context context) {
  if (npmTokenManager.logout()) {
    NestedAttributesMap response = new NestedAttributesMap("response", Maps.newHashMap());
    response.set("ok", Boolean.TRUE.toString());
    return NpmResponses.ok(new BytesPayload(NpmJsonUtils.bytes(response), ContentTypes.APPLICATION_JSON));
  }
  else {
    return NpmResponses.notFound("Token not found");
  }
}
 
Example #21
Source File: NpmHandlers.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  State state = context.getAttributes().require(TokenMatcher.State.class);
  Repository repository = context.getRepository();
  log.debug("[putPackage] repository: {} tokens: {}", repository.getName(), state.getTokens());

  repository.facet(NpmHostedFacet.class)
      .putPackage(packageId(state), revision(state), context.getRequest().getPayload());
  return NpmResponses.ok();
}
 
Example #22
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Content getCachedContent(final Context context) throws IOException
{
  ProxyTarget proxyTarget = context.getAttributes().require(ProxyTarget.class);

  if (proxyTarget.equals(ProxyTarget.SEARCH_V1_RESULTS)) {
    return null; // we do not cache search results
  }
  else if (ProxyTarget.PACKAGE == proxyTarget) {
    return getPackageRoot(context, packageId(matcherState(context)));
  }
  else if (ProxyTarget.DIST_TAGS == proxyTarget) {
    return getDistTags(packageId(matcherState(context)));
  }
  else if (ProxyTarget.TARBALL == proxyTarget) {
    TokenMatcher.State state = matcherState(context);
    return getTarball(packageId(state), tarballName(state));
  }
  else if (ProxyTarget.SEARCH_INDEX == proxyTarget) {
    Content fullIndex = getRepositoryRoot();
    if (fullIndex == null) {
      return null;
    }
    return NpmSearchIndexFilter.filterModifiedSince(
        fullIndex, NpmHandlers.indexSince(context.getRequest().getParameters()));
  }
  throw new IllegalStateException();
}
 
Example #23
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
@TransactionalTouchBlob
public Content getPackageRoot(final Context context, final NpmPackageId packageId) throws IOException {
  checkNotNull(packageId);
  StorageTx tx = UnitOfWork.currentTx();
  Asset packageRootAsset = NpmFacetUtils.findPackageRootAsset(tx, tx.findBucket(getRepository()), packageId);
  if (packageRootAsset == null) {
    return null;
  }

  return toContent(getRepository(), packageRootAsset)
      .fieldMatchers(rewriteTarballUrlMatcher(getRepository(), packageId.id()))
      .packageId(packageRootAsset.name())
      .missingBlobInputStreamSupplier(missingBlobException -> doGetOnMissingBlob(context, missingBlobException));
}
 
Example #24
Source File: NpmHandlers.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  State state = context.getAttributes().require(TokenMatcher.State.class);
  Repository repository = context.getRepository();
  log.debug("[deleteToken] repository: {} tokens: {}", repository.getName(), state.getTokens());

  return repository.facet(NpmTokenFacet.class).logout(context);
}
 
Example #25
Source File: UnitOfWorkHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response handle(Context context) throws Exception {
  UnitOfWork.begin(context.getRepository().facet(StorageFacet.class).txSupplier());
  try {
    return context.proceed();
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #26
Source File: NpmHandlers.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  State state = context.getAttributes().require(TokenMatcher.State.class);
  Repository repository = context.getRepository();
  log.debug("[createToken] repository: {} tokens: {}", repository.getName(), state.getTokens());

  return repository.facet(NpmTokenFacet.class).login(context);
}
 
Example #27
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Content putTarball(final NpmPackageId packageId,
                           final String tarballName,
                           final TempBlob tempBlob,
                           final Content content,
                           final Context context) throws IOException
{
  checkNotNull(packageId);
  checkNotNull(tarballName);
  checkNotNull(tempBlob);
  checkNotNull(content);
  checkNotNull(context);
  return doPutTarball(packageId, tarballName, tempBlob, content);
}
 
Example #28
Source File: MavenContentHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void doPut(
    @Nonnull final Context context,
    final MavenPath mavenPath,
    final MavenContentFacet storage)
    throws IOException
{
  validatePathForStrictLayoutPolicy(mavenPath, storage);
  storage.put(mavenPath, context.getRequest().getPayload());
}
 
Example #29
Source File: PyPiRecipeSupportTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) {
  String name = name(matcherState(context));
  assertThat(name, is("foo"));
  throw new RuntimeException("index");
}
 
Example #30
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected CacheController getCacheController(final Context context) {
  if (isDebPackageContentType(assetPath(context))) {
    return cacheControllerHolder.getContentCacheController();
  }
  return cacheControllerHolder.getMetadataCacheController();
}