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

The following examples show how to use org.sonatype.nexus.repository.view.ContentTypes. 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: ConanProxyIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void retrieveDownloadUrls() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_DOWNLOAD_URLS);
  assertThat(status(response), is(HttpStatus.OK));
  HttpEntity entity = response.getEntity();
  String download_urls = EntityUtils.toString(entity);
  JsonObject obj = new JsonParser().parse(download_urls).getAsJsonObject();

  assertThat(obj.get(FILE_INFO).getAsString(), is(NXRM_CONAN_PROXY_REPO_PATH + PATH_INFO));
  assertThat(obj.get(FILE_PACKAGE).getAsString(), is(NXRM_CONAN_PROXY_REPO_PATH + PATH_TGZ_PACKAGE));
  assertThat(obj.get(FILE_MANIFEST).getAsString(), is(NXRM_CONAN_PROXY_REPO_PATH + PATH_MANIFEST));

  final Asset asset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS);
  assertThat(asset.format(), is(ConanFormat.NAME));
  assertThat(asset.name(), is(PATH_DOWNLOAD_URLS));
  assertThat(asset.contentType(), is(ContentTypes.TEXT_PLAIN));
}
 
Example #2
Source File: OrientPyPiGroupFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
protected AssetBlob updateAsset(final StorageTx tx, final Asset asset, final Content content) throws IOException {
  AttributesMap contentAttributes = Content.maintainLastModified(asset, content.getAttributes());
  Content.applyToAsset(asset, contentAttributes);

  InputStream inputStream = content.openInputStream();
  AssetBlob blob = tx.setBlob(asset,
      asset.name(),
      () -> inputStream,
      HASH_ALGORITHMS,
      null,
      ContentTypes.TEXT_HTML,
      true);

  tx.saveAsset(asset);

  return blob;
}
 
Example #3
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 #4
Source File: RawHostedIT.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void contentTypeDetectedFromContent() throws Exception {

  HttpEntity textEntity = new StringEntity("test");
  rawClient.put("path/to/content", textEntity);
  HttpResponse response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
  HttpClientUtils.closeQuietly(response);

  HttpEntity htmlEntity = new StringEntity("<html>...</html>");
  rawClient.put("path/to/content", htmlEntity);
  response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
  HttpClientUtils.closeQuietly(response);

  // turn off strict validation so we can test falling back to declared content-type
  Configuration hostedConfig = repositoryManager.get(HOSTED_REPO).getConfiguration().copy();
  hostedConfig.attributes(STORAGE).set(STRICT_CONTENT_TYPE_VALIDATION, false);
  repositoryManager.update(hostedConfig);

  HttpEntity jsonEntity = new StringEntity("", ContentType.APPLICATION_JSON);
  rawClient.put("path/to/content", jsonEntity);
  response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.APPLICATION_JSON));
  HttpClientUtils.closeQuietly(response);
}
 
Example #5
Source File: OrientPyPiGroupFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
public Content saveToCache(final String name, final Content content) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();

  Asset asset = getAsset(tx, name);
  AttributesMap contentAttributes = Content.maintainLastModified(asset, null);
  contentAttributes.set(CacheInfo.class, cacheController.current());
  Content.applyToAsset(asset, contentAttributes);

  AssetBlob blob = updateAsset(tx, asset, content);

  Content response = new Content(new BlobPayload(blob.getBlob(), ContentTypes.TEXT_HTML));
  Content.extractFromAsset(asset, HASH_ALGORITHMS, response.getAttributes());

  return response;
}
 
