org.sonatype.nexus.repository.view.payloads.BytesPayload Java Examples

The following examples show how to use org.sonatype.nexus.repository.view.payloads.BytesPayload. 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: 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 #2
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #3
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 #4
Source File: GolangHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional
@Override
public Content getList(final String module) {
  checkNotNull(module);

  StorageTx tx = UnitOfWork.currentTx();

  Iterable<Asset> assetsForModule = golangDataAccess.findAssetsForModule(tx, getRepository(), module);

  List<String> collection = StreamSupport.stream(assetsForModule.spliterator(), false)
      .filter(asset -> PACKAGE.name().equals(asset.formatAttributes().get(P_ASSET_KIND)))
      .map(Asset::name)
      .map(name -> name.split("/@v/")[1])
      .map(name -> name.replaceAll(".zip", ""))
      .collect(Collectors.toList());

  if (collection.isEmpty()) {
    return null;
  }

  String listOfVersions = String.join("\n", collection);

  return new Content(new BytesPayload(listOfVersions.getBytes(UTF_8), TEXT_PLAIN));
}
 
Example #5
Source File: OrientMetadataUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Writes passed in metadata as XML.
 */
public static void write(final Repository repository, final MavenPath mavenPath, final Metadata metadata)
    throws IOException
{
  MavenFacet mavenFacet = repository.facet(MavenFacet.class);
  final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  MavenModels.writeMetadata(buffer, metadata);
  mavenFacet.put(mavenPath, new BytesPayload(buffer.toByteArray(),
      MavenMimeRulesSource.METADATA_TYPE));
  final Map<HashAlgorithm, HashCode> hashCodes = mavenFacet.get(mavenPath).getAttributes()
      .require(Content.CONTENT_HASH_CODES_MAP, Content.T_CONTENT_HASH_CODES_MAP);
  checkState(hashCodes != null, "hashCodes");
  for (HashType hashType : HashType.values()) {
    MavenPath checksumPath = mavenPath.hash(hashType);
    HashCode hashCode = hashCodes.get(hashType.getHashAlgorithm());
    checkState(hashCode != null, "hashCode: type=%s", hashType);
    mavenFacet.put(checksumPath, new StringPayload(hashCode.toString(), Constants.CHECKSUM_CONTENT_TYPE));
  }
}
 
Example #6
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
public Content getPublicKey() throws IOException, PGPException {
  PGPSecretKey signKey = readSecretKey();
  PGPPublicKey publicKey = signKey.getPublicKey();
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try (BCPGOutputStream os = new BCPGOutputStream(new ArmoredOutputStream(buffer))) {
    publicKey.encode(os);
  }
  return new Content(new BytesPayload(buffer.toByteArray(), AptMimeTypes.PUBLICKEY));
}
 
Example #7
Source File: AptHostedFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
@TransactionalStoreMetadata
private void rebuildIndexesInTransaction(StorageTx tx, AssetChange... changes) throws IOException, PGPException {
  AptFacet aptFacet = getRepository().facet(AptFacet.class);
  AptSigningFacet signingFacet = getRepository().facet(AptSigningFacet.class);
  Bucket bucket = tx.findBucket(getRepository());

  StringBuilder sha256Builder = new StringBuilder();
  StringBuilder md5Builder = new StringBuilder();
  String releaseFile;
  try (CompressingTempFileStore store = buildPackageIndexes(tx, bucket, changes)) {
    for (Map.Entry<String, CompressingTempFileStore.FileMetadata> entry : store.getFiles().entrySet()) {
      Content plainContent = aptFacet.put(
          packageIndexName(entry.getKey(), ""),
          new StreamPayload(entry.getValue().plainSupplier(), entry.getValue().plainSize(), AptMimeTypes.TEXT));
      addSignatureItem(md5Builder, MD5, plainContent, packageRelativeIndexName(entry.getKey(), ""));
      addSignatureItem(sha256Builder, SHA256, plainContent, packageRelativeIndexName(entry.getKey(), ""));

      Content gzContent = aptFacet.put(
          packageIndexName(entry.getKey(), ".gz"),
          new StreamPayload(entry.getValue().gzSupplier(), entry.getValue().bzSize(), AptMimeTypes.GZIP));
      addSignatureItem(md5Builder, MD5, gzContent, packageRelativeIndexName(entry.getKey(), ".gz"));
      addSignatureItem(sha256Builder, SHA256, gzContent, packageRelativeIndexName(entry.getKey(), ".gz"));

      Content bzContent = aptFacet.put(
          packageIndexName(entry.getKey(), ".bz2"),
          new StreamPayload(entry.getValue().bzSupplier(), entry.getValue().bzSize(), AptMimeTypes.BZIP));
      addSignatureItem(md5Builder, MD5, bzContent, packageRelativeIndexName(entry.getKey(), ".bz2"));
      addSignatureItem(sha256Builder, SHA256, bzContent, packageRelativeIndexName(entry.getKey(), ".bz2"));
    }

    releaseFile = buildReleaseFile(aptFacet.getDistribution(), store.getFiles().keySet(), md5Builder.toString(), sha256Builder.toString());
  }

  aptFacet.put(releaseIndexName("Release"), new BytesPayload(releaseFile.getBytes(Charsets.UTF_8), AptMimeTypes.TEXT));
  byte[] inRelease = signingFacet.signInline(releaseFile);
  aptFacet.put(releaseIndexName("InRelease"), new BytesPayload(inRelease, AptMimeTypes.TEXT));
  byte[] releaseGpg = signingFacet.signExternal(releaseFile);
  aptFacet.put(releaseIndexName("Release.gpg"), new BytesPayload(releaseGpg, AptMimeTypes.SIGNATURE));
}
 
