View Javadoc

1   /*
2    * $Id: ModelFactory.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.impl.model;
12  
13  import org.mule.providers.service.TransportFactory;
14  import org.mule.umo.model.UMOModel;
15  import org.mule.util.BeanUtils;
16  import org.mule.util.ClassUtils;
17  import org.mule.util.SpiUtils;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.util.Properties;
22  
23  /**
24   * Will locate the model service in META-INF/service using the model type as the key
25   * and construct the model.
26   */
27  public final class ModelFactory
28  {
29  
30      public static final String DEFAULT_MODEL_NAME = "main";
31  
32      public static final String MODEL_SERVICE_PATH = "org/mule/models";
33  
34      /** Do not instanciate. */
35      private ModelFactory ()
36      {
37          // no-op
38      }
39  
40      public static UMOModel createModel(String type) throws ModelServiceNotFoundException
41      {
42          String location = SpiUtils.SERVICE_ROOT + MODEL_SERVICE_PATH;
43          InputStream is = SpiUtils.findServiceDescriptor(MODEL_SERVICE_PATH, type + ".properties", TransportFactory.class);
44          try
45          {
46              if (is != null)
47              {
48                  Properties props = new Properties();
49                  props.load(is);
50                  String clazz = props.getProperty("model");
51                  try
52                  {
53                      UMOModel model = (UMOModel) ClassUtils.instanciateClass(clazz, ClassUtils.NO_ARGS,
54                          ModelFactory.class);
55                      BeanUtils.populateWithoutFail(model, props, false);
56                      if (model.getName() == null)
57                      {
58                          model.setName(DEFAULT_MODEL_NAME);
59                      }
60                      return model;
61                  }
62                  catch (Exception e)
63                  {
64                      throw new ModelServiceNotFoundException(location + "/" + type, e);
65                  }
66              }
67              else
68              {
69                  throw new ModelServiceNotFoundException(location + "/" + type);
70              }
71          }
72          catch (IOException e)
73          {
74              throw new ModelServiceNotFoundException(location + "/" + type, e);
75          }
76      }
77  }