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

The following examples show how to use org.sonatype.nexus.common.collect.AttributesMap#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: ConanManifest.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extract all the md5 for conan files
 * @param conanManifestContentStream
 * @return Returns {AttributesMap} of file path keys to file md5 hash values
 */
public static AttributesMap parse(InputStream conanManifestContentStream) {
  AttributesMap attributesMap = new AttributesMap();
  try(BufferedReader reader = new BufferedReader(new InputStreamReader(conanManifestContentStream))) {
    String line;
    while ((line = reader.readLine()) != null) {
      String[] split = line.split(":");
      if (split.length == 2) {
        attributesMap.set(split[0].trim(), split[1].trim());
      }
    }
  } catch (IOException e) {
    LOGGER.warn("Unable to convertKeys manifest file");
  }
  return attributesMap;
}
 
Example 2
Source File: OrientPyPiGroupFacetTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(CONTENT_LAST_MODIFIED, DateTime.now());

  when(originalContent.getAttributes()).thenReturn(attributesMap);

  underTest = new OrientPyPiGroupFacet(repositoryManager, constraintViolationFactory, new GroupType()) {
    @Override
    public boolean isStale(@Nullable final Content content) {
      return false;
    }
  };

  responses = ImmutableMap.of(repository, response);
}
 
Example 3
Source File: OrientVersionPolicyHandlerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testScenario() throws Exception {
  when(context.getRequest()).thenReturn(request);
  when(request.getAction()).thenReturn(httpMethod);
  when(context.getRepository()).thenReturn(repository);
  when(repository.facet(MavenFacet.class)).thenReturn(mavenFacet);
  when(mavenFacet.getVersionPolicy()).thenReturn(policy);
  AttributesMap attributes = new AttributesMap();
  attributes.set(MavenPath.class, mavenPathParser.parsePath(path));
  when(context.getAttributes()).thenReturn(attributes);
  if (shouldProceed) {
    when(context.proceed()).thenReturn(proceeded);
  }

  Response response = underTest.handle(context);
  if (shouldProceed) {
    assertThat(response, is(proceeded));
  }
  else {
    assertThat(response, not(proceeded));
    assertThat(response.getStatus().getCode(), is(BAD_REQUEST));
    assertThat(response.getStatus().isSuccessful(), is(false));
  }
}
 
Example 4
Source File: Content.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extracts non-format specific content attributes into the passed in {@link AttributesMap} (usually originating from
 * {@link Content#getAttributes()}) from passed in {@link Asset} and format required hashes.
 */
public static void extractFromAsset(final Asset asset,
                                    final Iterable<HashAlgorithm> hashAlgorithms,
                                    final AttributesMap contentAttributes)
{
  checkNotNull(asset);
  checkNotNull(hashAlgorithms);
  final NestedAttributesMap assetAttributes = asset.attributes().child(CONTENT);
  final DateTime lastModified = toDateTime(assetAttributes.get(P_LAST_MODIFIED, Date.class));
  final String etag = assetAttributes.get(P_ETAG, String.class);

  final Map<HashAlgorithm, HashCode> checksums = asset.getChecksums(hashAlgorithms);

  contentAttributes.set(Asset.class, asset);
  contentAttributes.set(Content.CONTENT_LAST_MODIFIED, lastModified);
  contentAttributes.set(Content.CONTENT_ETAG, etag);
  contentAttributes.set(Content.CONTENT_HASH_CODES_MAP, checksums);
  contentAttributes.set(CacheInfo.class, CacheInfo.extractFromAsset(asset));
}
 
Example 5
Source File: AptProxyFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private Optional<SnapshotItem> fetchLatest(ContentSpecifier spec) throws IOException {
  AptFacet aptFacet = getRepository().facet(AptFacet.class);
  ProxyFacet proxyFacet = facet(ProxyFacet.class);
  HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
  HttpClient httpClient = httpClientFacet.getHttpClient();
  CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
  CacheInfo cacheInfo = cacheController.current();
  Content oldVersion = aptFacet.get(spec.path);

  URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
  HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);

  HttpResponse response = httpClient.execute(getRequest);
  StatusLine status = response.getStatusLine();

  if (status.getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
    AttributesMap contentAttrs = fetchedContent.getAttributes();
    contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
    contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
    contentAttrs.set(CacheInfo.class, cacheInfo);
    Content storedContent = getAptFacet().put(spec.path, fetchedContent);
    return Optional.of(new SnapshotItem(spec, storedContent));
  }

  try {
    if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
      checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri);
      doIndicateVerified(oldVersion, cacheInfo, spec.path);
      return Optional.of(new SnapshotItem(spec, oldVersion));
    }
    throwProxyExceptionForStatus(response);
  }
  finally {
    HttpClientUtils.closeQuietly(response);
  }

  return Optional.empty();
}
 
