Java Code Examples for org.sonatype.nexus.common.collect.NestedAttributesMap#set()

The following examples show how to use org.sonatype.nexus.common.collect.NestedAttributesMap#set() . 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: GoogleCloudBlobStoreITSupport.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
public BlobStoreConfiguration newConfiguration(final String name, final String bucketName,
                                               @Nullable final File credentialFile) {
  BlobStoreConfiguration configuration = blobStoreManager.newConfiguration();
  configuration.setName(name);
  configuration.setType("Google Cloud Storage");
  NestedAttributesMap configMap = configuration.attributes("google cloud storage");
  configMap.set("bucket", bucketName);
  configMap.set("location", "us-central1");
  if (credentialFile != null) {
    configMap.set("credential_file", credentialFile.getAbsolutePath());
  }
  NestedAttributesMap quotaMap = configuration.attributes(BlobStoreQuotaSupport.ROOT_KEY);
  quotaMap.set(BlobStoreQuotaSupport.TYPE_KEY, SpaceUsedQuota.ID);
  quotaMap.set(BlobStoreQuotaSupport.LIMIT_KEY, 512000L);

  return configuration;
}
 
Example 2
Source File: NpmMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void rewriteTarballUrlTest() {
  try {
    assertThat(BaseUrlHolder.isSet(), is(false));
    BaseUrlHolder.set("http://localhost:8080/");

    NestedAttributesMap packageRoot = new NestedAttributesMap("package", Maps.newHashMap());
    packageRoot.set("_id", "id");
    packageRoot.set("name", "package");
    packageRoot.child("versions").child("1.0").set("name", "package");
    packageRoot.child("versions").child("1.0").set("version", "1.0");
    packageRoot.child("versions").child("1.0").child("dist")
        .set("tarball", "http://example.com/path/package-1.0.tgz");
    packageRoot.child("versions").set("2.0", "incomplete");

    NpmMetadataUtils.rewriteTarballUrl("testRepo", packageRoot);

    String rewritten = packageRoot.child("versions").child("1.0").child("dist").get("tarball", String.class);
    assertThat(rewritten, equalTo("http://localhost:8080/repository/testRepo/package/-/package-1.0.tgz"));
  }
  finally {
    BaseUrlHolder.unset();
  }
}
 
Example 3
Source File: NpmMetadataUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Maintains the time fields of npm package root. Sets created time if it doesn't exist, updates the modified time.
 */
public static DateTime maintainTime(final NestedAttributesMap packageRoot) {
  final NestedAttributesMap time = packageRoot.child(TIME);
  final DateTime now = DateTime.now();
  final String nowString = NPM_TIMESTAMP_FORMAT.print(now);
  if (!time.contains(CREATED)) {
    time.set(CREATED, nowString);
  }
  time.set(MODIFIED, nowString);
  for (String version : packageRoot.child(VERSIONS).keys()) {
    if (!time.contains(version)) {
      time.set(version, nowString);
    }
  }
  return now;
}
 
Example 4
Source File: OrientNpmHostedFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalTouchBlob
protected void upgradeRevisionOnPackageRoot(final Asset packageRootAsset, final String revision) {
  StorageTx tx = UnitOfWork.currentTx();

  NpmPackageId packageId = NpmPackageId.parse(packageRootAsset.name());
  Asset asset = findPackageRootAsset(tx, tx.findBucket(getRepository()), packageId);

  if (asset == null) {
    log.error("Failed to update revision on package root. Asset for id '{}' didn't exist", packageId.id());
    return;
  }

  // if there is a transaction failure and we fail to upgrade the package root with _rev
  // then the user who fetched the package root will not be able to run a delete command
  try {
    NestedAttributesMap packageRoot = NpmFacetUtils.loadPackageRoot(tx, asset);
    packageRoot.set(META_REV, revision);
    savePackageRoot(UnitOfWork.currentTx(), packageRootAsset, packageRoot);
  }
  catch (IOException e) {
    log.warn("Failed to update revision in package root. Revision '{}' was not set" +
            " and might cause delete for that revision to fail for Asset {}",
        revision, packageRootAsset, e);
  }
}
 
