org.sonatype.nexus.repository.http.HttpResponses Java Examples

The following examples show how to use org.sonatype.nexus.repository.http.HttpResponses. 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: DefaultHttpResponseSenderTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void payloadClosedAfterGET() throws Exception {
  when(request.getAction()).thenReturn(HttpMethods.GET);

  underTest.send(request, HttpResponses.ok(payload), httpServletResponse);

  InOrder order = inOrder(payload, input);

  order.verify(payload).getContentType();
  order.verify(payload, atLeastOnce()).getSize();
  order.verify(payload).openInputStream();
  order.verify(input).close();
  order.verify(payload).close();

  order.verifyNoMoreInteractions();
}
 
Example #2
Source File: ComposerHostedDownloadHandler.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  Repository repository = context.getRepository();
  ComposerHostedFacet hostedFacet = repository.facet(ComposerHostedFacet.class);
  AssetKind assetKind = context.getAttributes().require(AssetKind.class);
  switch (assetKind) {
    case PACKAGES:
      return HttpResponses.ok(hostedFacet.getPackagesJson());
    case LIST:
      throw new IllegalStateException("Unsupported assetKind: " + assetKind);
    case PROVIDER:
      return HttpResponses.ok(hostedFacet.getProviderJson(getVendorToken(context), getProjectToken(context)));
    case ZIPBALL:
      return responseFor(hostedFacet.getZipball(buildZipballPath(context)));
    default:
      throw new IllegalStateException("Unexpected assetKind: " + assetKind);
  }
}
 
Example #3
Source File: PackagesGroupHandler.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Response doGet(@Nonnull final Context context,
                         @Nonnull final GroupHandler.DispatchedRepositories dispatched)
    throws Exception
{
  GroupFacet groupFacet = context.getRepository().facet(GroupFacet.class);
  Map<Repository, Response> responses = getAll(context, groupFacet.members(), dispatched);
  List<Response> successfulResponses = responses.values().stream()
      .filter(response -> response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null)
      .collect(Collectors.toList());
  if (successfulResponses.isEmpty()) {
    return notFoundResponse(context);
  }
  if (successfulResponses.size() == 1) {
    return successfulResponses.get(0);
  }

  List<List<Map<String, String>>> parts = successfulResponses.stream().map(this::parseResponse).collect(
      Collectors.toList());
  List<Map<String, String>> merged = RPackagesUtils.merge(parts);

  return HttpResponses.ok(RPackagesUtils.buildPackages(merged));
}
 
Example #4
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 #5
Source File: ComposerGroupMergingHandler.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected final Response doGet(@Nonnull final Context context,
                               @Nonnull final GroupHandler.DispatchedRepositories dispatched)
    throws Exception
{
  Repository repository = context.getRepository();
  GroupFacet groupFacet = repository.facet(GroupFacet.class);

  makeUnconditional(context.getRequest());
  Map<Repository, Response> responses;
  try {
    responses = getAll(context, groupFacet.members(), dispatched);
  }
  finally {
    makeConditional(context.getRequest());
  }

  List<Payload> payloads = responses.values().stream()
      .filter(response -> response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null)
      .map(Response::getPayload)
      .collect(Collectors.toList());
  if (payloads.isEmpty()) {
    return notFoundResponse(context);
  }
  return HttpResponses.ok(merge(repository, payloads));
}
 
Example #6
Source File: ComposerHostedUploadHandler.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  String vendor = getVendorToken(context);
  String project = getProjectToken(context);
  String version = getVersionToken(context);

  Request request = checkNotNull(context.getRequest());
  Payload payload = checkNotNull(request.getPayload());

  Repository repository = context.getRepository();
  ComposerHostedFacet hostedFacet = repository.facet(ComposerHostedFacet.class);

  hostedFacet.upload(vendor, project, version, payload);
  return HttpResponses.ok();
}
 
Example #7
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 #8
Source File: OrientPyPiHostedHandlers.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handle request for search.
 */
public Handler search() {
  return context -> {
    Payload payload = checkNotNull(context.getRequest().getPayload());
    try (InputStream is = payload.openInputStream()) {
      QueryBuilder query = parseSearchRequest(context.getRepository().getName(), is);
      List<PyPiSearchResult> results = new ArrayList<>();
      for (SearchHit hit : searchQueryService.browse(unrestricted(query))) {
        Map<String, Object> source = hit.getSource();
        Map<String, Object> formatAttributes = (Map<String, Object>) source.getOrDefault(
            MetadataNodeEntityAdapter.P_ATTRIBUTES, Collections.emptyMap());
        Map<String, Object> pypiAttributes = (Map<String, Object>) formatAttributes.getOrDefault(PyPiFormat.NAME,
            Collections.emptyMap());
        String name = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_NAME));
        String version = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_VERSION));
        String summary = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_SUMMARY));
        results.add(new PyPiSearchResult(name, version, summary));
      }
      String response = buildSearchResponse(results);
      return HttpResponses.ok(new StringPayload(response, ContentTypes.APPLICATION_XML));
    }
  };
}
 
