Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /* 
   * JBoss, Home of Professional Open Source 
   * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
   * as indicated by the @author tags. All rights reserved. 
   * See the copyright.txt in the distribution for a 
   * full listing of individual contributors.
   *
   * This copyrighted material is made available to anyone wishing to use, 
   * modify, copy, or redistribute it subject to the terms and conditions 
  * of the GNU Lesser General Public License, v. 2.1. 
  * This program is distributed in the hope that it will be useful, but WITHOUT A 
  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
  * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details. 
  * You should have received a copy of the GNU Lesser General Public License, 
  * v.2.1 along with this distribution; if not, write to the Free Software 
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
  * MA  02110-1301, USA.
  */
 package org.switchyard.tools.forge.plugin;
 
 import java.io.File;
 import java.util.List;
 
 
Responsible for common functionality and dependency management for SwitchYard projects. Each component should provide it's own facet implementation and reference the SwitchYard facet using @RequiresFacet.
 
 @Alias("switchyard")
 public class SwitchYardFacet extends AbstractFacet {
     // repository id of JBoss Nexus repository
     private static final String CONFIG_ATTR = "switchyard.config";
     
     private static final String SWITCHYARD_PLUGIN = 
         "org.switchyard:switchyard-plugin";
     
     // List of dependencies added to every SwitchYard application
     private static final String[] DEPENDENCIES = new String[] {
             "org.switchyard:switchyard-api",
             "org.switchyard:switchyard-plugin",
             "org.switchyard:switchyard-test"
     };
     
     // Used if we are dealing with an OpenShift application
     static final String OPEN_SHIFT_PROFILE = "openshift";
     static final String OPEN_SHIFT_TRANSFORM = "/org/switchyard/tools/forge/plugin/openshift.xsl";
     static final String OPEN_SHIFT_CONFIG = ".openshift/config/standalone.xml";
 
     @Inject
     private Shell _shell;
    
    
Create a new SwitchYard facet.
    public SwitchYardFacet() {
        super();
    }
    
    @Override
    public boolean install() {
        // Doing this in a try/finally to set and unset the context class loader
        final ClassLoader orig = Classes.setTCCL(getClass().getClassLoader());
        try {
            return performInstall();
        } finally {
            Classes.setTCCL(orig);
        }
    }
    
    
Save the current SwitchYard configuration model.
    public void saveConfig() {
    }

    
Retrieve the composite service config for the specified service name.

Parameters:
name composite service name
Returns:
composite service config fragment, or null if the service does not exist
        for (CompositeServiceModel service : getSwitchYardConfig().getComposite().getServices()) {
            if (service.getName().equals(name)) {
                return service;
            }
        }
        // no matching service
        return null;
    }
    
    
Retrieve the component service config for the specified service name.

Parameters:
name component service name
Returns:
component service config fragment, or null if the service does not exist
        for (ComponentModel component : getMergedSwitchYardConfig().getComposite().getComponents()) {
            for (ComponentServiceModel service : component.getServices()) {
                if (service.getName().equals(name)) {
                    return service;
                }
            }
        }
        // no matching service
        return null;
    }
    
    
Retrieve the composite reference config for the specified reference name.

Parameters:
name composite reference name
Returns:
composite reference config fragment, or null if the reference does not exist
        for (CompositeReferenceModel reference : getSwitchYardConfig().getComposite().getReferences()) {
            if (reference.getName().equals(name)) {
                return reference;
            }
        }
        // no matching reference
        return null;
    }
    
    
Retrieve the component reference config for the specified reference name.

Parameters:
name component reference name
Returns:
component reference config fragment, or null if the reference does not exist
        for (ComponentModel component : getMergedSwitchYardConfig().getComposite().getComponents()) {
            for (ComponentReferenceModel reference : component.getReferences()) {
                if (reference.getName().equals(name)) {
                    return reference;
                }
            }
        }
        // no matching reference
        return null;
    }
    
    
Returns the editable SwitchYard configuration for the current project. The configuration is loaded if a config property has not been associated with the project, so this method must be synchronized to prevent phantom config references due to concurrent loading.