Example 5
Source File: NpmMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void selectVersionByTarballNameTest() {
  NestedAttributesMap packageRoot = new NestedAttributesMap("package", Maps.newHashMap());
  packageRoot.set("_id", "id");
  packageRoot.set("name", "package");
  packageRoot.child("versions").child("1.0").set("name", "package");
  packageRoot.child("versions").child("1.0").set("version", "1.0");
  packageRoot.child("versions").child("1.0").child("dist").set("tarball", "http://example.com/path/package-1.0.tgz");
  packageRoot.child("versions").child("2.0").set("name", "package");
  packageRoot.child("versions").child("2.0").set("version", "2.0");
  packageRoot.child("versions").child("2.0").child("dist").set("tarball", "http://example.com/path/package-2.0.tgz");

  NestedAttributesMap v1 = NpmMetadataUtils.selectVersionByTarballName(packageRoot, "package-1.0.tgz");
  NestedAttributesMap v2 = NpmMetadataUtils.selectVersionByTarballName(packageRoot, "package-2.0.tgz");
  NestedAttributesMap v3 = NpmMetadataUtils.selectVersionByTarballName(packageRoot, "package-3.0.tgz");

  assertThat(v1.child("dist").get("tarball"), equalTo("http://example.com/path/package-1.0.tgz"));
  assertThat(v2.child("dist").get("tarball"), equalTo("http://example.com/path/package-2.0.tgz"));
  assertThat(v3, nullValue());
}
 
Example 6
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 7
Source File: NpmPublishParser.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void updateMaintainerList(final NestedAttributesMap versionToUpdate, final String currentUserId) {
  Object maintainersObject = versionToUpdate.get(MAINTAINERS_KEY);

  if (nonNull(maintainersObject)) {
    if(maintainersObject instanceof List) {
      List maintainers = (List) maintainersObject;

      Object maintainer = maintainers.get(0);
      if (maintainer instanceof Map) {
        updateMaintainerAsMap(maintainers, currentUserId);
      }
      else if (maintainer instanceof String) {
        updateMaintainerAsString(maintainers, currentUserId);
      }
    }
    else if (maintainersObject instanceof String) {
      versionToUpdate.set(MAINTAINERS_KEY, currentUserId);
    }
  }
}
 
Example 8
Source File: ComposerFormatAttributesExtractor.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extracts author contact information (except for the role) into a collection of strings.
 */
@VisibleForTesting
void extractAuthors(final Map<String, Object> contents,
                    final NestedAttributesMap formatAttributes)
{
  Object sourceValue = contents.get(AUTHORS);
  if (sourceValue instanceof Collection) {
    List<String> authors = new ArrayList<>();
    for (Object author : (Collection) sourceValue) {
      if (author instanceof Map) {
        List<String> parts = new ArrayList<>();
        extractAuthorPart((Map<String, Object>) author, parts, AUTHOR_NAME, "%s");
        extractAuthorPart((Map<String, Object>) author, parts, AUTHOR_EMAIL, "<%s>");
        extractAuthorPart((Map<String, Object>) author, parts, AUTHOR_HOMEPAGE, "(%s)");
        if (!parts.isEmpty()) {
          authors.add(String.join(" ", parts));
        }
      }
    }
    if (!authors.isEmpty()) {
      formatAttributes.set(P_AUTHORS, authors);
    }
  }
}
 