Example 6
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 7
Source File: OrientNpmGroupPackageHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void shouldReturnLastModifiedAttribute() throws Exception {
  NpmContent content = mock(NpmContent.class);
  AttributesMap attributes = new AttributesMap();
  attributes.set(CONTENT_LAST_MODIFIED, "01-01-2020");
  when(content.getAttributes()).thenReturn(attributes);
  when(groupFacet.getFromCache(eq(context))).thenReturn(content);

  Response response = underTest.doGet(context, dispatchedRepositories);

  assertThat(response.getAttributes().contains(CONTENT_LAST_MODIFIED), is(true));
  assertThat(response.getAttributes().get(CONTENT_LAST_MODIFIED), is("01-01-2020"));
}
 
Example 8
Source File: OrientPyPiHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void mayAddEtag(final AttributesMap attributesMap, final HashCode hashCode) {
  if (attributesMap.contains(CONTENT_ETAG)) {
    return;
  }

  if (hashCode != null) {
    attributesMap.set(CONTENT_ETAG, "{SHA1{" + hashCode + "}}");
  }
}
 
Example 9
Source File: LastDownloadedHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void configureHappyPath() throws Exception {
  when(asset.lastDownloaded()).thenReturn(empty());

  attributes = new AttributesMap();
  attributes.set(Asset.class, asset);

  when(context.proceed()).thenReturn(response);
  when(context.getRepository()).thenReturn(repository);
  when(context.getRequest()).thenReturn(request);
  when(request.getAction()).thenReturn(GET);
  when(response.getPayload()).thenReturn(payload);
  when(response.getStatus()).thenReturn(new Status(true, 200));
  when(payload.getAttributes()).thenReturn(attributes);
}
 
Example 10
Source File: FluentAttributesHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Apply a change request to the given {@link AttributesMap}.
 */
public static boolean applyAttributeChange(final AttributesMap attributes,
                                           final AttributeChange change,
                                           final String key,
                                           @Nullable final Object value)
{
  switch (change) {
    case SET:
      return !value.equals(attributes.set(key, checkNotNull(value)));
    case REMOVE:
      return attributes.remove(key) != null; // value is ignored
    case APPEND:
      attributes.compute(key, v -> append(v, checkNotNull(value)));
      return true;
    case PREPEND:
      attributes.compute(key, v -> prepend(v, checkNotNull(value)));
      return true;
    case OVERLAY:
      Object oldMap = attributes.get(key);
      Object newMap = overlay(oldMap, checkNotNull(value));
      if (!newMap.equals(oldMap)) {
        attributes.set(key, newMap);
        return true;
      }
      return false;
    default:
      throw new IllegalArgumentException("Unknown request");
  }
}
 
Example 11
Source File: MavenFacetUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adds {@link Content#CONTENT_ETAG} content attribute if not present. In case of hosted repositories, this is safe
 * and even good thing to do, as the content is hosted here only and NX is content authority.
 */
public static void mayAddETag(final AttributesMap attributesMap,
                              final Map<HashAlgorithm, HashCode> hashCodes) {
  if (attributesMap.contains(Content.CONTENT_ETAG)) {
    return;
  }
  HashCode sha1HashCode = hashCodes.get(HashAlgorithm.SHA1);
  if (sha1HashCode != null) {
    attributesMap.set(Content.CONTENT_ETAG, "{SHA1{" + sha1HashCode + "}}");
  }
}
 
Example 12
Source File: VersionPolicyHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void setupMocks() {
  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(MavenPath.class, mavenPath);
  when(request.getAction()).thenReturn(PUT);
  when(context.getAttributes()).thenReturn(attributesMap);
  when(context.getRepository()).thenReturn(repository);
  when(repository.facet(MavenContentFacet.class)).thenReturn(mavenContentFacet);
  when(mavenPath.main()).thenReturn(mavenPath);
  when(mavenPath.getCoordinates()).thenReturn(new Coordinates(false, "g", "a",
      "1", 1L, 1, "1", "test", ".jar", GPG));
}
 
Example 13
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Optional<SnapshotItem> fetchLatest(final ContentSpecifier spec) throws IOException {
  AptFacet aptFacet = getRepository().facet(AptFacet.class);
  ProxyFacet proxyFacet = facet(ProxyFacet.class);
  HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
  HttpClient httpClient = httpClientFacet.getHttpClient();
  CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
  CacheInfo cacheInfo = cacheController.current();
  Content oldVersion = aptFacet.get(spec.path);

  URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
  HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);

  HttpResponse response = httpClient.execute(getRequest);
  StatusLine status = response.getStatusLine();

  if (status.getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
    AttributesMap contentAttrs = fetchedContent.getAttributes();
    contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
    contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
    contentAttrs.set(CacheInfo.class, cacheInfo);
    Content storedContent = getAptFacet().put(spec.path, fetchedContent);
    return Optional.of(new SnapshotItem(spec, storedContent));
  }

  try {
    if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
      checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri);
      doIndicateVerified(oldVersion, cacheInfo, spec.path);
      return Optional.of(new SnapshotItem(spec, oldVersion));
    }
    throwProxyExceptionForStatus(response);
  }
  finally {
    HttpClientUtils.closeQuietly(response);
  }

  return Optional.empty();
}
 
