Example usage for java.util TreeSet toString

List of usage examples for java.util TreeSet toString

Introduction

In this page you can find the example usage for java.util TreeSet toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Get a JAXBContext for the class/*from   w w  w.  j a  v a  2 s .c om*/
 * 
 * Note: The contextPackage object is used by multiple threads.  It should be considered immutable
 * and not altered by this method.
 *
 * @param contextPackage Set<Package>
 * @param cacheKey ClassLoader
 * @return JAXBContext
 * @throws JAXBException
 * @deprecated
 */
public static JAXBContext getJAXBContext(TreeSet<String> contextPackages, ClassLoader cacheKey)
        throws JAXBException {
    return getJAXBContext(contextPackages, new Holder<CONSTRUCTION_TYPE>(), contextPackages.toString(),
            cacheKey, null);
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Get a JAXBContext for the class//from   ww w .j  a  v  a 2 s  .co  m
 *
 * Note: The contextPackage object is used by multiple threads.  It should be considered immutable
 * and not altered by this method.
 * 
 * @param contextPackage  Set<Package> 
 * @param contructionType (output value that indicates how the context was constructed)
 * @param forceArrays (forces the returned JAXBContext to include the array types)
 * @param cacheKey ClassLoader
 * @return JAXBContext
 * @throws JAXBException
 */
public static JAXBContext getJAXBContext(TreeSet<String> contextPackages,
        Holder<CONSTRUCTION_TYPE> constructionType, boolean forceArrays, String key, ClassLoader cacheKey,
        Map<String, ?> properties) throws JAXBException {
    // JAXBContexts for the same class can be reused and are supposed to be thread-safe
    if (log.isDebugEnabled()) {
        log.debug("Following packages are in this batch of getJAXBContext() :");
        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
    }
    if (JAXBUtilsMonitor.isMonitoring()) {
        JAXBUtilsMonitor.addPackageKey(contextPackages.toString());
    }

    // Get or Create The InnerMap using the package key
    ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);

    if (softRef != null) {
        innerMap = softRef.get();
    }

    if (innerMap == null) {
        synchronized (jaxbMap) {
            softRef = jaxbMap.get(key);
            if (softRef != null) {
                innerMap = softRef.get();
            }
            if (innerMap == null) {
                innerMap = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                softRef = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(innerMap);
                jaxbMap.put(key, softRef);
            }
        }
    }

    // Now get the contextValue using either the classloader key or 
    // the current Classloader
    ClassLoader cl = getContextClassLoader();
    JAXBContextValue contextValue = null;
    if (cacheKey != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using supplied classloader to retrieve JAXBContext: " + cacheKey);
        }
        contextValue = innerMap.get(cacheKey);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Using classloader from Thread to retrieve JAXBContext: " + cl);
        }
        contextValue = innerMap.get(cl);
    }

    // If the context value is found, but the caller requested that the JAXBContext
    // contain arrays, then rebuild the JAXBContext value
    if (forceArrays && contextValue != null
            && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
        if (log.isDebugEnabled()) {
            log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                    + "  but the caller requested a JAXBContext "
                    + " that includes arrays.  A new JAXBContext will be built");
        }
        contextValue = null;
    }

    if (contextPackages == null) {
        contextPackages = new TreeSet<String>();
    }
    if (contextValue == null) {
        synchronized (innerMap) {
            // Try to get the contextValue once more since sync was temporarily exited.
            ClassLoader clKey = (cacheKey != null) ? cacheKey : cl;
            contextValue = innerMap.get(clKey);
            adjustPoolSize(innerMap);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                contextValue = null;
            }
            if (contextValue == null) {
                // Create a copy of the contextPackages.  This new TreeSet will
                // contain only the valid contextPackages.
                // Note: The original contextPackage set is accessed by multiple 
                // threads and should not be altered.

                TreeSet<String> validContextPackages = new TreeSet<String>(contextPackages);

                List<String> classRefs = pruneDirectives(validContextPackages);

                int numPackages = validContextPackages.size();

                contextValue = createJAXBContextValue(validContextPackages, clKey, forceArrays, properties,
                        classRefs);

                synchronized (jaxbMap) {
                    // Add the context value with the original package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map1 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef1 = jaxbMap.get(key);
                    if (softRef1 != null) {
                        map1 = softRef1.get();
                    }
                    if (map1 == null) {
                        map1 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef1 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map1);
                        jaxbMap.put(key, softRef1);
                    }
                    map1.put(clKey, contextValue);

                    String validPackagesKey = validContextPackages.toString();

                    // Add the context value with the new package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map2 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef2 = jaxbMap
                            .get(validPackagesKey);
                    if (softRef2 != null) {
                        map2 = softRef2.get();
                    }
                    if (map2 == null) {
                        map2 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef2 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map2);
                        jaxbMap.put(validPackagesKey, softRef2);
                    }
                    map2.put(clKey, contextValue);

                    if (log.isDebugEnabled()) {
                        log.debug("JAXBContext [created] for " + key);
                        log.debug("JAXBContext also stored by the list of valid packages:" + validPackagesKey);
                    }
                }
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("JAXBContext [from pool] for " + key);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("JAXBContext constructionType= " + contextValue.constructionType);
        log.debug("JAXBContextValue = " + JavaUtils.getObjectIdentity(contextValue));
        log.debug("JAXBContext = " + JavaUtils.getObjectIdentity(contextValue.jaxbContext));
    }
    constructionType.value = contextValue.constructionType;
    return contextValue.jaxbContext;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader/*from  w  w w.  j  av a2  s  .c o  m*/
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //   
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH: 
    //    Pros: preferred way of doing this.  
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //        
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list. 
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}

