/**
   * @param restResponse
   * @param servletContextUrl
   * @return
   */
  private String getGradleProperties(RestResponse restResponse, String servletContextUrl) {
    AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
    FilteredResourcesAddon filteredResourcesWebAddon =
        addonsManager.addonByType(FilteredResourcesAddon.class);

    java.util.Properties credentialProperties = new java.util.Properties();
    credentialProperties.setProperty(
        "auth.username", filteredResourcesWebAddon.getGeneratedSettingsUsernameTemplate());

    credentialProperties.setProperty(
        "auth.password",
        filteredResourcesWebAddon.getGeneratedSettingsUserCredentialsTemplate(false));

    credentialProperties.setProperty("auth.contextUrl", servletContextUrl);

    String content =
        replaceValuesAndGetTemplateValue(
            "/gradle.properties.template", credentialProperties, restResponse);
    try {
      String filtered =
          filteredResourcesWebAddon.filterResource(
              null,
              (org.artifactory.md.Properties) InfoFactoryHolder.get().createProperties(),
              new StringReader(content));
      return filtered;
    } catch (Exception e) {
      log.error("Unable to filter gradle build properties file: " + e.getMessage());
      restResponse.error(e.getMessage());
    }
    return content;
  }
 private boolean resourceIsExpirable(RepoResource resource, HttpRepo repo) {
   // If the file is expirable then the expirable mechanism is responsible to update the file and
   // the properties
   String path = resource.getRepoPath().getPath();
   CacheExpiry cacheExpiry = ContextHelper.get().beanForType(CacheExpiry.class);
   return cacheExpiry.isExpirable(repo.getLocalCacheRepo(), path);
 }
 /**
  * @return The last build number for snapshot version. 0 if maven-metadata not found for the path.
  */
 private int getLastBuildNumber(RepoPath repoPath) {
   int buildNumber = 0;
   try {
     // get the parent path which should contains the maven-metadata
     RepoPath parentRepoPath = repoPath.getParent();
     RepositoryService repoService = ContextHelper.get().getRepositoryService();
     RepoPathImpl mavenMetadataPath =
         new RepoPathImpl(parentRepoPath, MavenNaming.MAVEN_METADATA_NAME);
     if (repoService.exists(mavenMetadataPath)) {
       String mavenMetadataStr = repoService.getStringContent(mavenMetadataPath);
       Metadata metadata = MavenModelUtils.toMavenMetadata(mavenMetadataStr);
       Versioning versioning = metadata.getVersioning();
       if (versioning != null) {
         Snapshot snapshot = versioning.getSnapshot();
         if (snapshot != null) {
           buildNumber = snapshot.getBuildNumber();
         }
       }
     } else {
       // ok probably not found. just log
       log.debug("No maven metadata found for {}.", repoPath);
     }
   } catch (Exception e) {
     log.error("Cannot obtain build number from metadata.", e);
   }
   return buildNumber;
 }
 /**
  * @param snapshotDirectoryPath Path to a repository snapshot directory (eg, /a/path/1.0-SNAPSHOT)
  * @param buildNumber The file with build number to search for or 0 if doesn't matter
  * @param timestamp The file with timestamp to search for or null if doesn't matter
  * @param fileExtension The file type to search for. Use null for any type
  * @return The path of the first unique snapshot file with the input build number.
  */
 private String findSnapshotFile(
     RepoPath snapshotDirectoryPath, int buildNumber, String timestamp, String fileExtension) {
   log.debug(
       "Searching for unique snapshot file in {} with build number {} and timestamp {}",
       new Object[] {snapshotDirectoryPath, buildNumber, timestamp});
   RepositoryService repoService = ContextHelper.get().getRepositoryService();
   if (repoService.exists(snapshotDirectoryPath)) {
     List<String> children = repoService.getChildrenNames(snapshotDirectoryPath);
     for (String child : children) {
       if (MavenNaming.isUniqueSnapshotFileName(child)) {
         // now match against all the conditions
         boolean buildNumberMatches =
             buildNumber == 0
                 || buildNumber == MavenNaming.getUniqueSnapshotVersionBuildNumber(child);
         boolean timestampMatches =
             timestamp == null
                 || timestamp.equals(MavenNaming.getUniqueSnapshotVersionTimestamp(child));
         boolean typeMatches =
             fileExtension == null || fileExtension.equals(PathUtils.getExtension(child));
         if (buildNumberMatches && timestampMatches && typeMatches) {
           // passed all the search requirements...
           log.debug("Found unique snapshot: {}", child);
           return child;
         }
       }
     }
   }
   log.debug(
       "Unique snapshot file not found in {} for build number {}",
       snapshotDirectoryPath,
       buildNumber);
   return null;
 }
  /**
   * update storage summary with binaries repositories
   *
   * @param storageSummaryModel - storageSummary Model
   */
  private void updateFileStoreSummary(StorageSummaryImpl storageSummaryModel) {

    StorageService storageService = ContextHelper.get().beanForType(StorageService.class);

    FileStoreStorageSummary fileStoreSummaryInfo = storageService.getFileStoreStorageSummary();
    FileStoreSummary fileStoreSummary = new FileStoreSummary();
    fileStoreSummary.setStorageType(fileStoreSummaryInfo.getBinariesStorageType().toString());
    List<File> binariesFolders = fileStoreSummaryInfo.getBinariesFolders();
    String storageDirLabel = "Filesystem storage is not used";
    if (binariesFolders != null && !binariesFolders.isEmpty()) {
      storageDirLabel =
          String.join(
              ", ",
              binariesFolders.stream().map(File::getAbsolutePath).collect(Collectors.toList()));
    }
    fileStoreSummary.setStorageDirectory(storageDirLabel);
    fileStoreSummary.setTotalSpace(
        StorageUnit.toReadableString(fileStoreSummaryInfo.getTotalSpace()));
    fileStoreSummary.setUsedSpace(
        StorageUnit.toReadableString(fileStoreSummaryInfo.getUsedSpace())
            + " ("
            + NumberFormatter.formatPercentage(fileStoreSummaryInfo.getUsedSpaceFraction())
            + ")");
    fileStoreSummary.setFreeSpace(
        StorageUnit.toReadableString(fileStoreSummaryInfo.getFreeSpace())
            + " ("
            + NumberFormatter.formatPercentage(fileStoreSummaryInfo.getFreeSpaceFraction())
            + ")");
    storageSummaryModel.setFileStoreSummary(fileStoreSummary);
  }
 public boolean isFirstCallToSetupMC(ContainerRequest request) {
   MissionControlProperties missionControlProperties =
       ContextHelper.get().beanForType(MissionControlProperties.class);
   String token = missionControlProperties.getToken();
   String url = missionControlProperties.getUrl();
   if ((isBlank(url) || isBlank(token)) && request.getPath().endsWith("setupmc")) {
     return true;
   }
   return false;
 }
 @Override
 public Authentication getAnonymousAuthentication() {
   log.debug("Starting to generate Anonymous authentication");
   UserGroupService userGroupService = ContextHelper.get().beanForType(UserGroupService.class);
   UserInfo userInfo = userGroupService.findOrCreateExternalAuthUser(UserInfo.ANONYMOUS, true);
   MutableUserInfo mutableUserInfo = InfoFactoryHolder.get().copyUser(userInfo);
   mutableUserInfo.setRealm(MissionControlAuthenticationProvider.REALM);
   userInfo = mutableUserInfo;
   SimpleUser user = new SimpleUser(userInfo);
   // create new authentication response containing the user and it's authorities.
   log.debug("Finished to create Anonymous authentication");
   return new MissionControlAuthenticationToken(user, user.getAuthorities());
 }
