View Javadoc

1   /*
2    * $Id: AutoIdUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.config.spring.parsers.generic;
12  
13  import org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser;
14  import org.mule.util.StringUtils;
15  
16  import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
17  
18  import org.w3c.dom.Element;
19  
20  public class AutoIdUtils
21  {
22  
23      public static final String ATTRIBUTE_ID = AbstractMuleBeanDefinitionParser.ATTRIBUTE_ID;
24      public static final String ATTRIBUTE_NAME = AbstractMuleBeanDefinitionParser.ATTRIBUTE_NAME;
25      private static final AtomicInteger counter = new AtomicInteger(0);
26      public static final String PREFIX = "org.mule.autogen.";
27  
28      public static boolean blankAttribute(Element element, String attribute)
29      {
30          return StringUtils.isBlank(element.getAttribute(attribute));
31      }
32  
33      public static void ensureUniqueId(Element element, String type)
34      {
35          if (null != element && blankAttribute(element, ATTRIBUTE_ID))
36          {
37              if (blankAttribute(element, ATTRIBUTE_NAME))
38              {
39                  element.setAttribute(ATTRIBUTE_ID, uniqueValue(PREFIX + type));
40              }
41              else
42              {
43                  element.setAttribute(ATTRIBUTE_ID, element.getAttribute(ATTRIBUTE_NAME));
44              }
45          }
46      }
47  
48      public static String getUniqueName(Element element, String type)
49      {
50          if (!blankAttribute(element, ATTRIBUTE_NAME))
51          {
52              return element.getAttribute(ATTRIBUTE_NAME);
53          }
54          else if (!blankAttribute(element, ATTRIBUTE_ID))
55          {
56              return element.getAttribute(ATTRIBUTE_ID);
57          }
58          else
59          {
60              return uniqueValue(PREFIX + type);
61          }
62      }
63  
64      public static String uniqueValue(String value)
65      {
66          return value + "." + counter.incrementAndGet();
67      }
68  
69      public static void forceUniqueId(Element element, String type)
70      {
71          if (null != element)
72          {
73              String id = uniqueValue(PREFIX + type);
74              element.setAttribute(ATTRIBUTE_ID, id);
75              element.setAttribute(ATTRIBUTE_NAME, id);
76          }
77      }
78  
79  }