Source Code Cross Referenced for Generator.java in  » UML » MetaBoss » com » metaboss » sdlctools » frameworks » generation » pluggable » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » UML » MetaBoss » com.metaboss.sdlctools.frameworks.generation.pluggable 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        // THIS SOFTWARE IS PROVIDED BY SOFTARIS PTY.LTD. AND OTHER METABOSS
0002:        // CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
0003:        // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
0004:        // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOFTARIS PTY.LTD.
0005:        // OR OTHER METABOSS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
0006:        // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0007:        // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
0008:        // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0009:        // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
0010:        // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
0011:        // EVEN IF SOFTARIS PTY.LTD. OR OTHER METABOSS CONTRIBUTORS ARE ADVISED OF THE
0012:        // POSSIBILITY OF SUCH DAMAGE.
0013:        //
0014:        // Copyright 2000-2005 © Softaris Pty.Ltd. All Rights Reserved.
0015:        package com.metaboss.sdlctools.frameworks.generation.pluggable;
0016:
0017:        import java.io.File;
0018:        import java.io.FileOutputStream;
0019:        import java.io.FileWriter;
0020:        import java.io.IOException;
0021:        import java.io.InputStream;
0022:        import java.io.OutputStream;
0023:        import java.net.MalformedURLException;
0024:        import java.net.URL;
0025:        import java.net.URLConnection;
0026:        import java.util.ArrayList;
0027:        import java.util.Arrays;
0028:        import java.util.Collection;
0029:        import java.util.Iterator;
0030:        import java.util.List;
0031:        import java.util.Map;
0032:
0033:        import javax.jmi.reflect.RefBaseObject;
0034:        import javax.jmi.reflect.RefObject;
0035:        import javax.jmi.reflect.RefPackage;
0036:        import javax.naming.Context;
0037:        import javax.naming.InitialContext;
0038:        import javax.naming.NamingException;
0039:
0040:        import org.apache.commons.logging.Log;
0041:        import org.apache.commons.logging.LogFactory;
0042:
0043:        import com.metaboss.enterprise.bs.BSException;
0044:        import com.metaboss.enterprise.bs.BSIllegalArgumentException;
0045:        import com.metaboss.enterprise.bs.BSModelRepositoryInvocationException;
0046:        import com.metaboss.enterprise.bs.BSNamingAndDirectoryServiceInvocationException;
0047:        import com.metaboss.enterprise.bs.BSServiceProviderException;
0048:        import com.metaboss.enterprise.bs.BSUnexpectedProgramConditionException;
0049:        import com.metaboss.sdlctools.frameworks.generation.FormattingHelper;
0050:        import com.metaboss.sdlctools.frameworks.generation.StylesheetAccessor;
0051:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.CopyFileListStep;
0052:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.CopyFileStep;
0053:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.GenerateFileStep;
0054:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.GenerationStep;
0055:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.GenerationStepType;
0056:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.SourceFileListType;
0057:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.SourceFileType;
0058:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.TargetDirType;
0059:        import com.metaboss.sdlctools.frameworks.generation.pluggable.plandetails.TargetFileType;
0060:        import com.metaboss.sdlctools.models.ModelRepository;
0061:        import com.metaboss.sdlctools.models.ModelRepositoryException;
0062:        import com.metaboss.sdlctools.models.metabossmodel.MetaBossModelPackage;
0063:        import com.metaboss.sdlctools.models.metabossmodel.ModelElement;
0064:        import com.metaboss.sdlctools.services.jdktools.BSJamonTemplateProcessor;
0065:        import com.metaboss.sdlctools.services.jdktools.BSJavaTemplateProcessor;
0066:        import com.metaboss.sdlctools.services.jdktools.BSVelocityTemplateProcessor;
0067:        import com.metaboss.sdlctools.services.jdktools.MergeResult;
0068:        import com.metaboss.util.DirectoryUtils;
0069:        import com.metaboss.util.StreamUtils;
0070:        import com.metaboss.util.StringUtils;
0071:
0072:        /** Generator of developer's service simulator utilising XML files */
0073:        public class Generator {
0074:            // Commons Logging instance.
0075:            private static final Log sLogger = LogFactory
0076:                    .getLog(Generator.class);
0077:            private static boolean sClassInitialised = false;
0078:            private static Object sClassInitialisationSemaphore = new Object();
0079:            private static BSJamonTemplateProcessor sJamonTemplateProcessor = null;
0080:            private static BSVelocityTemplateProcessor sVelocityTemplateProcessor = null;
0081:            private static BSJavaTemplateProcessor sJavaTemplateProcessor = null;
0082:            private static StylesheetAccessor sStylesheetAccessor = new StylesheetAccessor();
0083:            private static FormattingHelper sFormattingHelper = new FormattingHelper();
0084:            private static Context sJndiContext = null;
0085:
0086:            // Pseudo class initialiser. Main feature that we can throw exception from here (unable to do that from native java class initialiser)
0087:            private static void initialiseClassIfNecessary() throws BSException {
0088:                if (!sClassInitialised) {
0089:                    synchronized (sClassInitialisationSemaphore) {
0090:                        if (!sClassInitialised) {
0091:                            try {
0092:                                sJndiContext = new InitialContext();
0093:                                sJamonTemplateProcessor = (BSJamonTemplateProcessor) sJndiContext
0094:                                        .lookup(BSJamonTemplateProcessor.COMPONENT_URL);
0095:                                sVelocityTemplateProcessor = (BSVelocityTemplateProcessor) sJndiContext
0096:                                        .lookup(BSVelocityTemplateProcessor.COMPONENT_URL);
0097:                                sJavaTemplateProcessor = (BSJavaTemplateProcessor) sJndiContext
0098:                                        .lookup(BSJavaTemplateProcessor.COMPONENT_URL);
0099:                            } catch (javax.naming.NamingException e) {
0100:                                throw new BSNamingAndDirectoryServiceInvocationException(
0101:                                        "Unable to initialise Generator", e);
0102:                            }
0103:                            sClassInitialised = true;
0104:                        }
0105:                    }
0106:                }
0107:            }
0108:
0109:            /** Performs generation steps for the default model and all contained elements only as specified in the given generation plan
0110:             * @param pDestinationDirectory - root directory to generate files to
0111:             * @param pGenerationPlan url of the xml file to be used as generation plan
0112:             * @param pTemplateContext context to pass to every generation template
0113:             * @return Number of generated files */
0114:            public static long doGenerationForDefaultModel(
0115:                    String pDestinationDirectory,
0116:                    URLConnection pGenerationPlan, Map pTemplateContext)
0117:                    throws BSException {
0118:                initialiseClassIfNecessary();
0119:                try {
0120:                    // Get the root element of the generation definition
0121:                    GenerationStep lGenerationStep = Parser
0122:                            .parseGenerationPlan(pGenerationPlan);
0123:                    URL lGenerationPlanURL = pGenerationPlan.getURL();
0124:                    // Get the model extent
0125:                    Context lContext = new InitialContext();
0126:                    ModelRepository lModelRepository = (ModelRepository) lContext
0127:                            .lookup(ModelRepository.COMPONENT_URL);
0128:                    RefPackage lModelExtent = lModelRepository
0129:                            .getDefaultModelExtent();
0130:                    String lStepLocation = pGenerationPlan.getURL()
0131:                            .toExternalForm()
0132:                            + "/GenerationStep";
0133:                    // Call the recursive GenerationStep processing method
0134:                    long lNumberOfFiles = doGenerationForGenerationStep(
0135:                            pDestinationDirectory,
0136:                            lModelRepository,
0137:                            Arrays.asList(new RefBaseObject[] { lModelExtent }),
0138:                            lGenerationStep, lGenerationPlanURL,
0139:                            pTemplateContext, lStepLocation);
0140:                    return lNumberOfFiles > 0 ? lNumberOfFiles : 0;
0141:                } catch (NamingException e) {
0142:                    throw new BSNamingAndDirectoryServiceInvocationException(
0143:                            "Unable to lookup model repository", e);
0144:                } catch (ModelRepositoryException e) {
0145:                    throw new BSModelRepositoryInvocationException(
0146:                            "Caught exception while doing generation from the default model.",
0147:                            e);
0148:                }
0149:            }
0150:
0151:            /** Performs generation steps for the given list of elements and all contained elements only as specified in the given generation plan
0152:             * @param pDestinationDirectory - root directory to generate files to
0153:             * @param pGenerationPlan url of the xml file to be used as generation plan
0154:             * @param pRootModelElements the elements to generate the stuff for
0155:             * @param pTemplateContext context to pass to every generation template
0156:             * @return Number of generated files */
0157:            public static long doGenerationForElements(
0158:                    String pDestinationDirectory,
0159:                    URLConnection pGenerationPlan,
0160:                    Collection pRootModelElements, Map pTemplateContext)
0161:                    throws BSException {
0162:                initialiseClassIfNecessary();
0163:                try {
0164:                    // Get the root element of the generation definition
0165:                    GenerationStep lGenerationStep = Parser
0166:                            .parseGenerationPlan(pGenerationPlan);
0167:                    URL lGenerationPlanURL = pGenerationPlan.getURL();
0168:                    // Get the model extent
0169:                    Context lContext = new InitialContext();
0170:                    ModelRepository lModelRepository = (ModelRepository) lContext
0171:                            .lookup(ModelRepository.COMPONENT_URL);
0172:                    String lStepLocation = pGenerationPlan.getURL()
0173:                            .toExternalForm()
0174:                            + "/GenerationStep";
0175:                    // Call the recursive GenerationStep processing method
0176:                    long lNumberOfFiles = doGenerationForGenerationStep(
0177:                            pDestinationDirectory, lModelRepository,
0178:                            pRootModelElements, lGenerationStep,
0179:                            lGenerationPlanURL, pTemplateContext, lStepLocation);
0180:                    return lNumberOfFiles > 0 ? lNumberOfFiles : 0;
0181:                } catch (NamingException e) {
0182:                    throw new BSNamingAndDirectoryServiceInvocationException(
0183:                            "Unable to lookup model repository", e);
0184:                }
0185:            }
0186:
0187:            /** Performs generation steps for the given metaboss model element and all contained elements only as specified in the given generation plan
0188:             * @param pDestinationDirectory - root directory to generate files to
0189:             * @param pModelName - the name of the model to use in generation.
0190:             * @param pGenerationPlan url of the xml file to be used as generation plan
0191:             * @param pMetaBossModelElementRef the reference to the MetaBoss model element
0192:             * @param pTemplateContext context to pass to every generation template
0193:             * @return Number of generated files */
0194:            public static long doGenerationForDefaultMetaBossModelElement(
0195:                    String pDestinationDirectory,
0196:                    URLConnection pGenerationPlan,
0197:                    String pMetaBossModelElementRef, Map pTemplateContext)
0198:                    throws BSException {
0199:                initialiseClassIfNecessary();
0200:                try {
0201:                    // Get the root element of the generation definition
0202:                    GenerationStep lGenerationStep = Parser
0203:                            .parseGenerationPlan(pGenerationPlan);
0204:                    URL lGenerationPlanURL = pGenerationPlan.getURL();
0205:                    // Get the model extent
0206:                    Context lContext = new InitialContext();
0207:                    ModelRepository lModelRepository = (ModelRepository) lContext
0208:                            .lookup(ModelRepository.COMPONENT_URL);
0209:                    if (!lModelRepository.getDefaultModelMetaModelName()
0210:                            .equals(ModelRepository.METAMODEL_NAME_METABOSS))
0211:                        throw new BSIllegalArgumentException(
0212:                                "The default model in the Model Repository is not an instance of the MetaBoss MetaModel. Operation can not proceed.");
0213:                    MetaBossModelPackage lMetaBossModelPackage = (MetaBossModelPackage) lModelRepository
0214:                            .getDefaultModelExtent();
0215:                    ModelElement lRootModelElement = lMetaBossModelPackage
0216:                            .getModelElement().getByRef(
0217:                                    pMetaBossModelElementRef);
0218:                    String lStepLocation = pGenerationPlan.getURL()
0219:                            .toExternalForm()
0220:                            + "/GenerationStep";
0221:                    // Call the recursive GenerationStep processing method
0222:                    long lNumberOfFiles = doGenerationForGenerationStep(
0223:                            pDestinationDirectory,
0224:                            lModelRepository,
0225:                            Arrays
0226:                                    .asList(new RefBaseObject[] { lRootModelElement }),
0227:                            lGenerationStep, lGenerationPlanURL,
0228:                            pTemplateContext, lStepLocation);
0229:                    return lNumberOfFiles > 0 ? lNumberOfFiles : 0;
0230:                } catch (NamingException e) {
0231:                    throw new BSNamingAndDirectoryServiceInvocationException(
0232:                            "Unable to lookup model repository", e);
0233:                } catch (ModelRepositoryException e) {
0234:                    throw new BSModelRepositoryInvocationException(
0235:                            "Caught exception while doing generation from the default model.",
0236:                            e);
0237:                }
0238:            }
0239:
0240:            /** Performs generation steps for the given model and all contained elements only as specified in the given generation plan
0241:             * @param pDestinationDirectory - root directory to generate files to
0242:             * @param pModelName - the name of the model to use in generation.
0243:             * @param pGenerationPlan url of the xml file to be used as generation plan
0244:             * @param pTemplateContext context to pass to every generation template
0245:             * @return Number of generated files */
0246:            public static long doGenerationForModel(
0247:                    String pDestinationDirectory, String pModelName,
0248:                    URLConnection pGenerationPlan, Map pTemplateContext)
0249:                    throws BSException {
0250:                initialiseClassIfNecessary();
0251:                try {
0252:                    // Get the root element of the generation definition
0253:                    GenerationStep lGenerationStep = Parser
0254:                            .parseGenerationPlan(pGenerationPlan);
0255:                    URL lGenerationPlanURL = pGenerationPlan.getURL();
0256:                    // Get the model extent
0257:                    Context lContext = new InitialContext();
0258:                    ModelRepository lModelRepository = (ModelRepository) lContext
0259:                            .lookup(ModelRepository.COMPONENT_URL);
0260:                    RefPackage lModelExtent = lModelRepository
0261:                            .getModelExtent(pModelName);
0262:                    String lStepLocation = pGenerationPlan.getURL()
0263:                            .toExternalForm()
0264:                            + "/GenerationStep";
0265:                    // Call the recursive GenerationStep processing method
0266:                    long lNumberOfFiles = doGenerationForGenerationStep(
0267:                            pDestinationDirectory,
0268:                            lModelRepository,
0269:                            Arrays.asList(new RefBaseObject[] { lModelExtent }),
0270:                            lGenerationStep, lGenerationPlanURL,
0271:                            pTemplateContext, lStepLocation);
0272:                    return lNumberOfFiles > 0 ? lNumberOfFiles : 0;
0273:                } catch (NamingException e) {
0274:                    throw new BSNamingAndDirectoryServiceInvocationException(
0275:                            "Unable to lookup model repository", e);
0276:                } catch (ModelRepositoryException e) {
0277:                    throw new BSModelRepositoryInvocationException(
0278:                            "Caught exception while doing generation from the '"
0279:                                    + pModelName + "' model.", e);
0280:                }
0281:            }
0282:
0283:            /** Recursive method which perfroms generation for a single GenerationStep element and all its
0284:             * subelements
0285:             * @param pDestinationDirectory - root directory to generate files to
0286:             * @param pModelRepository - the repository to use during generation
0287:             * @param pModelContextObjects - the list with RefbaseObjects we need to consider on this step
0288:             * @param pGenerationStep - the generation def element to process
0289:             * @param pURLContext - the url of the original xml plan definition document, can be used to find documents on the relative path
0290:             * @param pTemplateContext context to pass to every generation template
0291:             * @param pStepLocation XPath location of the step we need to excute (basically XPath location of the pGenerationStep element). 
0292:             * @return If there was no match at all -1 is returned, if there was a match non-negative long integer is returned indicating number of files actually generated */
0293:            private static long doGenerationForGenerationStep(
0294:                    String pDestinationDirectory,
0295:                    ModelRepository pModelRepository,
0296:                    Collection pModelContextObjects,
0297:                    GenerationStep pGenerationStep, URL pURLContext,
0298:                    Map pTemplateContext, String pStepLocation)
0299:                    throws BSException {
0300:                // Work on matching
0301:                Collection lMatchingModelElements = null;
0302:                String lXPathLocationToMatch = pGenerationStep.getMatchXPath();
0303:                String lElementRefToMatch = pGenerationStep.getMatchRef();
0304:                if (lXPathLocationToMatch != null) {
0305:                    try {
0306:                        lMatchingModelElements = pModelRepository
0307:                                .searchByXPath(pModelContextObjects,
0308:                                        lXPathLocationToMatch);
0309:                        if (sLogger.isDebugEnabled()) {
0310:                            if (lMatchingModelElements.isEmpty())
0311:                                sLogger
0312:                                        .debug("No model elements have matched required XPath location '"
0313:                                                + lXPathLocationToMatch + "'.");
0314:                            else if (lMatchingModelElements.size() == 1)
0315:                                sLogger
0316:                                        .debug("Found one model element which have matched required XPath location '"
0317:                                                + lXPathLocationToMatch + "'.");
0318:                            else
0319:                                sLogger
0320:                                        .debug("Found "
0321:                                                + lMatchingModelElements.size()
0322:                                                + " model elements which have matched required XPath location '"
0323:                                                + lXPathLocationToMatch + "'.");
0324:                        }
0325:                    } catch (ModelRepositoryException e) {
0326:                        throw new BSModelRepositoryInvocationException(
0327:                                "Caught exception while executing XPath search. Problem location: "
0328:                                        + pStepLocation, e);
0329:                    }
0330:                } else if (lElementRefToMatch != null) {
0331:                    try {
0332:                        lMatchingModelElements = new ArrayList();
0333:                        for (Iterator lModelContextObjectsIterator = pModelContextObjects
0334:                                .iterator(); lModelContextObjectsIterator
0335:                                .hasNext();) {
0336:                            RefBaseObject lModelContextObject = (RefBaseObject) lModelContextObjectsIterator
0337:                                    .next();
0338:                            // Ensure that this is the MetaBoss model - this will not work with any other
0339:                            String lOwnerModelName = pModelRepository
0340:                                    .getOwnerModelName(lModelContextObject);
0341:                            String lOwnerMetaModelName = pModelRepository
0342:                                    .getMetaModelName(lOwnerModelName);
0343:                            if (!lOwnerMetaModelName
0344:                                    .equals(ModelRepository.METAMODEL_NAME_METABOSS))
0345:                                throw new BSIllegalArgumentException(
0346:                                        "Matching of model elements by reference only works for MetaBoss Models. Model '"
0347:                                                + lOwnerModelName
0348:                                                + "' is not for the right kind and its elements can not be matched by reference. Problem location: "
0349:                                                + pStepLocation);
0350:                            if (lModelContextObject instanceof  ModelElement) {
0351:                                // This is just a normal model element
0352:                                for (Iterator lCombinedContentsIterator = ((ModelElement) lModelContextObject)
0353:                                        .getCombinedContents().iterator(); lCombinedContentsIterator
0354:                                        .hasNext();) {
0355:                                    ModelElement lContainedElement = (ModelElement) lCombinedContentsIterator
0356:                                            .next();
0357:                                    if (lContainedElement.getRef().matches(
0358:                                            lElementRefToMatch))
0359:                                        lMatchingModelElements
0360:                                                .add(lContainedElement);
0361:                                }
0362:                            } else if (lModelContextObject instanceof  MetaBossModelPackage) {
0363:                                // This is the model extent
0364:                                for (Iterator lTopLevelModelElementsIterator = pModelRepository
0365:                                        .getTopLevelModelObjects(
0366:                                                lOwnerModelName).iterator(); lTopLevelModelElementsIterator
0367:                                        .hasNext();) {
0368:                                    // Deal with the top level element
0369:                                    ModelElement lTopLevelModelElement = (ModelElement) lTopLevelModelElementsIterator
0370:                                            .next();
0371:                                    if (lTopLevelModelElement.getRef().matches(
0372:                                            lElementRefToMatch))
0373:                                        lMatchingModelElements
0374:                                                .add(lTopLevelModelElement);
0375:                                    // Deal with all contained elements
0376:                                    for (Iterator lCombinedContentsIterator = lTopLevelModelElement
0377:                                            .getCombinedContents().iterator(); lCombinedContentsIterator
0378:                                            .hasNext();) {
0379:                                        ModelElement lContainedElement = (ModelElement) lCombinedContentsIterator
0380:                                                .next();
0381:                                        if (lContainedElement.getRef().matches(
0382:                                                lElementRefToMatch))
0383:                                            lMatchingModelElements
0384:                                                    .add(lContainedElement);
0385:                                    }
0386:                                }
0387:                            } else
0388:                                throw new BSUnexpectedProgramConditionException(
0389:                                        "Unexpected type of model context object: "
0390:                                                + lModelContextObject
0391:                                                        .getClass().getName());
0392:                        }
0393:                        if (sLogger.isDebugEnabled()) {
0394:                            if (lMatchingModelElements.isEmpty())
0395:                                sLogger
0396:                                        .debug("No model elements have matched required Model Element Ref '"
0397:                                                + lElementRefToMatch + "'.");
0398:                            else if (lMatchingModelElements.size() == 1)
0399:                                sLogger
0400:                                        .debug("Found one model element which have matched required Model Element Ref '"
0401:                                                + lElementRefToMatch + "'.");
0402:                            else
0403:                                sLogger
0404:                                        .debug("Found "
0405:                                                + lMatchingModelElements.size()
0406:                                                + " model elements which have matched required Model Element Ref '"
0407:                                                + lElementRefToMatch + "'.");
0408:                        }
0409:                    } catch (ModelRepositoryException e) {
0410:                        throw new BSModelRepositoryInvocationException(
0411:                                "Caught exception while executing ref matching. Problem location: "
0412:                                        + pStepLocation, e);
0413:                    }
0414:                } else {
0415:                    // No XPath no ref - we will just use the given context objects
0416:                    lMatchingModelElements = pModelContextObjects;
0417:                }
0418:                // Check if there was a match. Return -1 if there wasn't
0419:                if (lMatchingModelElements.isEmpty())
0420:                    return -1;
0421:                long lProducedFilesCounter = 0;
0422:                // We now have a list of model elements which matches the def
0423:                // Execute all instructions against each of the elements
0424:
0425:                // First prepare the context
0426:                java.util.Map lContextMap = new java.util.HashMap();
0427:                lContextMap.putAll(pTemplateContext);
0428:                lContextMap.put("StylesheetAccessor", sStylesheetAccessor);
0429:                lContextMap.put("JndiContext", sJndiContext);
0430:                lContextMap.put("FormattingHelper", sFormattingHelper);
0431:                // Do all the necessary steps
0432:                GenerationStepType.CopyInstructionsType lCopyInstructions = pGenerationStep
0433:                        .getCopyInstructions();
0434:                GenerationStepType.GenerateInstructionsType lGenerateInstructions = pGenerationStep
0435:                        .getGenerateInstructions();
0436:                GenerationStepType.SubstepsType lSubsteps = pGenerationStep
0437:                        .getSubsteps();
0438:                // Run through the steps looking for the ones we need to do once only on match
0439:                {
0440:                    Object lPreviousContextObject = lContextMap.put("Elements",
0441:                            lMatchingModelElements);
0442:                    // Copying
0443:                    if (lCopyInstructions != null) {
0444:                        List lCopySteps = lCopyInstructions
0445:                                .getCopyFileStepOrCopyFileListStep();
0446:                        if (!lCopySteps.isEmpty())
0447:                            lProducedFilesCounter += doCopying("onMatch",
0448:                                    pDestinationDirectory, lCopyInstructions,
0449:                                    pURLContext, lContextMap, pStepLocation
0450:                                            + "/CopyInstructions");
0451:                    }
0452:                    // Generation
0453:                    if (lGenerateInstructions != null) {
0454:                        List lGenerationSteps = lGenerateInstructions
0455:                                .getGenerateFileStep();
0456:                        if (!lGenerationSteps.isEmpty())
0457:                            lProducedFilesCounter += doGenerating("onMatch",
0458:                                    pDestinationDirectory,
0459:                                    lGenerateInstructions, pURLContext,
0460:                                    lContextMap, pStepLocation
0461:                                            + "/GenerateInstructions");
0462:                    }
0463:                    // Substeps
0464:                    if (lSubsteps != null
0465:                            && lSubsteps.getExecutionPolicy().equals("onMatch"))
0466:                        lProducedFilesCounter += doSubsteps(
0467:                                pDestinationDirectory, lSubsteps,
0468:                                pModelRepository, lMatchingModelElements,
0469:                                pURLContext, pTemplateContext, pStepLocation);
0470:
0471:                    if (lPreviousContextObject != null)
0472:                        lContextMap.put("Elements", lPreviousContextObject);
0473:                    else
0474:                        lContextMap.remove("Elements");
0475:                }
0476:                // Now run through the steps looking for the ones we need to do once per matched element
0477:                for (Iterator lMatchedElementsIterator = lMatchingModelElements
0478:                        .iterator(); lMatchedElementsIterator.hasNext();) {
0479:                    RefBaseObject lMatchedElement = (RefBaseObject) lMatchedElementsIterator
0480:                            .next();
0481:                    String lReadableElementName = null;
0482:                    if (lMatchedElement instanceof  ModelElement)
0483:                        lReadableElementName = ((ModelElement) lMatchedElement)
0484:                                .getRef()
0485:                                + " Model Element";
0486:                    else
0487:                        lReadableElementName = "Instance of "
0488:                                + lMatchedElement.refMetaObject().refGetValue(
0489:                                        "name");
0490:                    // Prepare template context and run steps for this element
0491:                    RefObject lModelElementMetaObject = lMatchedElement
0492:                            .refMetaObject();
0493:                    String lModelElementTypeName = (String) lModelElementMetaObject
0494:                            .refGetValue("name");
0495:                    Object lPreviousContextObject = lContextMap.put(
0496:                            lModelElementTypeName, lMatchedElement);
0497:
0498:                    // Copying
0499:                    if (lCopyInstructions != null) {
0500:                        List lCopySteps = lCopyInstructions
0501:                                .getCopyFileStepOrCopyFileListStep();
0502:                        if (!lCopySteps.isEmpty())
0503:                            lProducedFilesCounter += doCopying("forEachMatch",
0504:                                    pDestinationDirectory, lCopyInstructions,
0505:                                    pURLContext, lContextMap, pStepLocation
0506:                                            + "/CopyInstructions");
0507:                    }
0508:                    // Generation
0509:                    if (lGenerateInstructions != null) {
0510:                        List lGenerationSteps = lGenerateInstructions
0511:                                .getGenerateFileStep();
0512:                        if (!lGenerationSteps.isEmpty())
0513:                            lProducedFilesCounter += doGenerating(
0514:                                    "forEachMatch", pDestinationDirectory,
0515:                                    lGenerateInstructions, pURLContext,
0516:                                    lContextMap, pStepLocation
0517:                                            + "/GenerateInstructions");
0518:                    }
0519:
0520:                    // Substeps
0521:                    if (lSubsteps != null
0522:                            && lSubsteps.getExecutionPolicy().equals(
0523:                                    "forEachMatch"))
0524:                        lProducedFilesCounter += doSubsteps(
0525:                                pDestinationDirectory,
0526:                                lSubsteps,
0527:                                pModelRepository,
0528:                                Arrays
0529:                                        .asList(new RefBaseObject[] { lMatchedElement }),
0530:                                pURLContext, pTemplateContext, pStepLocation);
0531:
0532:                    if (lPreviousContextObject != null)
0533:                        lContextMap.put(lModelElementTypeName,
0534:                                lPreviousContextObject);
0535:                    else
0536:                        lContextMap.remove(lModelElementTypeName);
0537:
0538:                }
0539:                return lProducedFilesCounter;
0540:            }
0541:
0542:            // Helper. Executes generation substeps 
0543:            private static long doSubsteps(String pDestinationDirectory,
0544:                    GenerationStepType.SubstepsType pSubsteps,
0545:                    ModelRepository pModelRepository,
0546:                    Collection pModelElements, URL pURLContext,
0547:                    Map pTemplateContext, String pStepLocation)
0548:                    throws BSException {
0549:                boolean lExitAfterFirstMatch = pSubsteps.getMatchPolicy()
0550:                        .equals("first");
0551:                String lSubstepsLocation = pStepLocation + "/Substeps";
0552:                int lGenerationSubstepsCounter = 0;
0553:                long lProducedFilesCounter = 0;
0554:                boolean lNeedIndex = pSubsteps.getGenerationStep().size() > 1;
0555:                for (Iterator lGenerationSubstepsIterator = pSubsteps
0556:                        .getGenerationStep().iterator(); lGenerationSubstepsIterator
0557:                        .hasNext();) {
0558:                    GenerationStep lGenerationSubstep = (GenerationStep) lGenerationSubstepsIterator
0559:                            .next();
0560:                    String lStepLocation = lSubstepsLocation
0561:                            + "/GenerationStep"
0562:                            + (lNeedIndex ? ("["
0563:                                    + (++lGenerationSubstepsCounter) + "]")
0564:                                    : "");
0565:                    // Call the recursive GenerationStep processing method
0566:                    long lNumberOfFilesInThisStep = doGenerationForGenerationStep(
0567:                            pDestinationDirectory, pModelRepository,
0568:                            pModelElements, lGenerationSubstep, pURLContext,
0569:                            pTemplateContext, lStepLocation);
0570:                    // Update the counter.
0571:                    if (lNumberOfFilesInThisStep > 0)
0572:                        lProducedFilesCounter += lNumberOfFilesInThisStep;
0573:                    // We may need to stop iterations if we have matched the step and policy is 'first'
0574:                    // Matching step will be indicated by not negative integer
0575:                    if (lExitAfterFirstMatch && lNumberOfFilesInThisStep >= 0) {
0576:                        // There was a match and we are told not to look any further
0577:                        if (sLogger.isDebugEnabled()
0578:                                && lGenerationSubstepsIterator.hasNext())
0579:                            sLogger
0580:                                    .debug("Skipping execution of sibling generation steps after "
0581:                                            + lStepLocation
0582:                                            + " due to the specified matchPolicy.");
0583:                        break;
0584:                    }
0585:                }
0586:                return lProducedFilesCounter;
0587:            }
0588:
0589:            // Helper. Does the generating of all defined resources from source to target 
0590:            private static long doGenerating(
0591:                    String pExecutionPolicy,
0592:                    String pDestinationDirectory,
0593:                    GenerationStepType.GenerateInstructionsType pGenerateInstructions,
0594:                    URL pURLContext, Map pTemplateContext, String pStepLocation)
0595:                    throws BSException {
0596:                // Do all the copying steps
0597:                int lGeneratedFilesCounter = 0;
0598:                String lTargetFileTemplateInclude = pGenerateInstructions
0599:                        .getTargetFileTemplateInclude();
0600:                for (Iterator lGenerateFileStepsIterator = pGenerateInstructions
0601:                        .getGenerateFileStep().iterator(); lGenerateFileStepsIterator
0602:                        .hasNext();) {
0603:                    GenerateFileStep lGenerateFileStep = (GenerateFileStep) lGenerateFileStepsIterator
0604:                            .next();
0605:                    if (pExecutionPolicy != null
0606:                            && lGenerateFileStep.getExecutionPolicy().equals(
0607:                                    pExecutionPolicy) == false)
0608:                        continue; // This generation step has a different execution policy
0609:                    lGeneratedFilesCounter++;
0610:                    String lStepLocation = pStepLocation + "/GenerateFileStep["
0611:                            + lGeneratedFilesCounter + "]";
0612:                    URL lSourceURL = null; // Full URL of the source 
0613:                    String lSourceLocation = null; // Location of the source relative to the context
0614:                    try {
0615:                        SourceFileType lSourceFile = lGenerateFileStep
0616:                                .getSourceFile();
0617:                        lSourceLocation = lSourceFile.getLocation();
0618:                        if (lSourceLocation == null) {
0619:                            String lLocationTemplate = lSourceFile.getValue();
0620:                            if (lLocationTemplate != null) {
0621:                                MergeResult lResult = sVelocityTemplateProcessor
0622:                                        .mergeTemplate(lLocationTemplate, "",
0623:                                                pTemplateContext);
0624:                                if (!lResult.isSuccessful()) {
0625:                                    // We handle problems here by throwing the exceptions
0626:                                    throw new BSUnexpectedProgramConditionException(
0627:                                            "Error processing template. Template processor log :"
0628:                                                    + lResult
0629:                                                            .getMergeLogPrintout()
0630:                                                    + " Problem location: "
0631:                                                    + lStepLocation);
0632:                                }
0633:                                lSourceLocation = lResult.getMergedOutput();
0634:                            }
0635:                        }
0636:                        if (lSourceLocation == null
0637:                                || lSourceLocation.trim().length() == 0)
0638:                            throw new BSUnexpectedProgramConditionException(
0639:                                    "Undefined source location in the generate file step. Problem location: "
0640:                                            + lStepLocation);
0641:                        lSourceURL = new URL(pURLContext, lSourceLocation);
0642:                    } catch (MalformedURLException e) {
0643:                        throw new BSUnexpectedProgramConditionException(
0644:                                "Invalid source location in the generate file step. Problem location: "
0645:                                        + lStepLocation, e);
0646:                    }
0647:                    File lDestinationFile = null;
0648:                    {
0649:                        TargetFileType lTargetFile = lGenerateFileStep
0650:                                .getTargetFile();
0651:                        String lTargetLocation = lTargetFile.getLocation();
0652:                        if (lTargetLocation == null) {
0653:                            String lLocationTemplate = lTargetFile.getValue();
0654:                            if (lLocationTemplate != null) {
0655:                                // Prepend the template with the included one if necessary
0656:                                if (lTargetFileTemplateInclude != null)
0657:                                    lLocationTemplate = lTargetFileTemplateInclude
0658:                                            + lLocationTemplate;
0659:                                MergeResult lResult = sVelocityTemplateProcessor
0660:                                        .mergeTemplate(lLocationTemplate, "",
0661:                                                pTemplateContext);
0662:                                if (!lResult.isSuccessful()) {
0663:                                    // We handle problems here by throwing the exceptions
0664:                                    throw new BSUnexpectedProgramConditionException(
0665:                                            "Error processing template. Template processor log :"
0666:                                                    + lResult
0667:                                                            .getMergeLogPrintout()
0668:                                                    + " Problem location: "
0669:                                                    + lStepLocation);
0670:                                }
0671:                                lTargetLocation = lResult.getMergedOutput();
0672:                            }
0673:                        }
0674:                        if (lTargetLocation == null
0675:                                || lTargetLocation.trim().length() == 0)
0676:                            throw new BSUnexpectedProgramConditionException(
0677:                                    "Undefined target location in the generate file step. Problem location: "
0678:                                            + lStepLocation);
0679:                        lDestinationFile = new File(pDestinationDirectory
0680:                                + File.separator + lTargetLocation.trim());
0681:                    }
0682:                    // Now do the generation depending on file extension
0683:                    if (lSourceLocation.endsWith(".jamon")) {
0684:                        // Process jamon template
0685:                        try {
0686:                            InputStream lInputStream = null;
0687:                            try {
0688:                                if ((lInputStream = lSourceURL.openStream()) == null)
0689:                                    throw new BSUnexpectedProgramConditionException(
0690:                                            "Unable to locate resource: "
0691:                                                    + lSourceURL
0692:                                                    + " Problem location: "
0693:                                                    + lStepLocation);
0694:                                String lTemplate = StringUtils
0695:                                        .readTextStreamFully(lInputStream);
0696:                                MergeResult lResult = sJamonTemplateProcessor
0697:                                        .mergeTemplate(
0698:                                                lTemplate,
0699:                                                StringUtils
0700:                                                        .suggestJavaIdentifier(lSourceURL
0701:                                                                .toExternalForm()),
0702:                                                pTemplateContext);
0703:                                if (!lResult.isSuccessful()) {
0704:                                    // We handle problems here by loging the problem and returning model URI
0705:                                    throw new BSUnexpectedProgramConditionException(
0706:                                            "Error processing template. Template processor log :"
0707:                                                    + lResult
0708:                                                            .getMergeLogPrintout()
0709:                                                    + " Problem location: "
0710:                                                    + lStepLocation);
0711:                                }
0712:                                FileWriter lFileWriter = null;
0713:                                try {
0714:                                    DirectoryUtils
0715:                                            .ensureThereIsDirectory(lDestinationFile
0716:                                                    .getParent());
0717:                                    lFileWriter = new FileWriter(
0718:                                            lDestinationFile);
0719:                                    lFileWriter
0720:                                            .write(lResult.getMergedOutput());
0721:                                    lFileWriter.flush();
0722:                                } finally {
0723:                                    if (lFileWriter != null)
0724:                                        lFileWriter.close();
0725:                                }
0726:                            } finally {
0727:                                if (lInputStream != null)
0728:                                    lInputStream.close();
0729:                            }
0730:                        } catch (IOException e) {
0731:                            throw new BSServiceProviderException(
0732:                                    "Unable to process Jamon template.", e);
0733:                        }
0734:                    } else if (lSourceLocation.endsWith(".vsl")) {
0735:                        // Process velocity template
0736:                        try {
0737:                            InputStream lInputStream = null;
0738:                            try {
0739:                                if ((lInputStream = lSourceURL.openStream()) == null)
0740:                                    throw new BSUnexpectedProgramConditionException(
0741:                                            "Unable to locate resource: "
0742:                                                    + lSourceURL
0743:                                                    + " Problem location: "
0744:                                                    + lStepLocation);
0745:                                String lTemplate = StringUtils
0746:                                        .readTextStreamFully(lInputStream);
0747:                                MergeResult lResult = sVelocityTemplateProcessor
0748:                                        .mergeTemplate(
0749:                                                lTemplate,
0750:                                                StringUtils
0751:                                                        .suggestJavaIdentifier(lSourceURL
0752:                                                                .toExternalForm()),
0753:                                                pTemplateContext);
0754:                                if (!lResult.isSuccessful()) {
0755:                                    // We handle problems here by loging the problem and returning model URI
0756:                                    throw new BSUnexpectedProgramConditionException(
0757:                                            "Error processing template. Template processor log :"
0758:                                                    + lResult
0759:                                                            .getMergeLogPrintout()
0760:                                                    + " Problem location: "
0761:                                                    + lStepLocation);
0762:                                }
0763:                                FileWriter lFileWriter = null;
0764:                                try {
0765:                                    DirectoryUtils
0766:                                            .ensureThereIsDirectory(lDestinationFile
0767:                                                    .getParent());
0768:                                    lFileWriter = new FileWriter(
0769:                                            lDestinationFile);
0770:                                    lFileWriter
0771:                                            .write(lResult.getMergedOutput());
0772:                                    lFileWriter.flush();
0773:                                } finally {
0774:                                    if (lFileWriter != null)
0775:                                        lFileWriter.close();
0776:                                }
0777:                            } finally {
0778:                                if (lInputStream != null)
0779:                                    lInputStream.close();
0780:                            }
0781:                        } catch (IOException e) {
0782:                            throw new BSServiceProviderException(
0783:                                    "Unable to process Velocity template.", e);
0784:                        }
0785:                    } else if (lSourceLocation.endsWith(".java")) {
0786:                        // Process Java template
0787:                        // Need to come up with the full java class name
0788:                        String lJavaSoureceClassName = lSourceLocation
0789:                                .substring(0, lSourceLocation.length() - 5)
0790:                                .replaceAll("/", ".");
0791:                        try {
0792:                            InputStream lInputStream = null;
0793:                            try {
0794:                                if ((lInputStream = lSourceURL.openStream()) == null)
0795:                                    throw new BSUnexpectedProgramConditionException(
0796:                                            "Unable to locate resource: "
0797:                                                    + lSourceURL
0798:                                                    + " Problem location: "
0799:                                                    + lStepLocation);
0800:                                String lTemplate = StringUtils
0801:                                        .readTextStreamFully(lInputStream);
0802:                                MergeResult lResult = sJavaTemplateProcessor
0803:                                        .mergeTemplate(
0804:                                                lTemplate,
0805:                                                StringUtils
0806:                                                        .suggestJavaIdentifier(lSourceURL
0807:                                                                .toExternalForm()),
0808:                                                lJavaSoureceClassName,
0809:                                                pTemplateContext);
0810:                                if (!lResult.isSuccessful()) {
0811:                                    // We handle problems here by loging the problem and returning model URI
0812:                                    throw new BSUnexpectedProgramConditionException(
0813:                                            "Error processing template. Template processor log :"
0814:                                                    + lResult
0815:                                                            .getMergeLogPrintout()
0816:                                                    + " Problem location: "
0817:                                                    + lStepLocation);
0818:                                }
0819:                                FileWriter lFileWriter = null;
0820:                                try {
0821:                                    DirectoryUtils
0822:                                            .ensureThereIsDirectory(lDestinationFile
0823:                                                    .getParent());
0824:                                    lFileWriter = new FileWriter(
0825:                                            lDestinationFile);
0826:                                    lFileWriter
0827:                                            .write(lResult.getMergedOutput());
0828:                                    lFileWriter.flush();
0829:                                } finally {
0830:                                    if (lFileWriter != null)
0831:                                        lFileWriter.close();
0832:                                }
0833:                            } finally {
0834:                                if (lInputStream != null)
0835:                                    lInputStream.close();
0836:                            }
0837:                        } catch (IOException e) {
0838:                            throw new BSServiceProviderException(
0839:                                    "Unable to process Velocity template.", e);
0840:                        }
0841:                    } else
0842:                        throw new BSUnexpectedProgramConditionException(
0843:                                "Unknown source template type. Unable to process template at "
0844:                                        + lSourceURL.toExternalForm());
0845:                }
0846:                return lGeneratedFilesCounter;
0847:            }
0848:
0849:            // Helper. Does the copying of all defined resources from source to target 
0850:            private static long doCopying(String pExecutionPolicy,
0851:                    String pDestinationDirectory,
0852:                    GenerationStepType.CopyInstructionsType pCopyInstructions,
0853:                    URL pURLContext, Map pTemplateContext, String pStepLocation)
0854:                    throws BSException {
0855:                long lCopiedFilesCounter = 0;
0856:                int lCopyFileStepCounter = 0;
0857:                int lCopyFileListStepCounter = 0;
0858:                // Do all the copying steps if necessary
0859:                for (Iterator lCopyFileStepsIterator = pCopyInstructions
0860:                        .getCopyFileStepOrCopyFileListStep().iterator(); lCopyFileStepsIterator
0861:                        .hasNext();) {
0862:                    Object lStep = lCopyFileStepsIterator.next();
0863:                    if (lStep instanceof  CopyFileStep) {
0864:                        CopyFileStep lCopyFileStep = (CopyFileStep) lStep;
0865:                        // Only execute the step if execution policy is matching, or not specified at all
0866:                        if (pExecutionPolicy == null
0867:                                || lCopyFileStep.getExecutionPolicy().equals(
0868:                                        pExecutionPolicy)) {
0869:                            String lStepLocation = pStepLocation
0870:                                    + "/CopyFileStep["
0871:                                    + Integer.toString(++lCopyFileStepCounter)
0872:                                    + "]";
0873:                            lCopiedFilesCounter += doCopyFileStep(
0874:                                    pDestinationDirectory, lCopyFileStep,
0875:                                    pURLContext, pTemplateContext,
0876:                                    lStepLocation);
0877:                        }
0878:                    } else if (lStep instanceof  CopyFileListStep) {
0879:                        CopyFileListStep lCopyFileListStep = (CopyFileListStep) lStep;
0880:                        // Only execute the step if execution policy is matching, or not specified at all
0881:                        if (pExecutionPolicy == null
0882:                                || lCopyFileListStep.getExecutionPolicy()
0883:                                        .equals(pExecutionPolicy)) {
0884:                            String lStepLocation = pStepLocation
0885:                                    + "/CopyFileListStep["
0886:                                    + Integer
0887:                                            .toString(++lCopyFileListStepCounter)
0888:                                    + "]";
0889:                            lCopiedFilesCounter += doCopyFileListStep(
0890:                                    pDestinationDirectory, lCopyFileListStep,
0891:                                    pURLContext, pTemplateContext,
0892:                                    lStepLocation);
0893:                        }
0894:                    }
0895:                }
0896:                return lCopiedFilesCounter;
0897:            }
0898:
0899:            // Helper. Does the copying of a single file from source to target 
0900:            private static long doCopyFileStep(String pDestinationDirectory,
0901:                    CopyFileStep pCopyFileStep, URL pURLContext,
0902:                    Map pTemplateContext, String pStepLocation)
0903:                    throws BSException {
0904:                URL lSourceURL = null;
0905:                try {
0906:                    SourceFileType lSourceFile = pCopyFileStep.getSourceFile();
0907:                    String lSourceLocation = lSourceFile.getLocation();
0908:                    if (lSourceLocation == null) {
0909:                        String lLocationTemplate = lSourceFile.getValue();
0910:                        if (lLocationTemplate != null) {
0911:                            MergeResult lResult = sVelocityTemplateProcessor
0912:                                    .mergeTemplate(lLocationTemplate, "",
0913:                                            pTemplateContext);
0914:                            if (!lResult.isSuccessful()) {
0915:                                // We handle problems here by throwing the exceptions
0916:                                throw new BSUnexpectedProgramConditionException(
0917:                                        "Error processing template. Template processor log :"
0918:                                                + lResult.getMergeLogPrintout()
0919:                                                + " Problem location: "
0920:                                                + pStepLocation);
0921:                            }
0922:                            lSourceLocation = lResult.getMergedOutput();
0923:                        }
0924:                    }
0925:                    if (lSourceLocation == null
0926:                            || lSourceLocation.trim().length() == 0)
0927:                        throw new BSUnexpectedProgramConditionException(
0928:                                "Undefined source location in the copy file step. Problem location: "
0929:                                        + pStepLocation);
0930:                    lSourceURL = new URL(pURLContext, lSourceLocation);
0931:                } catch (MalformedURLException e) {
0932:                    throw new BSUnexpectedProgramConditionException(
0933:                            "Invalid source location in the copy file step. Problem location: "
0934:                                    + pStepLocation, e);
0935:                }
0936:                File lDestinationFile = null;
0937:                {
0938:                    TargetFileType lTargetFile = pCopyFileStep.getTargetFile();
0939:                    String lTargetLocation = lTargetFile.getLocation();
0940:                    if (lTargetLocation == null) {
0941:                        String lLocationTemplate = lTargetFile.getValue();
0942:                        if (lLocationTemplate != null) {
0943:                            MergeResult lResult = sVelocityTemplateProcessor
0944:                                    .mergeTemplate(lLocationTemplate, "",
0945:                                            pTemplateContext);
0946:                            if (!lResult.isSuccessful()) {
0947:                                // We handle problems here by throwing the exceptions
0948:                                throw new BSUnexpectedProgramConditionException(
0949:                                        "Error processing template. Template processor log :"
0950:                                                + lResult.getMergeLogPrintout()
0951:                                                + " Problem location: "
0952:                                                + pStepLocation);
0953:                            }
0954:                            lTargetLocation = lResult.getMergedOutput();
0955:                        }
0956:                    }
0957:                    if (lTargetLocation == null
0958:                            || lTargetLocation.trim().length() == 0)
0959:                        throw new BSUnexpectedProgramConditionException(
0960:                                "Undefined target location in the copy file step. Problem location: "
0961:                                        + pStepLocation);
0962:                    lDestinationFile = new File(pDestinationDirectory
0963:                            + File.separator + lTargetLocation);
0964:                }
0965:                // Now do the copying
0966:                try {
0967:                    InputStream lInputStream = null;
0968:                    try {
0969:                        if ((lInputStream = lSourceURL.openStream()) == null)
0970:                            throw new BSUnexpectedProgramConditionException(
0971:                                    "Unable to open URL for reading: "
0972:                                            + lSourceURL
0973:                                            + " Problem location: "
0974:                                            + pStepLocation);
0975:                        DirectoryUtils.ensureThereIsDirectory(lDestinationFile
0976:                                .getParent());
0977:                        OutputStream lOutputStream = null;
0978:                        try {
0979:                            lOutputStream = new FileOutputStream(
0980:                                    lDestinationFile, false);
0981:                            StreamUtils.copyData(lInputStream, lOutputStream);
0982:                            lOutputStream.flush();
0983:                            return 1L;
0984:                        } finally {
0985:                            if (lOutputStream != null)
0986:                                lOutputStream.close();
0987:                        }
0988:                    } finally {
0989:                        if (lInputStream != null)
0990:                            lInputStream.close();
0991:                    }
0992:                } catch (IOException e) {
0993:                    throw new BSServiceProviderException(
0994:                            "Unable to copy resource files. Problem location: "
0995:                                    + pStepLocation, e);
0996:                }
0997:            }
0998:
0999:            // Helper. Does the copying of a single file from source to target 
1000:            private static long doCopyFileListStep(
1001:                    String pDestinationDirectory,
1002:                    CopyFileListStep pCopyFileListStep, URL pURLContext,
1003:                    Map pTemplateContext, String pStepLocation)
1004:                    throws BSException {
1005:                SourceFileListType lSourceFileList = pCopyFileListStep
1006:                        .getSourceFileList();
1007:                String lBasedir = lSourceFileList.getBasedir();
1008:                List lSourceLocations = new ArrayList();
1009:                for (Iterator lSourceFilesIterator = lSourceFileList
1010:                        .getSourceFile().iterator(); lSourceFilesIterator
1011:                        .hasNext();) {
1012:                    SourceFileType lSourceFile = (SourceFileType) lSourceFilesIterator
1013:                            .next();
1014:                    String lSourceLocation = lSourceFile.getLocation();
1015:                    if (lSourceLocation == null) {
1016:                        String lLocationTemplate = lSourceFile.getValue();
1017:                        if (lLocationTemplate != null) {
1018:                            MergeResult lResult = sVelocityTemplateProcessor
1019:                                    .mergeTemplate(lLocationTemplate, "",
1020:                                            pTemplateContext);
1021:                            if (!lResult.isSuccessful()) {
1022:                                // We handle problems here by throwing the exceptions
1023:                                throw new BSUnexpectedProgramConditionException(
1024:                                        "Error processing template. Template processor log :"
1025:                                                + lResult.getMergeLogPrintout()
1026:                                                + " Problem location: "
1027:                                                + pStepLocation);
1028:                            }
1029:                            lSourceLocation = lResult.getMergedOutput();
1030:                        }
1031:                    }
1032:                    if (lSourceLocation == null
1033:                            || lSourceLocation.trim().length() == 0)
1034:                        throw new BSUnexpectedProgramConditionException(
1035:                                "Undefined source location in the copy file step. Problem location: "
1036:                                        + pStepLocation);
1037:                    lSourceLocations.add(lSourceLocation);
1038:                }
1039:
1040:                File lDestinationDir = null;
1041:                {
1042:                    TargetDirType lTargetDir = pCopyFileListStep.getTargetDir();
1043:                    String lTargetLocation = lTargetDir.getLocation();
1044:                    if (lTargetLocation == null) {
1045:                        String lLocationTemplate = lTargetDir.getValue();
1046:                        if (lLocationTemplate != null) {
1047:                            MergeResult lResult = sVelocityTemplateProcessor
1048:                                    .mergeTemplate(lLocationTemplate, "",
1049:                                            pTemplateContext);
1050:                            if (!lResult.isSuccessful()) {
1051:                                // We handle problems here by throwing the exceptions
1052:                                throw new BSUnexpectedProgramConditionException(
1053:                                        "Error processing template. Template processor log :"
1054:                                                + lResult.getMergeLogPrintout()
1055:                                                + " Problem location: "
1056:                                                + pStepLocation);
1057:                            }
1058:                            lTargetLocation = lResult.getMergedOutput();
1059:                        }
1060:                    }
1061:                    if (lTargetLocation == null
1062:                            || lTargetLocation.trim().length() == 0)
1063:                        throw new BSUnexpectedProgramConditionException(
1064:                                "Undefined target location in the copy file step. Problem location: "
1065:                                        + pStepLocation);
1066:                    lDestinationDir = new File(pDestinationDirectory
1067:                            + File.separator + lTargetLocation);
1068:                }
1069:                // Now do the copying
1070:                try {
1071:                    DirectoryUtils.ensureThereIsDirectory(lDestinationDir
1072:                            .getAbsolutePath());
1073:                    for (Iterator lSourceLocationsIter = lSourceLocations
1074:                            .iterator(); lSourceLocationsIter.hasNext();) {
1075:                        String lSourceLocation = (String) lSourceLocationsIter
1076:                                .next();
1077:                        URL lSourceURL = (lBasedir != null && lBasedir.length() > 0) ? new URL(
1078:                                pURLContext, lBasedir + "/" + lSourceLocation)
1079:                                : new URL(pURLContext, lSourceLocation);
1080:                        String lDestinationFile = lDestinationDir
1081:                                .getAbsolutePath()
1082:                                + File.separator + lSourceLocation;
1083:                        InputStream lInputStream = null;
1084:                        try {
1085:                            if ((lInputStream = lSourceURL.openStream()) == null)
1086:                                throw new BSUnexpectedProgramConditionException(
1087:                                        "Unable to open URL for reading: "
1088:                                                + lSourceURL
1089:                                                + " Problem location: "
1090:                                                + pStepLocation);
1091:                            OutputStream lOutputStream = null;
1092:                            try {
1093:                                lOutputStream = new FileOutputStream(
1094:                                        lDestinationFile, false);
1095:                                StreamUtils.copyData(lInputStream,
1096:                                        lOutputStream);
1097:                                lOutputStream.flush();
1098:                            } finally {
1099:                                if (lOutputStream != null)
1100:                                    lOutputStream.close();
1101:                            }
1102:                        } finally {
1103:                            if (lInputStream != null)
1104:                                lInputStream.close();
1105:                        }
1106:                    }
1107:                    return lSourceLocations.size();
1108:                } catch (MalformedURLException e) {
1109:                    throw new BSUnexpectedProgramConditionException(
1110:                            "Invalid source location in the copy file step. Problem location: "
1111:                                    + pStepLocation, e);
1112:                } catch (IOException e) {
1113:                    throw new BSServiceProviderException(
1114:                            "Unable to copy resource files. Problem location: "
1115:                                    + pStepLocation, e);
1116:                }
1117:            }
1118:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.