示例#8
0
 /**
  * Returns true if the node that the path points to exists (Use with files only!)
  *
  * @param path repo path to check for existence
  */
 public static boolean exists(RepoPath path) {
   AqlSearchablePath aqlPath = new AqlSearchablePath(path);
   AqlApiItem aql =
       AqlApiItem.create()
           .filter(
               and(
                   AqlApiItem.repo().equal(aqlPath.getRepo()),
                   AqlApiItem.path().equal(aqlPath.getPath()),
                   AqlApiItem.name().equal(aqlPath.getFileName())));
   AqlEagerResult<AqlItem> results =
       ContextHelper.get().beanForType(AqlService.class).executeQueryEager(aql);
   return results != null && results.getResults() != null && results.getResults().size() > 0;
 }
  protected ObjectName createObjectName(String type, String mbeanProps) {
    String nameStr =
        MBEANS_DOMAIN_NAME
            + ":"
            + "instance="
            + ContextHelper.get().getContextId()
            + ", type="
            + type;
    if (StringUtils.isNotBlank(mbeanProps)) {
      nameStr += ",prop=" + mbeanProps;
    }

    try {
      return new ObjectName(nameStr);
    } catch (MalformedObjectNameException e) {
      throw new IllegalArgumentException("Failed to create object name for '" + nameStr + "'.", e);
    }
  }