Example #6
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 #7
Source File: ConanProxyIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void retrieveDownloadUrlsFromNonPackageRoute() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_DOWNLOAD_URLS_WITHOUT_PACKAGES);
  assertThat(status(response), is(HttpStatus.OK));

  HttpEntity entity = response.getEntity();
  String download_urls = EntityUtils.toString(entity);
  JsonObject obj = new JsonParser().parse(download_urls).getAsJsonObject();

  assertThat(obj.get(FILE_MANIFEST).getAsString(),
      is("http://localhost:10000/repository/conan-test-proxy-online/conans/vthiery/jsonformoderncpp/3.7.0/stable/conanmanifest.txt"));
  assertThat(obj.get("conanfile.py").getAsString(),
      is("http://localhost:10000/repository/conan-test-proxy-online/conans/vthiery/jsonformoderncpp/3.7.0/stable/conanfile.py"));

  final Asset asset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS_WITHOUT_PACKAGES);
  assertThat(asset.format(), is(ConanFormat.NAME));
  assertThat(asset.name(), is(PATH_DOWNLOAD_URLS_WITHOUT_PACKAGES));
  assertThat(asset.contentType(), is(ContentTypes.TEXT_PLAIN));
}
 
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: ConanProxySearchIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void conanManifestUrlDownloadUrlIsNotExistButDigestIsExist() throws Exception {
  // init digest begin
  HttpResponse initDigestResponse = proxyClient.getHttpResponse(PATH_DIGEST);
  assertThat(status(initDigestResponse), is(HttpStatus.OK));
  // init digest end
  // do not test digest. It should be covered by proxy integration test

  HttpResponse response = proxyClient.getHttpResponse(PATH_MANIFEST);
  assertThat(status(response), is(HttpStatus.OK));

  // we should make sure that downloadUrls is not exist
  Asset downloadUrlsAsset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS);
  assertThat(downloadUrlsAsset, nullValue());

  Asset conanManifestAsset = findAsset(proxyRepo, PATH_MANIFEST);
  assertThat(conanManifestAsset.format(), is(ConanFormat.NAME));
  assertThat(conanManifestAsset.name(), is(PATH_MANIFEST));
  assertThat(conanManifestAsset.contentType(), is(ContentTypes.TEXT_PLAIN));
}
 
Example #10
Source File: ConanProxySearchIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void search() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_SEARCH);
  assertThat(status(response), is(HttpStatus.OK));

  HttpEntity entity = response.getEntity();
  String actualJson = EntityUtils.toString(entity);
  assertThat(actualJson, is(MOCK_SEARCH_REMOTE_RESPONSE));

  Header contentType = response.getEntity().getContentType();
  String mimeType = contentType.getValue();
  assertThat(mimeType, is(ContentTypes.APPLICATION_JSON));

  Asset conanManifestAsset = findAsset(proxyRepo, PATH_MANIFEST);
  assertThat(conanManifestAsset, nullValue());

  Asset downloadUrlsAsset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS);
  assertThat(downloadUrlsAsset, nullValue());

  Asset digestAsset = findAsset(proxyRepo, PATH_DIGEST);
  assertThat(digestAsset, nullValue());
}
 
Example #11
Source File: ConanProxySearchIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void patternSearch() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_PATTERN_SEARCH);
  assertThat(status(response), is(HttpStatus.OK));

  HttpEntity entity = response.getEntity();
  String actualJson = EntityUtils.toString(entity);
  assertThat(actualJson, is(MOCK_PATTERN_SEARCH_REMOTE_RESPONSE));

  Header contentType = response.getEntity().getContentType();
  String mimeType = contentType.getValue();
  assertThat(mimeType, is(ContentTypes.APPLICATION_JSON));

  Asset conanManifestAsset = findAsset(proxyRepo, PATH_MANIFEST);
  assertThat(conanManifestAsset, nullValue());

  Asset downloadUrlsAsset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS);
  assertThat(downloadUrlsAsset, nullValue());

  Asset digestAsset = findAsset(proxyRepo, PATH_DIGEST);
  assertThat(digestAsset, nullValue());
}
 
Example #12
Source File: MavenHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
protected int doRebuildArchetypeCatalog() throws IOException {
  final Path path = Files.createTempFile("hosted-archetype-catalog", "xml");
  int count = 0;
  try {
    StorageTx tx = UnitOfWork.currentTx();
    Iterable<Archetype> archetypes = getArchetypes(tx);
    ArchetypeCatalog hostedCatalog = new ArchetypeCatalog();
    Iterables.addAll(hostedCatalog.getArchetypes(), archetypes);
    count = hostedCatalog.getArchetypes().size();

    try (Content content = MavenFacetUtils.createTempContent(
        path,
        ContentTypes.APPLICATION_XML,
        (OutputStream outputStream) -> MavenModels.writeArchetypeCatalog(outputStream, hostedCatalog))) {
      MavenFacetUtils.putWithHashes(mavenFacet, archetypeCatalogMavenPath, content);
      log.trace("Rebuilt hosted archetype catalog for {} with {} archetype", getRepository().getName(), count);
    }
  }
  finally {
    Files.delete(path);
    
  }
  return count;
}
 