From source file:org.apache.jackrabbit.oak.plugins.blob.FileLineDifferenceIteratorTest.java

@Test
public void testRandomized() throws Exception {
    Random r = new Random(0);
    for (int i = 0; i < 10000; i++) {
        TreeSet<String> marked = new TreeSet<String>();
        TreeSet<String> all = new TreeSet<String>();
        TreeSet<String> diff = new TreeSet<String>();
        int size = r.nextInt(5);
        for (int a = 0; a < size; a++) {
            marked.add("" + r.nextInt(10));
        }/*from   ww  w . j  av  a2  s .  co  m*/
        size = r.nextInt(5);
        for (int a = 0; a < size; a++) {
            all.add("" + r.nextInt(10));
        }
        diff.addAll(all);
        diff.removeAll(marked);
        String m = marked.toString().replaceAll("[ \\[\\]]", "");
        String a = all.toString().replaceAll("[ \\[\\]]", "");
        assertDiff(m, a, new ArrayList<String>(diff));
    }
}

From source file:org.apache.ranger.rest.ServiceRESTUtil.java

static private List<RangerPolicy.RangerPolicyItem> mergePolicyItems(
        List<RangerPolicy.RangerPolicyItem> policyItems) {
    List<RangerPolicy.RangerPolicyItem> ret = new ArrayList<RangerPolicy.RangerPolicyItem>();

    if (CollectionUtils.isNotEmpty(policyItems)) {
        Map<String, RangerPolicy.RangerPolicyItem> matchedPolicyItems = new HashMap<String, RangerPolicy.RangerPolicyItem>();

        for (RangerPolicy.RangerPolicyItem policyItem : policyItems) {
            if ((CollectionUtils.isEmpty(policyItem.getUsers())
                    && CollectionUtils.isEmpty(policyItem.getGroups()))
                    || (CollectionUtils.isEmpty(policyItem.getAccesses()) && !policyItem.getDelegateAdmin())) {
                continue;
            }//w ww  . ja  va 2 s . c  o m

            if (policyItem.getConditions().size() > 1) {
                ret.add(policyItem);
                continue;
            }
            TreeSet<String> accesses = new TreeSet<String>();

            for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
                accesses.add(access.getType());
            }
            if (policyItem.getDelegateAdmin()) {
                accesses.add("delegateAdmin");
            }

            String allAccessesString = accesses.toString();

            RangerPolicy.RangerPolicyItem matchingPolicyItem = matchedPolicyItems.get(allAccessesString);

            if (matchingPolicyItem != null) {
                addDistinctItems(policyItem.getUsers(), matchingPolicyItem.getUsers());
                addDistinctItems(policyItem.getGroups(), matchingPolicyItem.getGroups());
            } else {
                matchedPolicyItems.put(allAccessesString, policyItem);
            }
        }

        for (Map.Entry<String, RangerPolicy.RangerPolicyItem> entry : matchedPolicyItems.entrySet()) {
            ret.add(entry.getValue());
        }
    }

    return ret;
}