Returns:
switchyard configuration
    public synchronized SwitchYardModel getSwitchYardConfig() {
        SwitchYardModel config = (SwitchYardModel
        if (config == null) {
            try {
                config = readSwitchYardConfig(getSwitchYardConfigFile());
                setSwitchYardConfig(config);
            } catch (java.io.IOException ioEx) {
                .println("Error while reading SwitchYard configuration: " + ioEx.getMessage());
            }
        }
        config.orderModelChildren();
        return config;
    }
    
    
Retrieves a merge of the user config and the generated configuration in target/classes/META-INF/switchyard.xml.

Returns:
merged switchyard configuration
        SwitchYardModel mergedConfig = null;
        FileResource<?> generatedFile = getGeneratedConfigFile();
        
        if (generatedFile != null && generatedFile.exists()) {
            try {
                SwitchYardModel generatedConfig = readSwitchYardConfig(generatedFile);
                mergedConfig = Models.merge(generatedConfiggetSwitchYardConfig());
            } catch (java.io.IOException ioEx) {
                .println("Error while reading SwitchYard configuration: " + ioEx.getMessage());
            }
        }
        
        // If we don't have a merged config at this point, then we should just
        // return the user configuration
        if (mergedConfig == null) {
            mergedConfig = getSwitchYardConfig();
        }
        return mergedConfig;
    }
    
    void writeSwitchYardConfig() {
        FileResource<?> configFile = getSwitchYardConfigFile();
        SwitchYardModel config = getSwitchYardConfig();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(configFile.getUnderlyingResourceObject());
            config.write(fos);
        } catch (java.io.IOException ioEx) {
            .println("Error while saving SwitchYard configuration: " + ioEx.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (java.io.IOException ioEx) {
                    return;
                }
            }
        }
    }
    
    private void addNexusRepository() {
        DependencyFacet deps = .getFacet(DependencyFacet.class);
    }
    
    private void addPluginRepository() {
        MavenPluginFacet plugins =  .getFacet(MavenPluginFacet.class);
    }
    
    private void tweakForOpenShift() throws Exception {
        // Check to see if this is an openshift app
        if (!(new File().exists())) {
            return;
        }
        
        // NEXUS repository definition is missing for OS apps
        addNexusRepository();
        
        // update standalone.xml to include switchyard bits
        
        // add a build section with the scanner plugins
        MavenCoreFacet mvn = .getFacet(MavenCoreFacet.class);
        Model pom = mvn.getPOM();
        List<Profileprofiles = new ArrayList<Profile>();
        profiles.add(buildOpenShiftProfile());
        pom.setProfiles(profiles);
        mvn.setPOM(pom);
    }
    
    
Adds SwitchYard scanners to the build section of a pom.