Example 9
Source File: NpmMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void mergeTest() {
  NestedAttributesMap recessive = new NestedAttributesMap("recessive", Maps.newHashMap());
  recessive.set("_id", "id");
  recessive.set("name", "recessive");
  recessive.child("versions").child("1.0").set("version", "1.0");
  recessive.child("versions").child("1.0").set("foo", "bar");
  recessive.child("versions").child("1.0").set("foo1", "bar1");
  recessive.child("versions").child("2.0").set("version", "2.0");
  recessive.child("versions").child("2.0").set("foo", "bar");
  NestedAttributesMap dominant = new NestedAttributesMap("dominant", Maps.newHashMap());
  dominant.set("_id", "id");
  dominant.set("name", "dominant");
  dominant.child("versions").child("1.0").set("version", "1.0");
  dominant.child("versions").child("1.0").set("foo", "baz");
  dominant.child("versions").child("1.0").set("foo2", "bar2");
  dominant.child("versions").child("1.1").set("version", "1.1");
  dominant.child("versions").child("1.1").set("foo", "bar");

  NestedAttributesMap result = NpmMetadataUtils.merge("theKey", ImmutableList.of(recessive, dominant));

  assertThat(result, not(equalTo(recessive)));
  assertThat(result.getKey(), Matchers.equalTo("theKey"));
  assertThat(result.backing(), not(hasEntry("_id", "id")));
  assertThat(result.backing(), hasEntry("name", "dominant"));
  assertThat(result.child("versions").child("1.0").backing(), hasEntry("foo", "baz"));
  assertThat(result.child("versions").child("1.0").backing(), not(hasEntry("foo1", "bar1")));
  assertThat(result.child("versions").child("1.0").backing(), hasEntry("foo2", "bar2"));
  assertThat(result.child("versions").child("1.1").backing(), hasEntry("foo", "bar"));
  assertThat(result.child("versions").child("2.0").backing(), hasEntry("foo", "bar"));
}
 
Example 10
Source File: SimpleApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static void setStorageAttributes(
    final Repository repository,
    final String blobStoreName,
    final Boolean strictContentTypeValidation,
    final String writePolicy)
{
  NestedAttributesMap storage = repository.getConfiguration().attributes(ConfigurationConstants.STORAGE);
  storage.set(ConfigurationConstants.BLOB_STORE_NAME, blobStoreName);
  if (strictContentTypeValidation != null) {
    storage.set(ConfigurationConstants.STRICT_CONTENT_TYPE_VALIDATION, strictContentTypeValidation);
  }
  if (writePolicy != null) {
    storage.set(ConfigurationConstants.WRITE_POLICY, writePolicy);
  }
}
 
Example 11
Source File: ProxyRepositoryApiRequestToConfigurationConverter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void convertProxy(final T request, final Configuration configuration) {
  ProxyAttributes proxy = request.getProxy();
  if (nonNull(proxy)) {
    NestedAttributesMap proxyConfiguration = configuration.attributes("proxy");
    proxyConfiguration.set("remoteUrl", proxy.getRemoteUrl());
    proxyConfiguration.set("contentMaxAge", proxy.getContentMaxAge());
    proxyConfiguration.set("metadataMaxAge", proxy.getMetadataMaxAge());
  }
}
 
Example 12
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the package root JSON content by reading up package root asset's blob and parsing it. It also decorates
 * the JSON document with some fields.
 */
public static NestedAttributesMap loadPackageRoot(final StorageTx tx,
                                                  final Asset packageRootAsset) throws IOException
{
  final Blob blob = tx.requireBlob(packageRootAsset.requireBlobRef());
  NestedAttributesMap metadata = NpmJsonUtils.parse(() -> blob.getInputStream());
  // add _id
  metadata.set(NpmMetadataUtils.META_ID, packageRootAsset.name());
  return metadata;
}
 