Example #13
Source File: ConanProxyFacet.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
private Content putMetadata(final Context context,
                            final Content content,
                            final AssetKind assetKind,
                            final ConanCoords coords)
    throws IOException
{
  StorageFacet storageFacet = facet(StorageFacet.class);
  try (TempBlob tempBlob = storageFacet.createTempBlob(content.openInputStream(), HASH_ALGORITHMS)) {

    if (assetKind == DOWNLOAD_URL || assetKind == DIGEST) {
      Content saveMetadata = doSaveMetadata(tempBlob, content, assetKind, coords);
      return new Content(
          new StringPayload(
              conanUrlIndexer.updateAbsoluteUrls(context, saveMetadata, getRepository()),
              ContentTypes.APPLICATION_JSON)
      );
    }
    return doSaveMetadata(tempBlob, content, assetKind, coords);
  }
}
 
Example #14
Source File: ConanContentValidator.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public String determineContentType(final boolean strictContentTypeValidation,
                                   final Supplier<InputStream> contentSupplier,
                                   @Nullable final MimeRulesSource mimeRulesSource,
                                   @Nullable final String contentName,
                                   @Nullable final String declaredContentType) throws IOException
{
  if (contentName != null) {
    if (contentName.endsWith(".tgz")) {
      return ContentTypes.APPLICATION_GZIP;
    }
    else if (contentName.endsWith("/conanfile.py")) {
      return X_PYTHON;
    }
    else if (ConanFacetUtils.isPackageSnapshot(contentName)) {
      return ContentTypes.APPLICATION_JSON;
    }
    else if (ConanFacetUtils.isDigest(contentName)) {
      return ContentTypes.APPLICATION_JSON;
    }
  }
  return defaultContentValidator.determineContentType(
      strictContentTypeValidation, contentSupplier, mimeRulesSource, contentName, declaredContentType
  );
}
 
Example #15
Source File: CompressedContentExtractorTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void fileExists() {
  StreamPayload payload = new StreamPayload(() -> getClass().getResourceAsStream(SONATYPE_ZIP),
      UNKNOWN_SIZE, ContentTypes.TEXT_PLAIN);

  assertThat(underTest.fileExists(payload, ANYPATH, GO_MOD), is(true));
}
 
Example #16
Source File: OrientPyPiGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
protected Content buildMergedIndexRoot(final String name, final Supplier<String> lazyMergeResult, boolean save)
    throws IOException
{
  try {
    String html = lazyMergeResult.get();
    Content newContent = new Content(new StringPayload(html, ContentTypes.TEXT_HTML));
    return save ? saveToCache(name, newContent) : newContent;
  }
  catch (UncheckedIOException e) { // NOSONAR: unchecked wrapper, we're only interested in its cause
    throw e.getCause();
  }
}
 
Example #17
Source File: NpmSearchIndexFacetCachingTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  when(repository.getName()).thenReturn("npm-test");
  when(repository.getFormat()).thenReturn(new NpmFormat());

  underTest = Guice.createInjector(new TransactionModule(), new AbstractModule()
  {
    @Override
    protected void configure() {
      bind(EventManager.class).toInstance(eventManager);
    }
  }).getInstance(NpmSearchIndexFacetCachingImpl.class);
  underTest.attach(repository);

  frozenException = mockOrientException(OModificationOperationProhibitedException.class);

  assetAttributes = new NestedAttributesMap(MetadataNodeEntityAdapter.P_ATTRIBUTES, new HashMap<>());
  assetAttributes.child(Asset.CHECKSUM).set(HashAlgorithm.SHA1.name(), "1234567890123456789012345678901234567890");

  doReturn(blobRef).when(asset).requireBlobRef();
  doReturn(NpmFormat.NAME).when(asset).format();
  doReturn(assetAttributes).when(asset).attributes();
  asset.contentType(ContentTypes.APPLICATION_JSON);

  when(assetBlob.getBlob()).thenReturn(blob);

  when(storageTx.findBucket(repository)).thenReturn(bucket);
  when(storageTx.requireBlob(blobRef)).thenReturn(blob);
  UnitOfWork.begin(() -> storageTx);
}
 