From source file:org.atricore.idbus.capabilities.sso.support.core.util.XmlUtils.java

public static String marshal(Object msg, final String msgQName, final String msgLocalName,
        String[] userPackages) throws Exception {

    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
        String userPackage = userPackages[i];
        contextPackages.add(userPackage);
    }//from   w  w  w.j ava 2s. c o m

    JAXBContext jaxbContext = JAXBUtils.getJAXBContext(contextPackages, constructionType,
            contextPackages.toString(), XmlUtils.class.getClassLoader(), new HashMap<String, Object>());
    Marshaller marshaller = JAXBUtils.getJAXBMarshaller(jaxbContext);

    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);

    Writer writer = new StringWriter();

    // Support XMLDsig
    XMLEventWriter xmlWriter = staxOF.createXMLEventWriter(writer);
    marshaller.marshal(jaxbRequest, xmlWriter);
    xmlWriter.flush();
    JAXBUtils.releaseJAXBMarshaller(jaxbContext, marshaller);

    return writer.toString();

}

From source file:org.atricore.idbus.capabilities.sso.support.core.util.XmlUtils.java

public static Object unmarshal(String msg, String userPackages[]) throws Exception {
    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
        String userPackage = userPackages[i];
        contextPackages.add(userPackage);
    }//w  w w .  j  a  v a 2 s  . c  o m

    JAXBContext jaxbContext = JAXBUtils.getJAXBContext(contextPackages, constructionType,
            contextPackages.toString(), XmlUtils.class.getClassLoader(), new HashMap<String, Object>());
    Unmarshaller unmarshaller = JAXBUtils.getJAXBUnmarshaller(jaxbContext);
    Object o = unmarshaller.unmarshal(staxIF.createXMLEventReader(new StringSource(msg)));
    JAXBUtils.releaseJAXBUnmarshaller(jaxbContext, unmarshaller);

    if (o instanceof JAXBElement)
        return ((JAXBElement) o).getValue();

    return o;

}

From source file:org.atricore.idbus.capabilities.sso.support.core.util.XmlUtils.java

public static Object unmarshal(Document doc, String userPackages[]) throws Exception {

    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
        String userPackage = userPackages[i];
        contextPackages.add(userPackage);
    }/*  www. ja v a2s  .  c o m*/

    JAXBContext jaxbContext = JAXBUtils.getJAXBContext(contextPackages, constructionType,
            contextPackages.toString(), XmlUtils.class.getClassLoader(), new HashMap<String, Object>());
    Unmarshaller unmarshaller = JAXBUtils.getJAXBUnmarshaller(jaxbContext);
    Object o = unmarshaller.unmarshal(doc);
    JAXBUtils.releaseJAXBUnmarshaller(jaxbContext, unmarshaller);

    if (o instanceof JAXBElement)
        return ((JAXBElement) o).getValue();

    return o;
}

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

/**
 * Get a JAXBContext for the class//  w w  w .ja v  a  2s . c om
 *
 * Note: The contextPackage object is used by multiple threads.  It should be considered immutable
 * and not altered by this method.
 *
 * @param contextPackage  Set<Package>
 * @param contructionType (output value that indicates how the context was constructed)
 * @param forceArrays (forces the returned JAXBContext to include the array types)
 * @param cacheKey ClassLoader
 * @return JAXBContext
 * @throws javax.xml.bind.JAXBException
 */