Example #9
Source File: DefaultHttpResponseSenderTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void payloadClosedAfterError() throws Exception {
  when(request.getAction()).thenReturn(HttpMethods.GET);

  doThrow(new IOException("Dropped")).when(payload).copy(input, output);

  try {
    underTest.send(request, HttpResponses.ok(payload), httpServletResponse);
    fail("Expected IOException");
  }
  catch (IOException e) {
    assertThat(e.getMessage(), is("Dropped"));
  }

  InOrder order = inOrder(payload, input);

  order.verify(payload).getContentType();
  order.verify(payload, atLeastOnce()).getSize();
  order.verify(payload).openInputStream();
  order.verify(input).close();
  order.verify(payload).close();

  order.verifyNoMoreInteractions();
}
 
Example #10
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 #11
Source File: OrientArchetypeCatalogHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Tries to get the catalog from hosted repository, and generate it if not present.
 */
private Response doGet(final MavenPath path, final Repository repository) throws IOException {
  MavenFacet mavenFacet = repository.facet(MavenFacet.class);
  Content content = mavenFacet.get(path);
  if (content == null) {
    // try to generate it
    repository.facet(MavenHostedFacet.class).rebuildArchetypeCatalog();
    content = mavenFacet.get(path);
    if (content == null) {
      return HttpResponses.notFound(path.getPath());
    }
  }
  AttributesMap attributesMap = content.getAttributes();
  MavenFacetUtils.mayAddETag(attributesMap, getHashAlgorithmFromContent(attributesMap));
  return HttpResponses.ok(content);
}
 
Example #12
Source File: HostedHandler.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 {
  MavenPath path = context.getAttributes().require(MavenPath.class);
  MavenFacet mavenFacet = context.getRepository().facet(MavenFacet.class);
  String action = context.getRequest().getAction();
  switch (action) {
    case GET:
    case HEAD:
      return doGet(path, mavenFacet);

    case PUT:
      return doPut(context, path, mavenFacet);

    case DELETE:
      return doDelete(path, mavenFacet);

    default:
      return HttpResponses.methodNotAllowed(context.getRequest().getAction(), GET, HEAD, PUT, DELETE);
  }
}
 
Example #13
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 #14
Source File: AptHostedHandler.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 {
  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:
      return doPost(context, path, method, hostedFacet);
    default:
      return HttpResponses.methodNotAllowed(method, GET, HEAD, POST);
  }
}
 
Example #15
Source File: AptHostedHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Response doPost(final Context context,
                        final String path,
                        final String method,
                        final AptHostedFacet hostedFacet) throws IOException
{
  if ("rebuild-indexes".equals(path)) {
    hostedFacet.rebuildIndexes();
    return HttpResponses.ok();
  }
  else if ("".equals(path)) {
    hostedFacet.ingestAsset(context.getRequest().getPayload());
    return HttpResponses.created();
  }
  else {
    return HttpResponses.methodNotAllowed(method, GET, HEAD);
  }
}
 
Example #16
Source File: AptSnapshotHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Response handleSnapshotAdminRequest(final Context context, final String id) throws Exception {
  String method = context.getRequest().getAction();
  Repository repository = context.getRepository();
  AptSnapshotFacet snapshotFacet = repository.facet(AptSnapshotFacet.class);

  switch (method) {
    case MKCOL:
      return doMkcol(id, snapshotFacet);
    case PUT:
      return doPut(context, id, snapshotFacet);
    case DELETE:
      return doDelete(id, snapshotFacet);
    default:
      return HttpResponses.methodNotAllowed(method, DELETE, MKCOL, PUT);
  }
}
 
Example #17
Source File: GroupHandler.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 String method = context.getRequest().getAction();
  switch (method) {
    case GET:
    case HEAD: {
      final DispatchedRepositories dispatched = context.getRequest().getAttributes()
          .getOrCreate(DispatchedRepositories.class);
      return doGet(context, dispatched);
    }

    default:
      return HttpResponses.methodNotAllowed(method, GET, HEAD);
  }
}
 
Example #18
Source File: IndexHtmlForwardHandler.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 path = context.getRequest().getPath();

  // sanity, to ensure we don't corrupt the path
  if (!path.endsWith("/")) {
    path = path + "/";
  }

  for (String file : INDEX_FILES) {
    Response response = forward(context, path + file);
    // return response if it was successful or an error which was not not found
    if (response.getStatus().isSuccessful() || response.getStatus().getCode() != HttpStatus.NOT_FOUND) {
      return response;
    }
    // otherwise try next index file
  }

  // or there is no such file, give up not found
  return HttpResponses.notFound(context.getRequest().getPath());
}
 