Example #18
Source File: ViewServlet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@VisibleForTesting
Response describe(final Request request, final Response response, final Exception exception, final String flags) {
  final Description description = new Description(ImmutableMap.<String, Object>of(
      "path", request.getPath(),
      "nexusUrl", BaseUrlHolder.get()
  ));
  if (exception != null) {
    descriptionHelper.describeException(description, exception);
  }
  descriptionHelper.describeRequest(description, request);
  if (response != null) {
    descriptionHelper.describeResponse(description, response);
  }

  DescribeType type = DescribeType.parse(flags);
  log.trace("Describe type: {}", type);
  switch (type) {
    case HTML: {
      String html = descriptionRenderer.renderHtml(description);
      return HttpResponses.ok(new StringPayload(html, ContentTypes.TEXT_HTML));
    }
    case JSON: {
      String json = descriptionRenderer.renderJson(description);
      return HttpResponses.ok(new StringPayload(json, ContentTypes.APPLICATION_JSON));
    }
    default:
      throw new RuntimeException("Invalid describe-type: " + type);
  }
}
 
Example #19
Source File: ViewServletTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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 #20
Source File: ViewServletTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void describeRequestReturnsDescriptionResponse_JSON() throws Exception {
  descriptionRequested("JSON");
  facetThrowsException(false);

  underTest.dispatchAndSend(request, facet, defaultResponseSender, servletResponse);

  verify(underTest).describe(request, facetResponse, null, "JSON");
  verify(underTest).send(eq(request), any(Response.class), eq(servletResponse));
  verify(servletResponse).setContentType(ContentTypes.APPLICATION_JSON);
}
 
Example #21
Source File: NpmSearchFacetHosted.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public Content searchV1(final Parameters parameters) throws IOException {
  String text = npmSearchParameterExtractor.extractText(parameters);
  int size = npmSearchParameterExtractor.extractSize(parameters);
  int from = npmSearchParameterExtractor.extractFrom(parameters);

  // npm search V1 endpoint currently returns an empty result set if no text is provided in the request
  NpmSearchResponse response;
  if (text.isEmpty()) {
    response = npmSearchResponseFactory.buildEmptyResponse();
  }
  else {
    QueryStringQueryBuilder query = QueryBuilders.queryStringQuery(text)
        .allowLeadingWildcard(true)
        .analyzeWildcard(true);
    TermsBuilder terms = AggregationBuilders.terms("name")
        .field("assets.attributes.npm.name")
        .size(v1SearchMaxResults)
        .subAggregation(AggregationBuilders.topHits("versions")
            .addSort(SortBuilders.fieldSort("assets.attributes.npm.search_normalized_version")
                .order(SortOrder.DESC))
            .setTrackScores(true)
            .setSize(1));

    SearchResponse searchResponse = searchQueryService.search(
        repositoryQuery(query).inRepositories(getRepository()), singletonList(terms));
    Aggregations aggregations = searchResponse.getAggregations();
    Terms nameTerms = aggregations.get("name");
    response = npmSearchResponseFactory.buildResponseForResults(nameTerms.getBuckets(), size, from);
  }

  String content = npmSearchResponseMapper.writeString(response);
  return new Content(new StringPayload(content, ContentTypes.APPLICATION_JSON));
}
 
Example #22
Source File: CompressedContentExtractorTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void fileDoesNotExist() {
  StreamPayload payload = new StreamPayload(() -> getClass().getResourceAsStream(SONATYPE_ZIP),
      UNKNOWN_SIZE, ContentTypes.TEXT_PLAIN);

  assertThat(underTest.fileExists(payload, ANYPATH, "does_not_exist.mod"), is(false));
}
 
Example #23
Source File: MavenIndexPublisher.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Maven2WritableResource locate(final String name) throws IOException {
  String contentType;
  if (name.endsWith(".properties")) {
    contentType = ContentTypes.TEXT_PLAIN;
  }
  else if (name.endsWith(".gz")) {
    contentType = ContentTypes.APPLICATION_GZIP;
  }
  else {
    throw new IllegalArgumentException("Unsupported MI index resource:" + name);
  }
  MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath("/.index/" + name);
  return new Maven2WritableResource(mavenPath, mavenFacet, contentType);
}
 
Example #24
Source File: NpmSearchIndexFacetHosted.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Builds the index by querying (read only access) the underlying CMA structures.
 */