Example 13
Source File: SimpleApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAdapt_proxyRepository() throws Exception {
  Repository repository = createRepository(new ProxyType());

  NestedAttributesMap proxy = repository.getConfiguration().attributes("proxy");
  proxy.set("remoteUrl", "https://repo1.maven.org/maven2/");

  SimpleApiProxyRepository proxyRepository = (SimpleApiProxyRepository) underTest.adapt(repository);
  assertRepository(proxyRepository, "proxy", true);

  assertThat(proxyRepository.getProxy().getContentMaxAge(), is(1440));
  assertThat(proxyRepository.getProxy().getMetadataMaxAge(), is(1440));
  assertThat(proxyRepository.getProxy().getRemoteUrl(), is("https://repo1.maven.org/maven2/"));
  assertThat(proxyRepository.getHttpClient().getAutoBlock(), is(false));
  assertThat(proxyRepository.getHttpClient().getBlocked(), is(false));

  // Test specified values
  proxy.set("contentMaxAge", 1000.0); // specifically a double here to ensure exceptions not thrown
  proxy.set("metadataMaxAge", 1000.0); // specifically a double here to ensure exceptions not thrown

  NestedAttributesMap httpclient = repository.getConfiguration().attributes("httpclient");
  httpclient.set("autoBlock", true);
  httpclient.set("blocked", true);

  proxyRepository = (SimpleApiProxyRepository) underTest.adapt(repository);

  assertThat(proxyRepository.getProxy().getContentMaxAge(), is(1000));
  assertThat(proxyRepository.getProxy().getMetadataMaxAge(), is(1000));
  assertThat(proxyRepository.getHttpClient().getAutoBlock(), is(true));
  assertThat(proxyRepository.getHttpClient().getBlocked(), is(true));
}
 
Example 14
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static BiConsumer<String, Object> populateLatestVersion(final NestedAttributesMap merged) {
  return (k, v) -> {
    if (!merged.contains(k)) {
      merged.set(k, v);
    }
    else {
      final String newestVersion = extractNewestVersion.apply(merged.get(k, String.class), (String) v);
      merged.set(k, newestVersion);
    }
  };
}
 
Example 15
Source File: OrientNpmGroupFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private NestedAttributesMap createSimplePackageRoot(final String version) {
  NestedAttributesMap packageRoot = new NestedAttributesMap("simple", newHashMap());
  packageRoot.set("_id", "id");
  packageRoot.set("_rev", "1");

  NestedAttributesMap versionAttributes = packageRoot.child(VERSIONS).child(version);
  versionAttributes.set("version", version);
  versionAttributes.set("name", "package");
  versionAttributes.child("dist").set("tarball", "http://example.com/path/package-" + version + ".tgz");

  return packageRoot;
}
 
Example 16
Source File: GoogleCloudBlobstoreApiResource.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param config the configuration to be updated
 * @param blobstoreApiModel the source of new values
 */
void merge(BlobStoreConfiguration config, GoogleCloudBlobstoreApiModel blobstoreApiModel) {
  config.setName(blobstoreApiModel.getName());
  NestedAttributesMap bucket = config.attributes(CONFIG_KEY);
  bucket.set(BUCKET_KEY, blobstoreApiModel.getBucketName());
  bucket.set(LOCATION_KEY, blobstoreApiModel.getRegion());

  if (blobstoreApiModel.getSoftQuota() != null ) {
    NestedAttributesMap softQuota = config.attributes(ROOT_KEY);
    softQuota.set(TYPE_KEY, checkNotNull(blobstoreApiModel.getSoftQuota().getType()));
    final Long softQuotaLimit = checkNotNull(blobstoreApiModel.getSoftQuota().getLimit());
    softQuota.set(LIMIT_KEY, softQuotaLimit * ONE_MILLION);
  }
}
 
Example 17
Source File: NpmPublishParser.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void updateNpmUser(final NestedAttributesMap packageEntry, final String currentUserId) {
  if (packageEntry.contains(NPM_USER)) {
    NestedAttributesMap npmUser = packageEntry.child(NPM_USER);
    npmUser.set(NAME, currentUserId);
  }
}
 
