Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package io.fabric8.openshift.agent;
  
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
Updates the deployment in a Fabric managed OpenShift cartridge by either copying new deployment artifacts into directories in git directly or by updating the pom.xml in the maven build of the cartridges git repository to download the required deployment artifacts as part of the build (based on the flag isCopyFilesIntoGit().

For some common containers like Tomcat we also auto-detect special files like OPENSHIFT_CONFIG_CATALINA_PROPERTIES so that we can enable the use of a shared folder for deploying jars on a shared classpath across deployment units.

This allows, for example, shared features to be used across deployment units; such as, say, Apache Camel jars to be installed and shared across all web applications in the container.

 
 public class DeploymentUpdater {
     private static final transient Logger LOG = LoggerFactory.getLogger(DeploymentUpdater.class);
     public static final String OPENSHIFT_CONFIG_CATALINA_PROPERTIES = ".openshift/config/catalina.properties";
 
     private final DownloadManager downloadManager;
     private final Container container;
     private final String webAppDir;
     private final String deployDir;
     private boolean copyFilesIntoGit = false;
     private String repositories;
 
     public DeploymentUpdater(DownloadManager downloadManagerContainer containerString webAppDir,
                              String deployDir) {
         this. = downloadManager;
         this. = container;
         this. = webAppDir;
         this. = deployDir;
     }
 
     public void updateDeployment(Git gitFile baseDirCredentialsProvider credentialsthrows Exception {
         Set<Stringbundles = new LinkedHashSet<String>();
         Set<Featurefeatures = new LinkedHashSet<Feature>();
         Profile profile = .getOverlayProfile();
         bundles.addAll(profile.getBundles());
         AgentUtils.addFeatures(featuresprofile);
 
         if () {
             copyDeploymentsIntoGit(gitbaseDirbundlesfeatures);
         } else {
             addDeploymentsIntoPom(gitbaseDirprofilebundlesfeatures);
         }
 
         // now lets do a commit
         String message = "updating deployment";
         git.commit().setMessage(message).call();
 
         enableDeployDirectory(gitbaseDir);
 
         String branch = GitHelpers.currentBranch(git);
         .info("Pushing deployment changes to branch " + branch
                 + " credentials " + credentials + " for container " + .getId());
         try {
             Iterable<PushResultresults = git.push().setCredentialsProvider(credentials).setRefSpecs(new RefSpec(branch))
                     .setOutputStream(new LoggingOutputStream()).call();
 /*
             for (PushResult result : results) {
                 LOG.info(result.getMessages());
            }
*/
            .info("Pushed deployment changes to branch " + branch + " for container " + .getId());
        } catch (GitAPIException e) {
            .error("Failed to push deployment changes to branch " + branch + " for container " + .getId() + ". Reason: " + ee);
        }
    }

    
Lets download all the deployments and copy them into the webAppDir or deployDir in git
    protected void copyDeploymentsIntoGit(Git gitFile baseDirSet<StringbundlesSet<Featurefeaturesthrows Exception {
        List<StringwebAppFilesToDelete = filesToDelete(baseDir);
        List<StringdeployDirFilesToDelete = filesToDelete(baseDir);
        .debug("Deploying into container " + .getId() + " features " + features + " and bundles "
                + bundles);
        Map<StringFilefiles = AgentUtils.downloadBundles(featuresbundles,
                Collections.<String>emptySet());
        Set<Map.Entry<StringFile>> entries = files.entrySet();
        for (Map.Entry<StringFileentry : entries) {
            String name = entry.getKey();
            File file = entry.getValue();
            String destPath;
            String fileName = file.getName();
            if (name.startsWith("war:") || name.contains("/war/") || fileName.toLowerCase()
                    .endsWith(".war")) {
                destPath = ;
                webAppFilesToDelete.remove(fileName);
            } else {
                destPath = ;
                deployDirFilesToDelete.remove(fileName);
            }
            if (destPath != null) {
                File destDir = new File(baseDirdestPath);
                destDir.mkdirs();
                File destFile = new File(destDirfileName);
                .info("Copying file " + fileName + " to :  " + destFile.getCanonicalPath()
                        + " for container " + .getId());
                Files.copy(filedestFile);
                git.add().addFilepattern(destPath + "/" + fileName).call();
            }
            // now lets delete all the old remaining files from the directory
            deleteFiles(gitbaseDirwebAppFilesToDelete);
            deleteFiles(gitbaseDirdeployDirFilesToDelete);
        }
    }


    
Copy the various deployments into the pom.xml so that after the push, OpenShift will run the build and download the deployments into the webAppDir or deployDir
    protected void addDeploymentsIntoPom(Git gitFile baseDirProfile profileSet<StringbundlesSet<Featurefeaturesthrows SAXExceptionParserConfigurationExceptionXPathExpressionExceptionIOExceptionTransformerExceptionGitAPIException {
        Collection<Parserartifacts = AgentUtils.getProfileArtifacts(profilebundlesfeatures).values();
        if (artifacts.size() > 0) {
            OpenShiftPomDeployer pomDeployer = new OpenShiftPomDeployer(gitbaseDir);
            List<MavenRepositoryURLrepositories = parseMavenRepositoryURLs();
            pomDeployer.update(artifactsrepositories);
        }
    }
        List<MavenRepositoryURLrepositories = new ArrayList<MavenRepositoryURL>();
        String text = getRepositories();
        if (Strings.isNotBlank(text)) {
            StringTokenizer iter = new StringTokenizer(text);
            while (iter.hasMoreTokens()) {
                String url = iter.nextToken();
                if (url.endsWith(",")) {
                    url = url.substring(0, url.length() - 1);
                }
                MavenRepositoryURL mavenUrl = new MavenRepositoryURL(url);
                repositories.add(mavenUrl);
            }
        }
        return repositories;
    }


    
Checks things like Tomcat to see if the deployDir needs to be added to the shared class loader
    protected void enableDeployDirectory(Git gitFile baseDirthrows GitAPIException {
        File catalinaProperties = new File(baseDir);
        if (catalinaProperties.exists()) {
            // TODO make this configurable?
            String propertyName = "shared.loader";
            Properties properties = new Properties();
            String value = properties.getProperty(propertyName);
            if (Strings.isNotBlank(value) && (value.startsWith( + "/") || value.contains(":" +  + "/"))) {
                .info("Already has valid " + propertyName + " in " + catalinaProperties + " with value: " + value);
            } else {
                String newValue =  + "/*.jar";
                if (Strings.isNotBlank(value)) {
                    newValue = newValue + ":" + value;
                }
                // now lets replace the line which starts with propertyName;
                .info("Updating " + propertyName + " to " + newValue + " in " + catalinaProperties + " to enable the use of the shared deploy directory: " + );
                try {
                    int propertyNameLength = propertyName.length();
                    List<Stringlines = Files.readLines(catalinaProperties);
                    for (int i = 0, size = lines.size(); i < sizei++) {
                        String line = lines.get(i);
                        if (line.startsWith(propertyName) && line.length() > propertyNameLength) {
                            char ch = line.charAt(propertyNameLength);
                            if (Character.isWhitespace(ch) || ch == '=') {
                                String newLine = propertyName + "=" + newValue;
                                lines.set(inewLine);
                            }
                        }
                    }
                    Files.writeLines(catalinaPropertieslines);
                    git.add().addFilepattern().call();
                    String message = "enabled the deploy directory '" +  + "' to be on the shared class loader";
                    git.commit().setMessage(message).call();
                    .info("Committed changes to: " + catalinaProperties);
                } catch (IOException e) {
                    .warn("Failed to update " + catalinaProperties + " for container " + .getId()
                            + ". " + ee);
                }
            }
        }
    }

    
Returns a list of file names contained in the path from the given base directory or an empty list if the path is null or the directory does not exist
    protected List<StringfilesToDelete(File baseDirString path) {
        List<Stringanswer = new ArrayList<String>();
        if (path != null) {
            File dir = new File(baseDirpath);
            if (dir.exists() && dir.isDirectory()) {
                String[] list = dir.list();
                if (list != null) {
                    answer.addAll(Arrays.asList(list));
                }
            }
        }
        return answer;
    }
    protected void deleteFiles(Git gitFile baseDirString pathList<StringfileNames)
            throws GitAPIException {
        if (path != null) {
            for (String fileName : fileNames) {
                File file = new File(baseDirpath + "/" + fileName);
                if (file.exists()) {
                    .debug("Removing " + file + " for container " + .getId());
                    git.rm().addFilepattern(path + "/" + fileName).call();
                    file.delete();
                }
            }
        }
    }
    public String getWebAppDir() {
        return ;
    }
    public String getDeployDir() {
        return ;
    }
    public boolean isCopyFilesIntoGit() {
        return ;
    }
    public void setCopyFilesIntoGit(boolean copyFilesIntoGit) {
        this. = copyFilesIntoGit;
    }
    public String getRepositories() {
        return ;
    }
    public void setRepositories(String repositories) {
        this. = repositories;
    }
New to GrepCode? Check out our FAQ X