Example 14
Source File: LastDownloadedHandlerTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void configureHappyPath() throws Exception {
  attributes = new AttributesMap();

  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(() -> tx);

  when(context.proceed()).thenReturn(response);
  when(context.getRepository()).thenReturn(repository);
  when(context.getRequest()).thenReturn(request);
  when(request.getAction()).thenReturn(GET);

  when(response.getPayload()).thenReturn(payload);

  when(payload.getAttributes()).thenReturn(attributes);

  when(response.getStatus()).thenReturn(new Status(true, 200));
  when(assetManager.maybeUpdateLastDownloaded(asset)).thenReturn(true);
  when(asset.getEntityMetadata()).thenReturn(entityMetadata);
  
  when(entityMetadata.getId()).thenReturn(id);
  
  when(tx.findAsset(any())).thenReturn(asset);

  attributes.set(Asset.class, asset);
}
 
Example 15
Source File: HostedHandlersTest.java    From nexus-repository-r with Eclipse Public License 1.0 4 votes vote down vote up
private void initialiseTestFixtures() {
  attributesMap = new AttributesMap();
  tokens = new HashMap<>();
  state = new TestState(tokens);
  attributesMap.set(State.class, state);
}
 
Example 16
Source File: GroupFacetImpl.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Maintains the latest cache information in the given content's attributes.
 */
protected void maintainCacheInfo(final AttributesMap attributesMap) {
  attributesMap.set(CacheInfo.class, cacheController.current());
}
 
Example 17
Source File: CocoapodsProxyRecipeTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setup() throws Exception
{
  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(LOCAL_ATTRIBUTE_PREFIX + "some_key", "some_value");
  when(context.getRepository()).thenReturn(repository);
  when(context.getAttributes()).thenReturn(attributesMap);
  when(request.getAction()).thenReturn(HttpMethods.GET);
  when(viewFacet.get()).thenReturn(cocoapodsViewFacet);
  when(format.getValue()).thenReturn(COCOAPODS_NAME);
  timingHandler = spy(new TimingHandler(null));

  underTest = new CocoapodsProxyRecipe(new ProxyType(), format);
  underTest.timingHandler = timingHandler;
  underTest.securityFacet = securityFacet;
  underTest.viewFacet = viewFacet;
  underTest.securityHandler = securityHandler;
  underTest.routingHandler = routingHandler;
  underTest.exceptionHandler = exceptionHandler;
  underTest.negativeCacheHandler = negativeCacheHandler;
  underTest.conditionalRequestHandler = conditionalRequestHandler;
  underTest.partialFetchHandler = partialFetchHandler;
  underTest.contentHeadersHandler = ontentHeadersHandler;
  underTest.unitOfWorkHandler = unitOfWorkHandler;
  underTest.lastDownloadedHandler = lastDownloadedHandler;
  underTest.proxyHandler = proxyHandler;
  underTest.httpClientFacet = httpClientFacet;
  underTest.negativeCacheFacet = negativeCacheFacet;
  underTest.proxyFacet = proxyFacet;
  underTest.cocoapodsFacet = cocoapodsFacet;
  underTest.storageFacet = storageFace;
  underTest.attributesFacet = attributesFacet;
  underTest.componentMaintenance = componentMaintenance;
  underTest.searchFacet = searchFacet;
  underTest.purgeUnusedFacet = purgeUnusedFacet;
  underTest.highAvailabilitySupportHandler = highAvailabilitySupportHandler;
  underTest.highAvailabilitySupportChecker = highAvailabilitySupportChecker;
  underTest.handlerContributor = handlerContributor;

  underTest.apply(repository);
  cocoapodsViewFacet.attach(repository);
}
 
Example 18
Source File: FluentAttributesHelperTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() {
  attributes = new AttributesMap();
  attributes.set("notalist", "text");
  attributes.set("notamap", "text");
}
 