Example 18
Source File: NpmMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void overlayTest() {
  NestedAttributesMap recessive = new NestedAttributesMap("recessive", Maps.newHashMap());
  recessive.set("_id", "id");
  recessive.set("name", "recessive");
  recessive.child("versions").child("1.0").set("version", "1.0");
  recessive.child("versions").child("1.0").set("foo", "bar");
  recessive.child("versions").child("1.0").set("foo1", "bar1");
  recessive.child("versions").child("1.0").child("author").set("url", "http://www.example.com");
  recessive.child("versions").child("1.0").child("dependencies").set("a", "1.0");
  recessive.child("versions").child("1.0").child("devDependencies").set("m", "2.0");
  recessive.child("versions").child("1.0").child("publishConfig").set("a", "m");
  recessive.child("versions").child("1.0").child("scripts").set("cmd1", "command1");

  NestedAttributesMap dominant = new NestedAttributesMap("dominant", Maps.newHashMap());
  dominant.set("_id", "id");
  dominant.set("name", "dominant");
  dominant.child("versions").child("1.0").set("version", "1.0");
  dominant.child("versions").child("1.0").set("foo", "baz");
  dominant.child("versions").child("1.0").child("author").set("email", "[email protected]");
  dominant.child("versions").child("1.0").child("dependencies").set("b", "2.0");
  dominant.child("versions").child("1.0").child("devDependencies").set("n", "3.0");
  dominant.child("versions").child("1.0").child("publishConfig").set("b", "n");
  dominant.child("versions").child("1.0").child("scripts").set("cmd2", "command2");

  NestedAttributesMap result = NpmMetadataUtils.overlay(recessive, dominant);

  assertThat(result, equalTo(recessive));
  assertThat(result.backing(), hasEntry("_id", "id"));
  assertThat(result.backing(), hasEntry("name", "dominant"));
  assertThat(result.child("versions").child("1.0").backing(), hasEntry("foo", "baz"));
  assertThat(result.child("versions").child("1.0").backing(), hasEntry("foo1", "bar1"));
  assertThat(result.child("versions").child("1.0").child("author").backing(),
      not(hasEntry("url", "http://www.example.com")));
  assertThat(result.child("versions").child("1.0").child("author").backing(), hasEntry("email", "[email protected]"));
  assertThat(result.child("versions").child("1.0").child("dependencies").backing(), not(hasEntry("a", "1.0")));
  assertThat(result.child("versions").child("1.0").child("dependencies").backing(), hasEntry("b", "2.0"));
  assertThat(result.child("versions").child("1.0").child("devDependencies").backing(), not(hasEntry("m", "2.0")));
  assertThat(result.child("versions").child("1.0").child("devDependencies").backing(), hasEntry("n", "3.0"));
  assertThat(result.child("versions").child("1.0").child("publishConfig").backing(), not(hasEntry("a", "m")));
  assertThat(result.child("versions").child("1.0").child("publishConfig").backing(), hasEntry("b", "n"));
  assertThat(result.child("versions").child("1.0").child("scripts").backing(), not(hasEntry("cmd1", "command1")));
  assertThat(result.child("versions").child("1.0").child("scripts").backing(), hasEntry("cmd2", "command2"));
}
 
Example 19
Source File: NpmFormatAttributesExtractor.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Sets a value into the map if the value is non-null.
 */
private void copyIfExists(final NestedAttributesMap attributesMap, final String key, @Nullable final Object value) {
  if (value != null) {
    attributesMap.set(key, value);
  }
}
 
Example 20
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns a new {@link InputStream} that returns an error object. Mostly useful for NPM Responses that have already
 * been written with a successful status (like a 200) but just before streaming out content found an issue preventing
 * the intended content to be streamed out.
 *
 * @return InputStream
 */
public static InputStream errorInputStream(final String message) {
  NestedAttributesMap errorObject = new NestedAttributesMap("error", newHashMap());
  errorObject.set("success", false);
  errorObject.set("error", "Failed to stream response due to: " + message);
  return new ByteArrayInputStream(NpmJsonUtils.bytes(errorObject));
}