Parameters:
pom the pom to update
profile the profile to update; a null parameter will simply update the main <build> section.
Throws:
java.lang.Exception adding scanners failed
    private void addScannerPlugin(Model pomProfile profilethrows Exception {
        String version = .getFacet(DependencyFacet.class).getProperty();
        Dependency dep = DependencyBuilder.create( + ":" + version);
        org.apache.maven.model.Plugin plugin = new org.apache.maven.model.Plugin();
        plugin.setArtifactId(dep.getArtifactId());
        plugin.setGroupId(dep.getGroupId());
        plugin.setVersion("${" +  + "}");
        
        // This is terrible - find a better way to set the config
        String pluginConfig = 
            "<configuration>"
            + "<scannerClassNames>" 
            +   "<param>org.switchyard.component.bean.config.model.BeanSwitchYardScanner</param>"
            +   "<param>org.switchyard.component.camel.config.model.RouteScanner</param>"
            +   "<param>org.switchyard.component.bpm.config.model.BPMSwitchYardScanner</param>"
            +   "<param>org.switchyard.component.rules.config.model.RulesSwitchYardScanner</param>"
            +   "<param>org.switchyard.transform.config.model.TransformSwitchYardScanner</param>"
            +   "<param>org.switchyard.transform.config.model.ValidateSwitchYardScanner</param>"
            + "</scannerClassNames>"
            + "</configuration>";
        Xpp3Dom dom = Xpp3DomBuilder.build(new ByteArrayInputStream(pluginConfig.getBytes()),
        "UTF-8");
          
        List<PluginExecutionexecutions = plugin.getExecutions();
        PluginExecution execution = new PluginExecution();
        execution.addGoal("configure");
        execution.setConfiguration(dom);
        executions.add(execution);
        
        // add to the build section
        if (profile == null) {
            if (pom.getBuild() == null) {
                pom.setBuild(new org.apache.maven.model.Build());
            }
            pom.getBuild().getPlugins().add(plugin);
        } else {
            List<Pluginplugins = profile.getBuild().getPlugins();
            plugins.add(plugin);
            profile.getBuild().setPlugins(plugins);
        }
    }
    
    private boolean performInstall() {        
        try {
            tweakForOpenShift();
        } catch (Exception ex) {
            .println("Unable to configure application for OpenShift: " + ex.getMessage());
            return false;
        }
        
        // Update the project with version and dependency info
        setVersion(Versions.getSwitchYardVersion());
        installDependencies();
        addPluginRepository();
        
        String appName = .prompt("Application name (e.g. myApp)");
        
        try {
            MavenCoreFacet mvn = .getFacet(MavenCoreFacet.class);
            Model pom = mvn.getPOM();
            addScannerPlugin(pomnull);
            mvn.setPOM(pom);
            
            // Create the initial SwitchYard configuration
            V1SwitchYardModel syConfig = new V1SwitchYardModel();
            V1CompositeModel composite = new V1CompositeModel();
            composite.setName(appName);
            composite.setTargetNamespace("urn:switchyard:application:" + appName);
            syConfig.setComposite(composite);
            
            // Attach a reference to the current config to the current project
            setSwitchYardConfig(syConfig);
            // Save an initial version of the config
            writeSwitchYardConfig();
        } catch (Exception ex) {
            .println("Failed to install switchyard facet: " + ex.getMessage());
            return false;
        }
        return true;
    }
    
    // Creates a new OpenShift profile with correct SwitchYard
        Model pom = .getFacet(MavenCoreFacet.class).getPOM();
        Profile profile = new Profile();
        profile.setId();
        
        Build build = new Build();
        build.setFinalName(pom.getArtifactId());
        profile.setBuild(build);
        addScannerPlugin(pomprofile);
        Plugin jarPlugin = new Plugin();
        jarPlugin.setGroupId("org.apache.maven.plugins");
        jarPlugin.setArtifactId("maven-jar-plugin");
        jarPlugin.setVersion("2.3.1");
        String pluginConfig = 
                "<configuration>"
                + "<outputDirectory>deployments</outputDirectory>"
                + "</configuration>";
        Xpp3Dom dom = Xpp3DomBuilder.build(new ByteArrayInputStream(pluginConfig.getBytes()), "UTF-8");
        jarPlugin.setConfiguration(dom);
        build.addPlugin(jarPlugin);
        
        return profile;
    }
    
    // This method updates the config @ asConfigPath with required switchyard
    // subsystem details for OpenShift
    void addSwitchYardToASConfig(String asConfigPaththrows Exception {
        File orig = new File(asConfigPath);
        // create a backup
        if (!orig.exists()) {
            throw new Exception("standalone.xml not available at " + orig.getAbsolutePath());
        }
        File backup = new File(asConfigPath + ".orig");
        if (backup.exists()) {
            throw new Exception("backup standalone.xml already exists " + backup.getAbsolutePath());
        }
        if (!orig.renameTo(backup)) {
            throw new Exception("Failed to create backup standalone.xml " + backup.getAbsolutePath());
        }
        orig.createNewFile();
        
        // transform the original
        InputStream xslStream = null;
        try {
            Transformer t = TransformerFactory.newInstance().newTransformer(
                    new StreamSource(Classes.getResourceAsStream()));
            t.transform(new StreamSource(backup), new StreamResult(orig));   
        } finally {
            if (xslStream != null) {
                xslStream.close();
            }
        }
    }
    
    private SwitchYardModel readSwitchYardConfig(FileResource<?> filethrows java.io.IOException {
        return new ModelPuller<SwitchYardModel>().pull(file.getUnderlyingResourceObject());
    }
    
    
Any write activity to the project's config property should be synchronized.
    private synchronized void setSwitchYardConfig(SwitchYardModel config) {
    }
    
    private FileResource<?> getSwitchYardConfigFile() {
               "src" 
               + . + "main" 
               + . + "resources"
               + . + "META-INF");
       if (!metaInf.exists()) {
           metaInf.mkdirs();
       }
       return (FileResource<?>) metaInf.getChild("switchyard.xml");
    }
    
    private FileResource<?> getGeneratedConfigFile() {
        FileResource<?> generatedConfig = null;
                "target" 
                + . + "classes" 
                + . + "META-INF");
        
        if (metaInf != null && metaInf.exists()) {
            generatedConfig = (FileResource<?>) metaInf.getChild("switchyard.xml");
        }
        
        return generatedConfig;
    }
New to GrepCode? Check out our FAQ X