org.sonatype.nexus.repository.view.Response Java Examples
The following examples show how to use
org.sonatype.nexus.repository.view.Response.
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: ConditionalRequestHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Nonnull @Override public Response handle(@Nonnull final Context context) throws Exception { final Predicate<Response> requestPredicate = requestPredicate(context.getRequest()); if (requestPredicate != null) { makeUnconditional(context.getRequest()); try { return handleConditional(context, requestPredicate); } finally { makeConditional(context.getRequest()); } } return context.proceed(); }
Example #2
Source File: LastDownloadedHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #3
Source File: NpmAuditErrorHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
private Response handleAuditExceptions(final ExecutionException e) { // list of all general exceptions in org.sonatype.nexus.repository.vulnerability.exceptions Throwable cause = e.getCause(); if (cause instanceof CompatibilityException) { return NpmResponses.npmErrorAuditResponse(BAD_REQUEST, cause.getMessage()); } if (cause instanceof VulnerabilityFetchingException || cause instanceof InternalException) { log.warn(cause.getMessage(), e); return NpmResponses.npmErrorAuditResponse(INTERNAL_SERVER_ERROR, USER_ERROR_MSG); } else if (cause instanceof ConfigurationException) { log.warn(cause.getMessage(), e); return NpmResponses.npmErrorAuditResponse(BAD_REQUEST, cause.getMessage()); } else { log.error(e.getMessage(), e); return NpmResponses.npmErrorAuditResponse(INTERNAL_SERVER_ERROR, USER_ERROR_MSG); } }
Example #4
Source File: GroupHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Returns the first OK response from member repositories or {@link HttpResponses#notFound()} if none of the members * responded with OK. */ protected Response getFirst(@Nonnull final Context context, @Nonnull final List<Repository> members, @Nonnull final DispatchedRepositories dispatched) throws Exception { final Request request = context.getRequest(); for (Repository member : members) { log.trace("Trying member: {}", member); // track repositories we have dispatched to, prevent circular dispatch for nested groups if (dispatched.contains(member)) { log.trace("Skipping already dispatched member: {}", member); continue; } dispatched.add(member); final ViewFacet view = member.facet(ViewFacet.class); final Response response = view.dispatch(request, context); log.trace("Member {} response {}", member, response.getStatus()); if (isValidResponse(response)) { return response; } } return notFoundResponse(context); }
Example #5
Source File: ContentHeadersHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #6
Source File: GroupHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void returnsFirstOkOrFirstBypassHttpErrorsHeaderResponse() throws Exception { Response forbidden = forbidden(); forbidden.getHeaders().set(BYPASS_HTTP_ERRORS_HEADER_NAME, BYPASS_HTTP_ERRORS_HEADER_VALUE); Response ok = ok(); setupDispatch(forbidden, ok); assertGetFirst(forbidden); verify(viewFacet1, times(1)).dispatch(request, context); verify(viewFacet2, times(0)).dispatch(request, context); setupDispatch(ok, forbidden); assertGetFirst(ok); verify(viewFacet1, times(2)).dispatch(request, context); verify(viewFacet2, times(0)).dispatch(request, context); }
Example #7
Source File: NpmSearchGroupHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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: NpmSearchGroupHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Searches the member repositories, returning the merged response for all contacted member repositories that returned * a valid search response. */ private NpmSearchResponse searchMembers(final Context context, final DispatchedRepositories dispatched, final Parameters parameters) throws Exception { // preserve original from and size for repeated queries int from = npmSearchParameterExtractor.extractFrom(parameters); int size = npmSearchParameterExtractor.extractSize(parameters); // if the text is empty, then we override the original parameters to return a full set from each upstream source // we could make multiple queries to make this more efficient, but this is the simplest implementation for now parameters.replace("from", "0"); parameters.replace("size", Integer.toString(v1SearchMaxResults)); // sort all the merged results by normalized search score, then build the result responses to send back GroupFacet groupFacet = context.getRepository().facet(GroupFacet.class); Set<Entry<Repository, Response>> entries = getAll(context, groupFacet.members(), dispatched).entrySet(); List<NpmSearchResponseObject> mergedResponses = mergeAndNormalizeResponses(entries); mergedResponses.sort(comparingDouble(NpmSearchResponseObject::getSearchScore).reversed()); List<NpmSearchResponseObject> mergedResponseObjects = mergedResponses.stream() .skip(from) .limit(size) .collect(toList()); return npmSearchResponseFactory.buildResponseForObjects(mergedResponseObjects); }
Example #9
Source File: NpmSearchGroupHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * 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 #10
Source File: AptHostedHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
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 #11
Source File: NpmHandlers.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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("[putDistTags] repository: {} tokens: {}", repository.getName(), state.getTokens()); try { repository.facet(NpmHostedFacet.class) .deleteDistTags(packageId(state), state.getTokens().get(T_PACKAGE_TAG), context.getRequest().getPayload()); return NpmResponses.ok(); } catch (IOException e) { //NOSONAR return NpmResponses.badRequest(e.getMessage()); } }
Example #12
Source File: ProxyHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testBypassHttpErrorExceptionPropagatesCodeWithMessageWithHeader() throws Exception { final int httpStatus = HttpStatus.FORBIDDEN; final String errorMessage = "Error Message"; final String headerName = "Header Name"; final String headerValue = "Header Value"; ListMultimap<String, String> headers = ArrayListMultimap.create(); headers.put(headerName, headerValue); BypassHttpErrorException bypassException = new BypassHttpErrorException(httpStatus, errorMessage, headers); when(request.getAction()).thenReturn(HttpMethods.GET); doThrow(bypassException).when(proxyFacet).get(context); Response response = underTest.handle(context); assertStatusCode(response, httpStatus); assertStatusMessage(response, errorMessage); assertThat(response.getHeaders().get(headerName), is(headerValue)); }
Example #13
Source File: AptSnapshotHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Override public Response handle(final Context context) throws Exception { String path = context.getRequest().getPath(); Matcher matcher = SNAPSHOT_PATH_PATTERN.matcher(path); if (!matcher.matches()) { context.getAttributes().set(AptSnapshotHandler.State.class, new AptSnapshotHandler.State(path.substring(1))); return context.proceed(); } String id = matcher.group(1); path = matcher.group(2); if (path.length() == 0) { return handleSnapshotAdminRequest(context, id); } else { return handleSnapshotFetchRequest(context, id, path); } }
Example #14
Source File: GroupHandler.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #15
Source File: NpmFacetUtils.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Merges the dist-tag responses from all members and merges the values */ public static Response mergeDistTagResponse(final Map<Repository, Response> responses) throws IOException { final List<NestedAttributesMap> collection = responses .values().stream() .map(response -> (Content) response.getPayload()) .filter(Objects::nonNull) .map(NpmFacetUtils::readDistTagResponse) .filter(Objects::nonNull) .collect(toList()); final NestedAttributesMap merged = collection.get(0); if (collection.size() > 1) { collection.subList(1, collection.size()) .forEach(response -> response.backing().forEach(populateLatestVersion(merged))); } return new Response.Builder() .status(success(OK)) .payload(new BytesPayload(NpmJsonUtils.bytes(merged), APPLICATION_JSON)) .build(); }
Example #16
Source File: PartialFetchHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testHandleWhenRangeParserReturnsMultipleRanges() throws Exception { Request request = createGetRequestBuilder().header(RANGE, RANGE_HEADER).build(); Response response = createOkResponseBuilder().payload(PAYLOAD).build(); List<Range<Long>> multipleRanges = asList(ZERO_TO_TWO_RANGE, ZERO_TO_TWO_RANGE); when(rangeParser.parseRangeSpec(RANGE_HEADER, PAYLOAD.getSize())).thenReturn(multipleRanges); Response actualResponse = doHandle(request, response); assertThat(actualResponse.getStatus().getCode(), is(NOT_IMPLEMENTED)); assertThat(actualResponse.getStatus().getMessage(), is("Multiple ranges not supported.")); }
Example #17
Source File: NpmHandlers.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Nonnull @Override public Response handle(@Nonnull final Context context) throws Exception { Repository repository = context.getRepository(); Parameters parameters = context.getRequest().getParameters(); log.debug("[searchV1] repository: {} parameters: {}", repository.getName(), parameters); return NpmResponses.ok(repository.facet(NpmSearchFacet.class).searchV1(parameters)); }
Example #18
Source File: PartialFetchHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testHandleWhenPayloadSizeIsUnknown() throws Exception { Request request = createGetRequestBuilder().build(); Response response = createOkResponseBuilder().payload(createPayloadOfUnknownSize()).build(); assertThat(doHandle(request, response), is(sameInstance(response))); }
Example #19
Source File: NpmWhoamiHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testHandle() throws Exception { currentUser("testuser"); Response response = underTest.handle(context); assertThat(response.getStatus().getCode(), is(200)); assertThat(IOUtils.toString(response.getPayload().openInputStream()), is("{\"username\":\"testuser\"}")); }
Example #20
Source File: PartialFetchHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testHandleWhenPayloadIsNull() throws Exception { Request request = createGetRequestBuilder().build(); Response responseWithNullPayload = createOkResponseBuilder().build(); assertThat(doHandle(request, responseWithNullPayload), is(sameInstance(responseWithNullPayload))); }
Example #21
Source File: PartialFetchHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testHandleWhenIfRangeCheckFailsToMatchOnLastModified() throws Exception { Request request = createGetRequestBuilder() .header(RANGE, RANGE_HEADER).header(IF_RANGE, "Wed, 17 Jun 2015 11:31:00 GMT").build(); Response response = createOkResponseBuilder() .header(ETAG, ETAG_VALUE).header(LAST_MODIFIED, LAST_MODIFIED_VALUE).payload(PAYLOAD).build(); when(rangeParser.parseRangeSpec(RANGE_HEADER, PAYLOAD.getSize())).thenReturn(singletonList(ZERO_TO_TWO_RANGE)); assertThat(doHandle(request, response), is(sameInstance(response))); }
Example #22
Source File: ProxyHandler.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * 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; }
Example #23
Source File: AptSigningHandler.java From nexus-repository-apt with Eclipse Public License 1.0 | 5 votes |
@Override public Response handle(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 #24
Source File: HttpResponses.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
public static Response rangeNotSatisfiable(final long contentSize) { return new Response.Builder() .status(Status.failure(REQUESTED_RANGE_NOT_SATISFIABLE)) .header(HttpHeaders.CONTENT_LENGTH, "0") .header(HttpHeaders.CONTENT_RANGE, "bytes */" + contentSize) .build(); }
Example #25
Source File: NegativeCacheHandler.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Nonnull @Override public Response handle(@Nonnull final Context context) throws Exception { String action = context.getRequest().getAction(); if (!NFC_CACHEABLE_ACTIONS.contains(action)) { return context.proceed(); } NegativeCacheFacet negativeCache = context.getRepository().facet(NegativeCacheFacet.class); NegativeCacheKey key = negativeCache.getCacheKey(context); Response response; Status status = negativeCache.get(key); if (status == null) { response = context.proceed(); if (isNotFound(response)) { negativeCache.put(key, response.getStatus()); } else if (response.getStatus().isSuccessful()) { negativeCache.invalidate(key); } } else { response = buildResponse(status, context); log.debug("Found {} in negative cache, returning {}", key, response); } return response; }
Example #26
Source File: NpmResponses.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Nonnull public static Response notFound(@Nullable final String message) { return new Response.Builder() .status(Status.failure(NOT_FOUND, "Not Found")) .payload(statusPayload(false, message)) .build(); }
Example #27
Source File: RoutingRuleHandler.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override public Response handle(final Context context) throws Exception { if (routingRuleHelper.isAllowed(context.getRepository(), path(context.getRequest()))) { return context.proceed(); } return HttpResponses.forbidden(PATH_IS_BLOCKED); }
Example #28
Source File: ContentHeadersHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void okResponse() throws Exception { final Content content = new Content(new StringPayload(payloadString, "text/plain")); content.getAttributes().set(Content.CONTENT_LAST_MODIFIED, now); content.getAttributes().set(Content.CONTENT_ETAG, "etag"); when(context.proceed()).thenReturn(HttpResponses.ok(content)); final Response r = subject.handle(context); assertThat(r.getStatus().isSuccessful(), is(true)); assertThat(r.getHeaders().get(HttpHeaders.LAST_MODIFIED), equalTo(DateTimeUtils.formatDateTime(now))); assertThat(r.getHeaders().get(HttpHeaders.ETAG), equalTo("\"etag\"")); }
Example #29
Source File: ViewServletTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void describeRequestReturnsDescriptionResponse_HTML() throws Exception { descriptionRequested("HTML"); facetThrowsException(false); underTest.dispatchAndSend(request, facet, defaultResponseSender, servletResponse); verify(underTest).describe(request, facetResponse, null, "HTML"); verify(underTest).send(eq(request), any(Response.class), eq(servletResponse)); verify(servletResponse).setContentType(ContentTypes.TEXT_HTML); }
Example #30
Source File: ExceptionHandler.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private Response readOnly(final Context context, Exception e) { log.warn("Nexus Repository Manager is in read-only mode: {} {}: {}", context.getRequest().getAction(), context.getRequest().getPath(), e.toString()); return HttpResponses.serviceUnavailable("Nexus Repository Manager is in read-only mode"); }