View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.config.spring.parsers.generic;
8   
9   import org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser;
10  import org.mule.util.StringUtils;
11  
12  import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
13  
14  import org.w3c.dom.Element;
15  
16  public class AutoIdUtils
17  {
18  
19      public static final String ATTRIBUTE_ID = AbstractMuleBeanDefinitionParser.ATTRIBUTE_ID;
20      public static final String ATTRIBUTE_NAME = AbstractMuleBeanDefinitionParser.ATTRIBUTE_NAME;
21      private static final AtomicInteger counter = new AtomicInteger(0);
22      public static final String PREFIX = "org.mule.autogen.";
23  
24      public static boolean blankAttribute(Element element, String attribute)
25      {
26          return StringUtils.isBlank(element.getAttribute(attribute));
27      }
28  
29      public static void ensureUniqueId(Element element, String type)
30      {
31          if (null != element && blankAttribute(element, ATTRIBUTE_ID))
32          {
33              if (blankAttribute(element, ATTRIBUTE_NAME))
34              {
35                  element.setAttribute(ATTRIBUTE_ID, uniqueValue(PREFIX + type));
36              }
37              else
38              {
39                  element.setAttribute(ATTRIBUTE_ID, element.getAttribute(ATTRIBUTE_NAME));
40              }
41          }
42      }
43  
44      public static String getUniqueName(Element element, String type)
45      {
46          if (!blankAttribute(element, ATTRIBUTE_NAME))
47          {
48              return element.getAttribute(ATTRIBUTE_NAME);
49          }
50          else if (!blankAttribute(element, ATTRIBUTE_ID))
51          {
52              return element.getAttribute(ATTRIBUTE_ID);
53          }
54          else
55          {
56              return uniqueValue(PREFIX + type);
57          }
58      }
59  
60      public static String uniqueValue(String value)
61      {
62          return value + "." + counter.incrementAndGet();
63      }
64  
65      public static void forceUniqueId(Element element, String type)
66      {
67          if (null != element)
68          {
69              String id = uniqueValue(PREFIX + type);
70              element.setAttribute(ATTRIBUTE_ID, id);
71              element.setAttribute(ATTRIBUTE_NAME, id);
72          }
73      }
74  
75  }