@Nonnull
@Override
protected Content buildIndex(final StorageTx tx, final Path path) throws IOException {
  Bucket bucket = tx.findBucket(getRepository());
  try (final Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
    Set<NpmPackageId> packageIds = Sets.newHashSet(NpmFacetUtils.findAllPackageNames(tx, bucket));
    DateTime updated = new DateTime();
    JsonGenerator generator = NpmJsonUtils.mapper.getFactory().createGenerator(writer);
    generator.writeStartObject();
    generator.writeNumberField(NpmMetadataUtils.META_UPDATED, updated.getMillis());
    for (NpmPackageId packageId : packageIds) {
      final Asset packageRootAsset = NpmFacetUtils.findPackageRootAsset(tx, bucket, packageId);
      if (packageRootAsset != null) { // removed during iteration, skip
        NestedAttributesMap packageRoot = NpmFacetUtils.loadPackageRoot(tx, packageRootAsset);
        if (!packageRoot.isEmpty()) {
          NpmMetadataUtils.shrink(packageRoot);
          generator.writeObjectField(packageId.id(), packageRoot.backing());
        }
      }
    }
    generator.writeEndObject();
    generator.flush();
  }

  return new Content(new StreamPayload(
      new InputStreamSupplier()
      {
        @Nonnull
        @Override
        public InputStream get() throws IOException {
          return new BufferedInputStream(Files.newInputStream(path));
        }
      },
      Files.size(path),
      ContentTypes.APPLICATION_JSON)
  );
}
 
Example #25
Source File: ComposerJsonProcessor.java    From nexus-repository-composer with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Builds a packages.json file as a {@code Content} instance containing the actual JSON for the given providers.
 */
private Content buildPackagesJson(final Repository repository, final Set<String> names) throws IOException {
  Map<String, Object> packagesJson = new LinkedHashMap<>();
  packagesJson.put(PROVIDERS_URL_KEY, repository.getUrl() + PACKAGE_JSON_PATH);
  packagesJson.put(PROVIDERS_KEY, names.stream()
      .collect(Collectors.toMap((each) -> each, (each) -> singletonMap(SHA256_KEY, null))));
  return new Content(new StringPayload(mapper.writeValueAsString(packagesJson), ContentTypes.APPLICATION_JSON));
}
 
Example #26
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 #27
Source File: NpmResponses.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static Payload statusPayload(final boolean success, @Nullable final String error) {
  NestedAttributesMap errorObject = new NestedAttributesMap("error", Maps.<String, Object>newHashMap());
  errorObject.set("success", Boolean.valueOf(success));
  if (error != null) {
    errorObject.set("error", error);
  }
  return new BytesPayload(NpmJsonUtils.bytes(errorObject), ContentTypes.APPLICATION_JSON);
}
 
Example #28
Source File: RawHostedIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void contentTypeDetectedFromPath() throws Exception {
  HttpEntity testEntity = new ByteArrayEntity(new byte[0]);

  rawClient.put("path/to/content.txt", testEntity);
  HttpResponse response = rawClient.get("path/to/content.txt");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
  HttpClientUtils.closeQuietly(response);

  rawClient.put("path/to/content.html", testEntity);
  response = rawClient.get("path/to/content.html");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
  HttpClientUtils.closeQuietly(response);
}
 
Example #29
Source File: ConanProxyIT.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void retrieveManifestWhenRemoteOnline() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_MANIFEST);

  assertThat(status(response), is(HttpStatus.OK));

  final Asset asset = findAsset(proxyRepo, PATH_MANIFEST);
  assertThat(asset.format(), is(ConanFormat.NAME));
  assertThat(asset.name(), is(PATH_MANIFEST));
  assertThat(asset.contentType(), is(ContentTypes.TEXT_PLAIN));
}
 
Example #30
Source File: ConanProxyIT.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void retrieveInfoWhenRemoteOnline() throws Exception {
  // Conan client gets conanmanifest.txt file to examine conanifo.txt file hash
  HttpResponse response = proxyClient.getHttpResponse(PATH_MANIFEST);
  assertThat(status(response), is(HttpStatus.OK));
  // Conan client gets conanifo.txt file
  assertThat(status(proxyClient.getHttpResponse(PATH_INFO)), is(HttpStatus.OK));

  final Asset asset = findAsset(proxyRepo, PATH_INFO);
  assertThat(asset.format(), is(ConanFormat.NAME));
  assertThat(asset.name(), is(PATH_INFO));
  assertThat(asset.contentType(), is(ContentTypes.TEXT_PLAIN));
}