示例#10
0
 private void doFilterInternal(
     HttpServletRequest request, HttpServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   final String servletPath = RequestUtils.getServletPathFromRequest(request);
   // add no cache header to web app request
   RequestUtils.addNoCacheToWebAppRequest(servletPath, response);
   String method = request.getMethod();
   if ((servletPath == null || "/".equals(servletPath) || servletPath.length() == 0)
       && "get".equalsIgnoreCase(method)) {
     // We were called with an empty path - redirect to the app main page
     response.sendRedirect(HttpUtils.ANGULAR_WEBAPP + "/");
     return;
   }
   // Reuse the authentication if it exists
   Authentication authentication = RequestUtils.getAuthentication(request);
   boolean isAuthenticated = authentication != null && authentication.isAuthenticated();
   // Make sure this is called only once
   boolean reAuthRequired = reAuthenticationRequired(request, authentication);
   if (reAuthRequired) {
     /**
      * A re-authentication is required but we might still have data that needs to be invalidated
      * (like the Wicket session)
      */
     Map<String, LogoutHandler> logoutHandlers =
         ContextHelper.get().beansForType(LogoutHandler.class);
     for (LogoutHandler logoutHandler : logoutHandlers.values()) {
       logoutHandler.logout(request, response, authentication);
     }
   }
   boolean authenticationRequired = !isAuthenticated || reAuthRequired;
   SecurityContext securityContext = SecurityContextHolder.getContext();
   if (authenticationRequired) {
     if (authFilter.acceptFilter(request)) {
       authenticateAndExecute(request, response, chain, securityContext);
     } else {
       useAnonymousIfPossible(request, response, chain, securityContext);
     }
   } else {
     log.debug("Using authentication {} from Http session.", authentication);
     useAuthentication(request, response, chain, authentication, securityContext);
   }
 }
 /**
  * update remote Properties
  *
  * @param resource - repo resource
  * @param properties - properties
  */
 private void updateRemoteProperties(RepoResource resource, Properties properties) {
   AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
   PropertiesAddon propertiesAddon = addonsManager.addonByType(PropertiesAddon.class);
   propertiesAddon.setProperties(resource.getRepoPath(), properties);
 }
  private String adjustChecksum(MavenSnapshotVersionAdapterContext context) {
    // find latest unique file matching the checksum coordinates
    RepositoryService repoService = ContextHelper.get().getRepositoryService();
    RepoPath repoPath = context.getRepoPath();
    RepoPath parentRepoPath = repoPath.getParent();
    RepoDescriptor repoDescriptor = repoService.repoDescriptorByKey(parentRepoPath.getRepoKey());
    RepoLayout repoLayout = repoDescriptor.getRepoLayout();

    String latestMatching = null;

    String originalChecksumRequestPath = repoPath.getPath();
    String originalRequestPathWithNoChecksum =
        PathUtils.stripExtension(originalChecksumRequestPath);

    if (repoService.exists(parentRepoPath)) {
      List<String> children = repoService.getChildrenNames(parentRepoPath);
      for (String child : children) {
        if (MavenNaming.isUniqueSnapshotFileName(child)) {

          ModuleInfo childModule =
              repoService.getItemModuleInfo(InternalRepoPathFactory.create(parentRepoPath, child));
          String fileRevisionIntegration = childModule.getFileIntegrationRevision();

          // Try to construct a new non-unique path as a descriptor
          String nonUniquePath =
              replaceIntegration(
                  ModuleInfoUtils.constructDescriptorPath(childModule, repoLayout, true),
                  fileRevisionIntegration);

          // If the path as a descriptor doesn't match, perhaps it's an artifact path
          if (!nonUniquePath.equals(originalRequestPathWithNoChecksum)) {
            // Try to construct a new non-unique path as an artifact
            nonUniquePath =
                replaceIntegration(
                    ModuleInfoUtils.constructArtifactPath(childModule, repoLayout),
                    fileRevisionIntegration);
          }

          if (nonUniquePath.equals(originalRequestPathWithNoChecksum)) {
            if (latestMatching == null
                || MavenNaming.getUniqueSnapshotVersionBuildNumber(latestMatching)
                    < MavenNaming.getUniqueSnapshotVersionBuildNumber(child)) {
              latestMatching = child;
            }
          }
        }
      }
    }

    // if latest not found, return invalid path which will fail and return a message to the client
    String timestamp =
        latestMatching != null
            ? MavenNaming.getUniqueSnapshotVersionTimestamp(latestMatching)
            : System.currentTimeMillis() + "";
    int buildNumber =
        latestMatching != null
            ? MavenNaming.getUniqueSnapshotVersionBuildNumber(latestMatching)
            : 0;

    // use the timestamp and build number from it. if not found return something that will fail?
    return buildUniqueSnapshotFileName(buildNumber, timestamp, context.getModuleInfo());
  }