Example 19
Source File: OrientNpmGroupFacetTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  BaseUrlHolder.set("http://localhost:8080/");

  setupNpmGroupFacet();
  underTest.attach(groupRepository);

  when(state.getTokens()).thenReturn(ImmutableMap.of(T_PACKAGE_NAME, "test"));

  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(TokenMatcher.State.class, state);

  when(context.getAttributes()).thenReturn(attributesMap);
  when(context.getRepository()).thenReturn(groupRepository);
  when(context.getRequest()).thenReturn(request);
  when(request.getPath()).thenReturn("/simple");

  when(groupRepository.getName()).thenReturn(OrientNpmGroupFacetTest.class.getSimpleName() + "-group");
  when(groupRepository.getFormat()).thenReturn(new NpmFormat());
  when(groupRepository.facet(ConfigurationFacet.class)).thenReturn(configurationFacet);
  when(groupRepository.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(packageRootAsset.formatAttributes()).thenReturn(new NestedAttributesMap("metadata", new HashMap<>()));
  when(packageRootAsset.attributes()).thenReturn(new NestedAttributesMap("content", new HashMap<>()));
  when(packageRootAsset.name(any())).thenReturn(packageRootAsset);
  when(packageRootAsset.requireBlobRef()).thenReturn(blobRef);

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

  when(blobStore.get(any())).thenReturn(blob);

  when(storageTx.createAsset(any(), any(NpmFormat.class))).thenReturn(packageRootAsset);
  when(storageTx.createBlob(any(), any(), any(), any(), any(), anyBoolean())).thenReturn(assetBlob);
  when(storageTx.requireBlob(blobRef)).thenReturn(blob);

  when(asset.blobRef()).thenReturn(blobRef);
  when(missingAssetBlobException.getAsset()).thenReturn(asset);

  underTest.doInit(configuration);

  UnitOfWork.beginBatch(storageTx);
}
 
Example 20
Source File: CondaProxyRecipeTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setup() throws Exception
{
  condaViewFacet = new ConfigurableViewFacet();
  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(LOCAL_ATTRIBUTE_PREFIX + "some_key", "some_value");
  when(format.getValue()).thenReturn(CONDA_NAME);
  when(viewFacet.get()).thenReturn(condaViewFacet);
  when(context.getRepository()).thenReturn(repository);
  when(context.getAttributes()).thenReturn(attributesMap);
  when(request.getAction()).thenReturn(HttpMethods.GET);
  when(securityHandler.handle(any())).thenAnswer(createPropagationAnswer());
  when(timingHandler.handle(any())).thenAnswer(createPropagationAnswer());
  when(browseUnsupportedHandler.getRoute()).thenReturn(
      new Route(mock(Matcher.class), ImmutableList.of(securityHandler, browseUnsupportedHandler)));

  proxyRecipe = new CondaProxyRecipe(new ProxyType(), format);

  proxyRecipe.setTimingHandler(timingHandler);
  proxyRecipe.setHighAvailabilitySupportHandler(highAvailabilitySupportHandler);
  proxyRecipe.setSecurityHandler(securityHandler);
  proxyRecipe.setExceptionHandler(exceptionHandler);
  proxyRecipe.setHandlerContributor(handlerContributor);
  proxyRecipe.setNegativeCacheHandler(negativeCacheHandler);
  proxyRecipe.setConditionalRequestHandler(conditionalRequestHandler);
  proxyRecipe.setPartialFetchHandler(partialFetchHandler);
  proxyRecipe.setContentHeadersHandler(contentHeadersHandler);
  proxyRecipe.setUnitOfWorkHandler(unitOfWorkHandler);
  proxyRecipe.setLastDownloadedHandler(lastDownloadedHandler);
  proxyRecipe.setProxyHandler(proxyHandler);
  proxyRecipe.setBrowseUnsupportedHandler(browseUnsupportedHandler);
  proxyRecipe.setRoutingHandler(routingRuleHandler);

  proxyRecipe.setSecurityFacet(securityFacet);
  proxyRecipe.setViewFacet(viewFacet);
  proxyRecipe.setHttpClientFacet(httpClientFacet);
  proxyRecipe.setNegativeCacheFacet(negativeCacheFacet);
  proxyRecipe.setProxyFacet(proxyFacet);
  proxyRecipe.setCondaFacet(condaFacet);
  proxyRecipe.setStorageFacet(storageFacet);
  proxyRecipe.setAttributesFacet(attributesFacet);
  proxyRecipe.setComponentMaintenanceFacet(componentMaintenanceFacet);
  proxyRecipe.setSearchFacet(searchFacet);
  proxyRecipe.setPurgeUnusedFacet(purgeUnusedFacet);
  proxyRecipe.setHighAvailabilitySupportChecker(highAvailabilitySupportChecker);

  proxyRecipe.apply(repository);
  condaViewFacet.attach(repository);
}