Example #8
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 #9
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 #10
Source File: RPackagesUtils.java    From nexus-repository-r with Eclipse Public License 1.0 5 votes vote down vote up
public static Content buildPackages(final Collection<Map<String, String>> entries) throws IOException {
  CompressorStreamFactory compressorStreamFactory = new CompressorStreamFactory();
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try (CompressorOutputStream cos = compressorStreamFactory.createCompressorOutputStream(GZIP, os)) {
    try (OutputStreamWriter writer = new OutputStreamWriter(cos, UTF_8)) {
      for (Map<String, String> entry : entries) {
        InternetHeaders headers = new InternetHeaders();
        headers.addHeader(P_PACKAGE, entry.get(P_PACKAGE));
        headers.addHeader(P_VERSION, entry.get(P_VERSION));
        headers.addHeader(P_DEPENDS, entry.get(P_DEPENDS));
        headers.addHeader(P_IMPORTS, entry.get(P_IMPORTS));
        headers.addHeader(P_SUGGESTS, entry.get(P_SUGGESTS));
        headers.addHeader(P_LINKINGTO, entry.get(P_LINKINGTO));
        headers.addHeader(P_LICENSE, entry.get(P_LICENSE));
        headers.addHeader(P_NEEDS_COMPILATION, entry.get(P_NEEDS_COMPILATION));
        Enumeration<String> headerLines = headers.getAllHeaderLines();
        while (headerLines.hasMoreElements()) {
          String line = headerLines.nextElement();
          writer.write(line, 0, line.length());
          writer.write('\n');
        }
        writer.write('\n');
      }
    }
  }
  catch ( CompressorException e ) {
    throw new RException(null, e);
  }
  return new Content(new BytesPayload(os.toByteArray(), "application/x-gzip"));
}
 
Example #11
Source File: OrientNpmGroupPackageHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
  underTest = new OrientNpmGroupPackageHandler();

  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(TokenMatcher.State.class, state);
  when(context.getAttributes()).thenReturn(attributesMap);
  when(context.getRepository()).thenReturn(group);
  when(context.getRequest()).thenReturn(request);

  when(group.getName()).thenReturn(OrientNpmGroupFacetTest.class.getSimpleName() + "-group");
  when(group.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(group.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(groupFacet.buildPackageRoot(anyMap(), eq(context)))
      .thenReturn(new Content(new BytesPayload("test".getBytes(), "")));

  when(viewFacet.dispatch(request, context))
      .thenReturn(new Response.Builder().status(success(OK)).build());

  when(proxy.facet(ViewFacet.class)).thenReturn(viewFacet);
  when(hosted.facet(ViewFacet.class)).thenReturn(viewFacet);

  when(request.getHeaders()).thenReturn(new Headers());
  when(request.getAttributes()).thenReturn(new AttributesMap());

  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);

  UnitOfWork.beginBatch(storageTx);
}
 
Example #12
Source File: OrientMavenGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Merges the metadata but doesn't cache it. Returns {@code null} if no usable response was in passed in map.
 *
 * @since 3.13
 */
@Override
@Nullable
public Content mergeWithoutCaching(final MavenPath mavenPath, final Map<Repository, Response> responses)
    throws IOException
{
  return merge(mavenPath, responses, Function.identity(), (in, contentType) -> {
    // load bytes in memory to make content re-usable; metadata shouldn't be too large
    // (don't include cache-related attributes since this content has not been cached)
    return new Content(new BytesPayload(toByteArray(in), contentType));
  });
}
 