Example #19
Source File: HandlerContributorTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void addContributedHandlers() throws Exception {
  final AttributesMap attributes = new AttributesMap();

  final Request request = mock(Request.class);
  final Context context = mock(Context.class);

  when(context.getRequest()).thenReturn(request);
  when(context.getAttributes()).thenReturn(attributes);
  when(context.proceed()).thenReturn(HttpResponses.ok(new Content(new StringPayload("test", "text/plain"))));

  final ContributedHandler handlerA = mock(ContributedHandler.class);
  final ContributedHandler handlerB = mock(ContributedHandler.class);
  final HandlerContributor underTest = new HandlerContributor(asList(handlerA, handlerB));
  final Response response = underTest.handle(context);

  assertThat(response.getStatus().isSuccessful(), is(true));
  assertThat(attributes.get(HandlerContributor.EXTENDED_MARKER), is(Boolean.TRUE));

  // Handle a second time to ensure the contributed handlers aren't injected twice
  underTest.handle(context);

  ArgumentCaptor<ContributedHandler> handlerCaptor = ArgumentCaptor.forClass(ContributedHandler.class);
  verify(context, times(2)).insertHandler(handlerCaptor.capture());
  assertThat(handlerCaptor.getAllValues(), is(asList(handlerB, handlerA))); // Intentionally added in "reverse" order
}
 
Example #20
Source File: ContentHeadersHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void okResponseNoExtraData() throws Exception {
  when(context.proceed()).thenReturn(
      HttpResponses.ok(new Content(new StringPayload(payloadString, "text/plain"))));
  final Response r = subject.handle(context);
  assertThat(r.getStatus().isSuccessful(), is(true));
  assertThat(r.getHeaders().get(HttpHeaders.LAST_MODIFIED), nullValue());
  assertThat(r.getHeaders().get(HttpHeaders.ETAG), nullValue());
}
 
Example #21
Source File: ContentHeadersHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void notOkResponse() throws Exception {
  when(context.proceed()).thenReturn(HttpResponses.notFound());
  final Response r = subject.handle(context);
  assertThat(r.getStatus().isSuccessful(), is(false));
  assertThat(r.getHeaders().get(HttpHeaders.LAST_MODIFIED), nullValue());
  assertThat(r.getHeaders().get(HttpHeaders.ETAG), nullValue());
}
 
Example #22
Source File: AptSnapshotHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Response handleSnapshotFetchRequest(final Context context, final String id, final String path) throws Exception {
  Repository repository = context.getRepository();
  AptSnapshotFacet snapshotFacet = repository.facet(AptSnapshotFacet.class);
  if (snapshotFacet.isSnapshotableFile(path)) {
    Content content = snapshotFacet.getSnapshotFile(id, path);
    return content == null ? HttpResponses.notFound() : HttpResponses.ok(content);
  }
  context.getAttributes().set(AptSnapshotHandler.State.class, new AptSnapshotHandler.State(path));
  return context.proceed();
}
 
Example #23
Source File: AptSnapshotHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Response doPut(final Context context, final String id, final AptSnapshotFacet snapshotFacet)
    throws IOException
{
  try (InputStream is = context.getRequest().getPayload().openInputStream()) {
    ControlFile settings = new ControlFileParser().parseControlFile(is);
    snapshotFacet.createSnapshot(id, new FilteredSnapshotComponentSelector(settings));
  }
  return HttpResponses.created();
}
 
Example #24
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 #25
Source File: AptHostedHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Response doGet(final String path, final AptFacet aptFacet) throws IOException {
  Content content = aptFacet.get(path);
  if (content == null) {
    return HttpResponses.notFound(path);
  }
  return HttpResponses.ok(content);
}
 
Example #26
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 #27
Source File: AptSigningHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response handle(final Context context) throws Exception {
  String path = assetPath(context);
  String method = context.getRequest().getAction();
  AptSigningFacet facet = context.getRepository().facet(AptSigningFacet.class);

  if ("repository-key.gpg".equals(path) && GET.equals(method)) {
    return HttpResponses.ok(facet.getPublicKey());
  }

  return context.proceed();
}
 
Example #28
Source File: MavenArchetypeCatalogHandler.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
{
  String method = context.getRequest().getAction();
  switch (method) {
    case GET:
    case HEAD:
      return fetchOrGenerateArchetypeCatalog(context);
    default:
      return HttpResponses.methodNotAllowed(context.getRequest().getAction(), GET, HEAD);
  }
}
 
Example #29
Source File: MavenContentHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response handle(@Nonnull final Context context) throws Exception {
  MavenPath mavenPath = contentPath(context);
  String path = mavenPath.getPath();
  String method = context.getRequest().getAction();
  Repository repository = context.getRepository();

  log.debug("{} repository '{}' content-path: {}", method, repository.getName(), path);

  MavenContentFacet storage = repository.facet(MavenContentFacet.class);

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

    case PUT:
      doPut(context, mavenPath, storage);
      return HttpResponses.created();

    case DELETE:
      return doDelete(mavenPath, storage);

    default:
      return HttpResponses.methodNotAllowed(method, GET, HEAD, PUT, DELETE);
  }
}
 
Example #30
Source File: ProxyHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Builds a not-allowed response if the specified method is unsupported under the specified context, null otherwise.
 */
@Nullable
protected Response buildMethodNotAllowedResponse(final Context context) {
  final String action = context.getRequest().getAction();
  if (!GET.equals(action) && !HEAD.equals(action)) {
    return HttpResponses.methodNotAllowed(action, GET, HEAD);
  }
  return null;
}