public static JAXBContext getJAXBContext(TreeSet<String> contextPackages,
        Holder<CONSTRUCTION_TYPE> constructionType, boolean forceArrays, String key, ClassLoader cacheKey,
        Map<String, ?> properties) throws JAXBException {
    // JAXBContexts for the same class can be reused and are supposed to be thread-safe
    if (log.isDebugEnabled()) {
        log.debug("Following packages are in this batch of getJAXBContext() :");
        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
    }
    if (JAXBUtilsMonitor.isMonitoring()) {
        JAXBUtilsMonitor.addPackageKey(contextPackages.toString());
    }

    // Get or Create The InnerMap using the package key
    ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);

    if (softRef != null) {
        innerMap = softRef.get();
    }

    if (innerMap == null) {
        synchronized (jaxbMap) {
            softRef = jaxbMap.get(key);
            if (softRef != null) {
                innerMap = softRef.get();
            }
            if (innerMap == null) {
                innerMap = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                softRef = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(innerMap);
                jaxbMap.put(key, softRef);
            }
        }
    }

    // Now get the contextValue using either the classloader key or
    // the current Classloader
    ClassLoader cl = getContextClassLoader();
    JAXBContextValue contextValue = null;
    if (cacheKey != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using supplied classloader to retrieve JAXBContext: " + cacheKey);
        }
        contextValue = innerMap.get(cacheKey);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Using classloader from Thread to retrieve JAXBContext: " + cl);
        }
        contextValue = innerMap.get(cl);
    }

    // If the context value is found, but the caller requested that the JAXBContext
    // contain arrays, then rebuild the JAXBContext value
    if (forceArrays && contextValue != null
            && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
        if (log.isDebugEnabled()) {
            log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                    + "  but the caller requested a JAXBContext "
                    + " that includes arrays.  A new JAXBContext will be built");
        }
        contextValue = null;
    }

    if (contextPackages == null) {
        contextPackages = new TreeSet<String>();
    }
    if (contextValue == null) {
        synchronized (innerMap) {
            // Try to get the contextValue once more since sync was temporarily exited.
            ClassLoader clKey = (cacheKey != null) ? cacheKey : cl;
            contextValue = innerMap.get(clKey);
            adjustPoolSize(innerMap);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                contextValue = null;
            }
            if (contextValue == null) {
                // Create a copy of the contextPackages.  This new TreeSet will
                // contain only the valid contextPackages.
                // Note: The original contextPackage set is accessed by multiple
                // threads and should not be altered.

                TreeSet<String> validContextPackages = new TreeSet<String>(contextPackages);

                List<String> classRefs = pruneDirectives(validContextPackages);

                int numPackages = validContextPackages.size();

                contextValue = createJAXBContextValue(validContextPackages, clKey, forceArrays, properties,
                        classRefs);

                synchronized (jaxbMap) {
                    // Add the context value with the original package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map1 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef1 = jaxbMap.get(key);
                    if (softRef1 != null) {
                        map1 = softRef1.get();
                    }
                    if (map1 == null) {
                        map1 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef1 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map1);
                        jaxbMap.put(key, softRef1);
                    }
                    map1.put(clKey, contextValue);

                    String validPackagesKey = validContextPackages.toString();

                    // Add the context value with the new package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map2 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef2 = jaxbMap
                            .get(validPackagesKey);
                    if (softRef2 != null) {
                        map2 = softRef2.get();
                    }
                    if (map2 == null) {
                        map2 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef2 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map2);
                        jaxbMap.put(validPackagesKey, softRef2);
                    }
                    map2.put(clKey, contextValue);

                    if (log.isDebugEnabled()) {
                        log.debug("JAXBContext [created] for " + key);
                        log.debug("JAXBContext also stored by the list of valid packages:" + validPackagesKey);
                    }
                }
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("JAXBContext [from pool] for " + key);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("JAXBContext constructionType= " + contextValue.constructionType);
        log.debug("JAXBContextValue = " + JavaUtils.getObjectIdentity(contextValue));
        log.debug("JAXBContext = " + JavaUtils.getObjectIdentity(contextValue.jaxbContext));
    }
    constructionType.value = contextValue.constructionType;
    return contextValue.jaxbContext;
}

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader//from ww w  .j  a v a 2s .c o m
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws javax.xml.bind.JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH:
    //    Pros: preferred way of doing this.
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list.
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}