Package org.sonatype.nexus.proxy.item

Examples of org.sonatype.nexus.proxy.item.StorageFileItem


      for (StorageItem item : items) {
        if (!(item instanceof StorageFileItem)) {
          break;
        }

        StorageFileItem fileItem = (StorageFileItem) item;

        try {
          existingMetadatas.add(parseMetadata(fileItem));
        }
        catch (IOException e) {
          log.warn(
              "IOException during parse of metadata UID=\"" + fileItem.getRepositoryItemUid().toString()
                  + "\", will be skipped from aggregation!", e);

          eventBus().post(
              newMetadataFailureEvent(fileItem,
                  "Invalid metadata served by repository. If repository is proxy, please check out what is it serving!"));
        }
        catch (MetadataException e) {
          log.warn(
              "Metadata exception during parse of metadata from UID=\""
                  + fileItem.getRepositoryItemUid().toString() + "\", will be skipped from aggregation!", e);

          eventBus().post(
              newMetadataFailureEvent(fileItem,
                  "Invalid metadata served by repository. If repository is proxy, please check out what is it serving!"));
        }
View Full Code Here


      throws LocalStorageException
  {
    // if the item is file, is M2 repository metadata and this repo is release-only or snapshot-only
    if (isCleanseRepositoryMetadata() && item instanceof StorageFileItem
        && M2ArtifactRecognizer.isMetadata(item.getPath())) {
      StorageFileItem mdFile = (StorageFileItem) item;
      ByteArrayInputStream backup = null;
      ByteArrayOutputStream backup1 = new ByteArrayOutputStream();
      try {
        // remote item is not reusable, and we usually cache remote stuff locally
        try (final InputStream orig = mdFile.getInputStream()) {
          StreamSupport.copy(orig, backup1, StreamSupport.BUFFER_SIZE);
        }
        backup = new ByteArrayInputStream(backup1.toByteArray());

        // Metadata is small, let's do it in memory
        MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
        InputStreamReader isr = new InputStreamReader(backup);
        Metadata imd = metadataReader.read(isr);

        // and fix it
        imd = cleanseMetadataForRepository(RepositoryPolicy.SNAPSHOT.equals(getRepositoryPolicy()), imd);

        // serialize and swap the new metadata
        MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(bos);
        metadataWriter.write(osw, imd);
        mdFile.setContentLocator(new ByteArrayContentLocator(bos.toByteArray(), mdFile.getMimeType()));
      }
      catch (Exception e) {
        log.error("Exception during repository metadata cleansing.", e);

        if (backup != null) {
          // get backup and continue operation
          backup.reset();
          mdFile.setContentLocator(new ByteArrayContentLocator(backup1.toByteArray(), mdFile.getMimeType()));
        }
      }
    }

    return super.doCacheItem(item);
View Full Code Here

      // the client's metadata version is known and it is not the latest one
      if (M2ArtifactRecognizer.isMetadata(request.getRequestPath()) && userSupportedVersion != null
          && !ModelVersionUtility.LATEST_MODEL_VERSION.equals(userSupportedVersion)) {
        // metadata checksum files are calculated and cached as side-effect
        // of doRetrieveMetadata.
        final StorageFileItem mdItem;
        if (M2ArtifactRecognizer.isChecksum(request.getRequestPath())) {
          String path = request.getRequestPath();
          if (request.getRequestPath().endsWith(".md5")) {
            path = path.substring(0, path.length() - 4);
          }
          else if (request.getRequestPath().endsWith(".sha1")) {
            path = path.substring(0, path.length() - 5);
          }
          // we have to keep original reqest's flags: localOnly and remoteOnly are strange ones, so
          // we do a hack here
          // second, since we initiate a request for different path within a context of this request,
          // we need to be careful about it
          ResourceStoreRequest mdRequest =
              new ResourceStoreRequest(path, request.isRequestLocalOnly(), request.isRequestRemoteOnly());
          mdRequest.getRequestContext().setParentContext(request.getRequestContext());

          mdItem = (StorageFileItem) super.retrieveItem(false, mdRequest);
        }
        else {
          mdItem = (StorageFileItem) super.doRetrieveItem(request);
        }

        try {
          Metadata metadata;
          try (final InputStream inputStream = mdItem.getInputStream()) {
            metadata = MetadataBuilder.read(inputStream);
          }

          Version requiredVersion = getClientSupportedVersion(userAgent);
          Version metadataVersion = ModelVersionUtility.getModelVersion(metadata);

          if (requiredVersion == null || requiredVersion.equals(metadataVersion)) {
            return super.doRetrieveItem(request);
          }

          ModelVersionUtility.setModelVersion(metadata, requiredVersion);

          ByteArrayOutputStream mdOutput = new ByteArrayOutputStream();

          MetadataBuilder.write(metadata, mdOutput);

          final byte[] content;
          if (M2ArtifactRecognizer.isChecksum(request.getRequestPath())) {
            String digest;
            if (request.getRequestPath().endsWith(".md5")) {
              digest = DigesterUtils.getMd5Digest(mdOutput.toByteArray());
            }
            else {
              digest = DigesterUtils.getSha1Digest(mdOutput.toByteArray());
            }
            content = (digest + '\n').getBytes("UTF-8");
          }
          else {
            content = mdOutput.toByteArray();
          }

          String mimeType =
              getMimeSupport().guessMimeTypeFromPath(getMimeRulesSource(), request.getRequestPath());
          ContentLocator contentLocator = new ByteArrayContentLocator(content, mimeType);

          DefaultStorageFileItem result =
              new DefaultStorageFileItem(this, request, true, false, contentLocator);
          result.setCreated(mdItem.getCreated());
          result.setModified(System.currentTimeMillis());
          return result;
        }
        catch (IOException e) {
          if (log.isDebugEnabled()) {
View Full Code Here

    for (MavenRepository mavenRepository : nexusWorkspace.getRepositories()) {
      gavRequest = new ArtifactStoreRequest(mavenRepository, gav, false, false);

      try {
        StorageFileItem artifactFile = mavenRepository.getArtifactStoreHelper().retrieveArtifact(gavRequest);

        // this will work with local FS storage only, since Aether wants java.io.File
        if (artifactFile.getRepositoryItemUid().getRepository()
            .getLocalStorage() instanceof DefaultFSLocalRepositoryStorage) {
          DefaultFSLocalRepositoryStorage ls =
              (DefaultFSLocalRepositoryStorage) artifactFile.getRepositoryItemUid().getRepository().getLocalStorage();

          return ls.getFileFromBase(artifactFile.getRepositoryItemUid().getRepository(), gavRequest);
        }
      }
      catch (Exception e) {
        // Something wrong happen for this repository, let's process the next one
      }
View Full Code Here

      // not returning null, will throw INFEx instead
      final Gav resolvedGav = helper.resolveArtifact(gavRequest);

      String repositoryPath = mavenRepository.getGavCalculator().gavToPath(resolvedGav);

      StorageFileItem resolvedFile = null;

      if (!isLocalOnly) {
        resolvedFile = helper.retrieveArtifact(gavRequest);
      }

      ArtifactResolveResource resource = new ArtifactResolveResource();

      resource.setPresentLocally(resolvedFile != null);

      if (resolvedFile != null) {
        resource.setSha1(resolvedFile.getRepositoryItemAttributes().get(DigestCalculatingInspector.DIGEST_SHA1_KEY));
      }

      resource.setGroupId(resolvedGav.getGroupId());

      resource.setArtifactId(resolvedGav.getArtifactId());
View Full Code Here

    try {
      MavenRepository mavenRepository = getMavenRepository(repositoryId);

      ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper();

      StorageFileItem file = helper.retrieveArtifactPom(gavRequest);

      try (InputStream pomContent = file.getInputStream();
           InputStreamReader ir = new InputStreamReader(pomContent)) {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        return reader.read(ir);
      }
    }
View Full Code Here

    try {
      MavenRepository mavenRepository = getMavenRepository(repositoryId);

      ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper();

      StorageFileItem file = helper.retrieveArtifact(gavRequest);

      if (redirectTo) {
        Reference fileReference =
            createRepositoryReference(request, file.getRepositoryItemUid().getRepository().getId(),
                file.getRepositoryItemUid().getPath());

        response.setLocationRef(fileReference);

        response.setStatus(Status.REDIRECTION_TEMPORARY);

        String redirectMessage =
            "If you are not automatically redirected use this url: " + fileReference.toString();
        return redirectMessage;
      }
      else {
        Representation result = new StorageFileItemRepresentation(file);

        result.setDownloadable(true);

        result.setDownloadName(file.getName());

        return result;
      }

    }
View Full Code Here

        TaskUtil.checkInterruption();

        ResourceStoreRequest req = new ResourceStoreRequest(PUBLISHING_PATH_PREFIX + "/" + name);

        try {
          StorageFileItem item = null;

          // XXX: ensure it goes to remote only and throws FileNotFoundException if nothing found on remote
          // kinda turn off transparent proxying for this method
          // We need to use ProxyRepository and get it's RemoteStorage stuff to completely
          // avoid "transparent" proxying, and even the slightest possibility to return
          // some stale file from cache to the updater.
          if (ISPROXY(repository) && REMOTEACCESSALLOWED(repository)) {
            item =
                (StorageFileItem) repository.getRemoteStorage()
                    .retrieveItem(repository, req, repository.getRemoteUrl());
          }
          else {
            throw new ItemNotFoundException(req, repository);
          }

          return item.getInputStream();
        }
        catch (ItemNotFoundException ex) {
          final FileNotFoundException fne = new FileNotFoundException(name + " (remote item not found)");
          fne.initCause(ex);
          throw fne;
View Full Code Here

  {
    ResourceStoreRequest request = new ResourceStoreRequest(path);

    FileContentLocator fc = new FileContentLocator(file, mimeSupport.guessMimeTypeFromPath(file.getName()));

    StorageFileItem item = new DefaultStorageFileItem(snapshots, request, true, true, fc);

    // deploy jar to storage
    snapshots.getLocalStorage().storeItem(snapshots, item);

    item = (StorageFileItem) snapshots.retrieveItem(request);
View Full Code Here

  @Override
  protected Object retrieveView(ResourceStoreRequest request, RepositoryItemUid itemUid, StorageItem item,
                                Request req)
      throws IOException
  {
    StorageFileItem fileItem = (StorageFileItem) item;

    Set<String> repositories = new LinkedHashSet<String>();

    // the artifact does exists on the repository it was found =D
    repositories.add(itemUid.getRepository().getId());

    final String checksum =
        fileItem == null ? null : fileItem.getRepositoryItemAttributes()
            .get(DigestCalculatingInspector.DIGEST_SHA1_KEY);
    if (checksum != null) {
      IteratorSearchResponse searchResponse = null;

      try {
        searchResponse =
            indexerManager.searchArtifactSha1ChecksumIterator(checksum, null, null, null, null, null);

        for (ArtifactInfo info : searchResponse) {
          repositories.add(info.repository);
        }
      }
      catch (NoSuchRepositoryException e) {
        // should never trigger this exception since I'm searching on all repositories
        getLogger().error(e.getMessage(), e);
      }
      finally {
        if (searchResponse != null) {
          searchResponse.close();
        }
      }
    }

    // hosted / cache check useful if the index is out to date or disable
    for (Repository repo : protectedRepositoryRegistry.getRepositories()) {
      // already found the artifact on this repo
      if (repositories.contains(repo.getId())) {
        continue;
      }

      final ResourceStoreRequest repoRequest =
          new ResourceStoreRequest(itemUid.getPath(), request.isRequestLocalOnly(),
              request.isRequestRemoteOnly());
      if (repo.getLocalStorage().containsItem(repo, repoRequest)) {
        try {
          StorageItem repoItem = repo.retrieveItem(repoRequest);
          if (checksum == null
              ||
              checksum.equals(repoItem.getRepositoryItemAttributes().get(DigestCalculatingInspector.DIGEST_SHA1_KEY))) {
            repositories.add(repo.getId());
          }
        }
        catch (AccessDeniedException e) {
          // that is fine, user doesn't have access
          continue;
        }
        catch (RepositoryNotAvailableException e) {
          // this could happen normally if a repository is not available, do not complain too loudly
          getLogger().trace("Repository not available; ignoring", e);
        }
        catch (Exception e) {
          getLogger().error(e.getMessage(), e);
        }
      }
    }

    ArtifactInfoResourceResponse result = new ArtifactInfoResourceResponse();

    ArtifactInfoResource resource = new ArtifactInfoResource();
    resource.setRepositoryId(itemUid.getRepository().getId());
    resource.setRepositoryName(itemUid.getRepository().getName());
    resource.setRepositoryPath(itemUid.getPath());
    resource.setRepositories(createRepositoriesUrl(repositories, req, itemUid.getPath()));
    resource.setPresentLocally(fileItem != null);

    if (fileItem != null) {
      resource.setMd5Hash(fileItem.getRepositoryItemAttributes().get(DigestCalculatingInspector.DIGEST_MD5_KEY));
      resource.setSha1Hash(checksum);
      resource.setLastChanged(fileItem.getModified());
      resource.setSize(fileItem.getLength());
      resource.setUploaded(fileItem.getCreated());
      resource.setUploader(fileItem.getRepositoryItemAttributes().get(AccessManager.REQUEST_USER));
      resource.setMimeType(fileItem.getMimeType());

      try {
        accessManager.decide(itemUid.getRepository(), request, Action.delete);
        resource.setCanDelete(true);
      }
View Full Code Here

TOP

Related Classes of org.sonatype.nexus.proxy.item.StorageFileItem

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.