Example #13
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public Content getPublicKey() throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  PGPSecretKey signKey = readSecretKey();
  PGPPublicKey publicKey = signKey.getPublicKey();
  try (BCPGOutputStream os = new BCPGOutputStream(new ArmoredOutputStream(buffer))) {
    publicKey.encode(os);
  }

  return new Content(new BytesPayload(buffer.toByteArray(), AptMimeTypes.PUBLICKEY));
}
 
Example #14
Source File: PartialPayloadTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private byte[] partial(final BytesPayload bytes, final Range<Long> closed) throws IOException {
  try (final PartialPayload partial = new PartialPayload(bytes, closed)) {
    return ByteStreams.toByteArray(partial.openInputStream());
  }
}
 
Example #15
Source File: TempContent.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private static Payload cachePayload(final Content remote) throws IOException {
  try (InputStream in = remote.openInputStream()) {
    return new BytesPayload(toByteArray(in), remote.getContentType());
  }
}
 
Example #16
Source File: AptHostedFacet.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@TransactionalStoreMetadata
public void rebuildIndexes(final List<AssetChange> changes) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  AptFacet aptFacet = getRepository().facet(AptFacet.class);
  AptSigningFacet signingFacet = getRepository().facet(AptSigningFacet.class);
  Bucket bucket = tx.findBucket(getRepository());

  StringBuilder sha256Builder = new StringBuilder();
  StringBuilder md5Builder = new StringBuilder();
  String releaseFile;
  try (CompressingTempFileStore store = buildPackageIndexes(tx, bucket, changes)) {
    for (Map.Entry<String, CompressingTempFileStore.FileMetadata> entry : store.getFiles().entrySet()) {
      Content plainContent = aptFacet.put(
          packageIndexName(entry.getKey(), ""),
          new StreamPayload(entry.getValue().plainSupplier(), entry.getValue().plainSize(), AptMimeTypes.TEXT));
      addSignatureItem(md5Builder, MD5, plainContent, packageRelativeIndexName(entry.getKey(), ""));
      addSignatureItem(sha256Builder, SHA256, plainContent, packageRelativeIndexName(entry.getKey(), ""));

      Content gzContent = aptFacet.put(
          packageIndexName(entry.getKey(), ".gz"),
          new StreamPayload(entry.getValue().gzSupplier(), entry.getValue().bzSize(), AptMimeTypes.GZIP));
      addSignatureItem(md5Builder, MD5, gzContent, packageRelativeIndexName(entry.getKey(), ".gz"));
      addSignatureItem(sha256Builder, SHA256, gzContent, packageRelativeIndexName(entry.getKey(), ".gz"));

      Content bzContent = aptFacet.put(
          packageIndexName(entry.getKey(), ".bz2"),
          new StreamPayload(entry.getValue().bzSupplier(), entry.getValue().bzSize(), AptMimeTypes.BZIP));
      addSignatureItem(md5Builder, MD5, bzContent, packageRelativeIndexName(entry.getKey(), ".bz2"));
      addSignatureItem(sha256Builder, SHA256, bzContent, packageRelativeIndexName(entry.getKey(), ".bz2"));
    }

    releaseFile = buildReleaseFile(aptFacet.getDistribution(), store.getFiles().keySet(), md5Builder.toString(),
        sha256Builder.toString());
  }

  aptFacet.put(releaseIndexName(RELEASE), new BytesPayload(releaseFile.getBytes(Charsets.UTF_8), AptMimeTypes.TEXT));
  byte[] inRelease = signingFacet.signInline(releaseFile);
  aptFacet.put(releaseIndexName(INRELEASE), new BytesPayload(inRelease, AptMimeTypes.TEXT));
  byte[] releaseGpg = signingFacet.signExternal(releaseFile);
  aptFacet.put(releaseIndexName(RELEASE_GPG), new BytesPayload(releaseGpg, AptMimeTypes.SIGNATURE));
}
 
Example #17
Source File: OrientNpmGroupFacetTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private Content toContent(final NestedAttributesMap packageRoot) {
  Content content = new Content(new BytesPayload(bytes(packageRoot), ContentTypes.APPLICATION_JSON));
  content.getAttributes().set(NestedAttributesMap.class, packageRoot);
  return content;
}
 
Example #18
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Converts the tags to a {@link Content} containing the tags as a json object
 */
public static Content distTagsToContent(final NestedAttributesMap distTags) throws IOException {
  final byte[] bytes = mapper.writeValueAsBytes(distTags.backing());
  return new Content(new BytesPayload(bytes, APPLICATION_JSON));
}