Search in sources :

Example 56 with WeakHashMap

use of java.util.WeakHashMap in project ofbiz-framework by apache.

the class XmlSerializer method deserializeSingle.

public static Object deserializeSingle(Element element, Delegator delegator) throws SerializeException {
    String tagName = element.getLocalName();
    if ("null".equals(tagName)) {
        return null;
    }
    if (tagName.startsWith("std-")) {
        // - Standard Objects -
        if ("std-String".equals(tagName)) {
            return element.getAttribute("value");
        } else if ("std-Integer".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return Integer.valueOf(valStr);
        } else if ("std-Long".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return Long.valueOf(valStr);
        } else if ("std-Float".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return Float.valueOf(valStr);
        } else if ("std-Double".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return Double.valueOf(valStr);
        } else if ("std-BigDecimal".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return new BigDecimal(valStr);
        } else if ("std-Boolean".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return Boolean.valueOf(valStr);
        } else if ("std-Locale".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return UtilMisc.parseLocale(valStr);
        } else if ("std-Date".equals(tagName)) {
            String valStr = element.getAttribute("value");
            DateFormat formatter = getDateFormat();
            java.util.Date value = null;
            try {
                synchronized (formatter) {
                    value = formatter.parse(valStr);
                }
            } catch (ParseException e) {
                throw new SerializeException("Could not parse date String: " + valStr, e);
            }
            return value;
        }
    } else if (tagName.startsWith("sql-")) {
        // - SQL Objects -
        if ("sql-Timestamp".equals(tagName)) {
            String valStr = element.getAttribute("value");
            /*
                 * sql-Timestamp is defined as xsd:dateTime in ModelService.getTypes(),
                 * so try to parse the value as xsd:dateTime first.
                 * Fallback is java.sql.Timestamp because it has been this way all the time.
                 */
            try {
                Calendar cal = DatatypeConverter.parseDate(valStr);
                return new java.sql.Timestamp(cal.getTimeInMillis());
            } catch (Exception e) {
                Debug.logWarning("sql-Timestamp does not conform to XML Schema definition, try java.sql.Timestamp format", module);
                return java.sql.Timestamp.valueOf(valStr);
            }
        } else if ("sql-Date".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return java.sql.Date.valueOf(valStr);
        } else if ("sql-Time".equals(tagName)) {
            String valStr = element.getAttribute("value");
            return java.sql.Time.valueOf(valStr);
        }
    } else if (tagName.startsWith("col-")) {
        // - Collections -
        Collection<Object> value = null;
        if ("col-ArrayList".equals(tagName)) {
            value = new ArrayList<>();
        } else if ("col-LinkedList".equals(tagName)) {
            value = new LinkedList<>();
        } else if ("col-Stack".equals(tagName)) {
            value = new Stack<>();
        } else if ("col-Vector".equals(tagName)) {
            value = new Vector<>();
        } else if ("col-TreeSet".equals(tagName)) {
            value = new TreeSet<>();
        } else if ("col-HashSet".equals(tagName)) {
            value = new HashSet<>();
        } else if ("col-Collection".equals(tagName)) {
            value = new LinkedList<>();
        }
        if (value == null) {
            return deserializeCustom(element);
        }
        Node curChild = element.getFirstChild();
        while (curChild != null) {
            if (curChild.getNodeType() == Node.ELEMENT_NODE) {
                value.add(deserializeSingle((Element) curChild, delegator));
            }
            curChild = curChild.getNextSibling();
        }
        return value;
    } else if (tagName.startsWith("map-")) {
        // - Maps -
        Map<Object, Object> value = null;
        if ("map-HashMap".equals(tagName)) {
            value = new HashMap<>();
        } else if ("map-Properties".equals(tagName)) {
            value = new Properties();
        } else if ("map-Hashtable".equals(tagName)) {
            value = new Hashtable<>();
        } else if ("map-WeakHashMap".equals(tagName)) {
            value = new WeakHashMap<>();
        } else if ("map-TreeMap".equals(tagName)) {
            value = new TreeMap<>();
        } else if ("map-Map".equals(tagName)) {
            value = new HashMap<>();
        }
        if (value == null) {
            return deserializeCustom(element);
        }
        Node curChild = element.getFirstChild();
        while (curChild != null) {
            if (curChild.getNodeType() == Node.ELEMENT_NODE) {
                Element curElement = (Element) curChild;
                if ("map-Entry".equals(curElement.getLocalName())) {
                    Element mapKeyElement = UtilXml.firstChildElement(curElement, "map-Key");
                    Element keyElement = null;
                    Node tempNode = mapKeyElement.getFirstChild();
                    while (tempNode != null) {
                        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                            keyElement = (Element) tempNode;
                            break;
                        }
                        tempNode = tempNode.getNextSibling();
                    }
                    if (keyElement == null) {
                        throw new SerializeException("Could not find an element under the map-Key");
                    }
                    Element mapValueElement = UtilXml.firstChildElement(curElement, "map-Value");
                    Element valueElement = null;
                    tempNode = mapValueElement.getFirstChild();
                    while (tempNode != null) {
                        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                            valueElement = (Element) tempNode;
                            break;
                        }
                        tempNode = tempNode.getNextSibling();
                    }
                    if (valueElement == null) {
                        throw new SerializeException("Could not find an element under the map-Value");
                    }
                    value.put(deserializeSingle(keyElement, delegator), deserializeSingle(valueElement, delegator));
                }
            }
            curChild = curChild.getNextSibling();
        }
        return value;
    } else if (tagName.startsWith("eepk-")) {
        return delegator.makePK(element);
    } else if (tagName.startsWith("eeval-")) {
        return delegator.makeValue(element);
    }
    return deserializeCustom(element);
}
Also used : HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Properties(java.util.Properties) Vector(java.util.Vector) HashSet(java.util.HashSet) Hashtable(java.util.Hashtable) Calendar(java.util.Calendar) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) ParseException(java.text.ParseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) LinkedList(java.util.LinkedList) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) UtilObject(org.apache.ofbiz.base.util.UtilObject) ParseException(java.text.ParseException) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) TreeMap(java.util.TreeMap)

Example 57 with WeakHashMap

use of java.util.WeakHashMap in project ofbiz-framework by apache.

the class XmlSerializer method serializeSingle.

public static Element serializeSingle(Object object, Document document) throws SerializeException {
    if (document == null) {
        return null;
    }
    if (object == null) {
        return makeElement("null", null, document);
    }
    // - Standard Objects -
    if (object instanceof String) {
        return makeElement("std-String", object, document);
    } else if (object instanceof Integer) {
        return makeElement("std-Integer", object, document);
    } else if (object instanceof Long) {
        return makeElement("std-Long", object, document);
    } else if (object instanceof Float) {
        return makeElement("std-Float", object, document);
    } else if (object instanceof Double) {
        return makeElement("std-Double", object, document);
    } else if (object instanceof Boolean) {
        return makeElement("std-Boolean", object, document);
    } else if (object instanceof Locale) {
        return makeElement("std-Locale", object, document);
    } else if (object instanceof BigDecimal) {
        String stringValue = ((BigDecimal) object).setScale(10, RoundingMode.HALF_UP).toString();
        return makeElement("std-BigDecimal", stringValue, document);
    // - SQL Objects -
    } else if (object instanceof java.sql.Timestamp) {
        String stringValue = object.toString().replace(' ', 'T');
        return makeElement("sql-Timestamp", stringValue, document);
    } else if (object instanceof java.sql.Date) {
        return makeElement("sql-Date", object, document);
    } else if (object instanceof java.sql.Time) {
        return makeElement("sql-Time", object, document);
    } else if (object instanceof java.util.Date) {
        // NOTE: make sure this is AFTER the java.sql date/time objects since they inherit from java.util.Date
        DateFormat formatter = getDateFormat();
        String stringValue = null;
        synchronized (formatter) {
            stringValue = formatter.format((java.util.Date) object);
        }
        return makeElement("std-Date", stringValue, document);
    // return makeElement("std-Date", object, document);
    } else if (object instanceof Collection<?>) {
        // - Collections -
        String elementName = null;
        // these ARE order sensitive; for instance Stack extends Vector, so if Vector were first we would lose the stack part
        if (object instanceof ArrayList<?>) {
            elementName = "col-ArrayList";
        } else if (object instanceof LinkedList<?>) {
            elementName = "col-LinkedList";
        } else if (object instanceof Stack<?>) {
            elementName = "col-Stack";
        } else if (object instanceof Vector<?>) {
            elementName = "col-Vector";
        } else if (object instanceof TreeSet<?>) {
            elementName = "col-TreeSet";
        } else if (object instanceof HashSet<?>) {
            elementName = "col-HashSet";
        } else {
            // no specific type found, do general Collection, will deserialize as LinkedList
            elementName = "col-Collection";
        }
        Collection<?> value = UtilGenerics.cast(object);
        Element element = document.createElement(elementName);
        Iterator<?> iter = value.iterator();
        while (iter.hasNext()) {
            element.appendChild(serializeSingle(iter.next(), document));
        }
        return element;
    } else if (object instanceof GenericPK) {
        // Do GenericEntity objects as a special case, use std XML import/export routines
        GenericPK value = (GenericPK) object;
        return value.makeXmlElement(document, "eepk-");
    } else if (object instanceof GenericValue) {
        GenericValue value = (GenericValue) object;
        return value.makeXmlElement(document, "eeval-");
    } else if (object instanceof Map<?, ?>) {
        // - Maps -
        String elementName = null;
        // these ARE order sensitive; for instance Properties extends Hashtable, so if Hashtable were first we would lose the Properties part
        if (object instanceof HashMap<?, ?>) {
            elementName = "map-HashMap";
        } else if (object instanceof Properties) {
            elementName = "map-Properties";
        } else if (object instanceof Hashtable<?, ?>) {
            elementName = "map-Hashtable";
        } else if (object instanceof WeakHashMap<?, ?>) {
            elementName = "map-WeakHashMap";
        } else if (object instanceof TreeMap<?, ?>) {
            elementName = "map-TreeMap";
        } else {
            // serialize as a simple Map implementation if nothing else applies, these will deserialize as a HashMap
            elementName = "map-Map";
        }
        Element element = document.createElement(elementName);
        Map<?, ?> value = UtilGenerics.cast(object);
        Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
        while (iter.hasNext()) {
            Map.Entry<?, ?> entry = iter.next();
            Element entryElement = document.createElement("map-Entry");
            element.appendChild(entryElement);
            Element key = document.createElement("map-Key");
            entryElement.appendChild(key);
            key.appendChild(serializeSingle(entry.getKey(), document));
            Element mapValue = document.createElement("map-Value");
            entryElement.appendChild(mapValue);
            mapValue.appendChild(serializeSingle(entry.getValue(), document));
        }
        return element;
    }
    return serializeCustom(object, document);
}
Also used : Locale(java.util.Locale) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Properties(java.util.Properties) TreeSet(java.util.TreeSet) Iterator(java.util.Iterator) GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) BigDecimal(java.math.BigDecimal) Stack(java.util.Stack) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) TreeMap(java.util.TreeMap) WeakHashMap(java.util.WeakHashMap)

Example 58 with WeakHashMap

use of java.util.WeakHashMap in project wicket by apache.

the class NonContextual method getCache.

private static ClassMetaCache<NonContextual<?>> getCache() {
    ClassMetaCache<NonContextual<?>> meta = cache.get(BeanManagerLookup.lookup());
    if (meta == null) {
        synchronized (lock) {
            BeanManager manager = BeanManagerLookup.lookup();
            meta = cache.get(manager);
            if (meta == null) {
                meta = new ClassMetaCache<NonContextual<?>>();
                // copy-on-write the cache
                Map<BeanManager, ClassMetaCache<NonContextual<?>>> newCache = new WeakHashMap<BeanManager, ClassMetaCache<NonContextual<?>>>(cache);
                newCache.put(manager, meta);
                cache = Collections.unmodifiableMap(newCache);
            }
        }
    }
    return meta;
}
Also used : ClassMetaCache(org.apache.wicket.util.collections.ClassMetaCache) BeanManager(javax.enterprise.inject.spi.BeanManager) WeakHashMap(java.util.WeakHashMap)

Example 59 with WeakHashMap

use of java.util.WeakHashMap in project prob2 by bendisposto.

the class StateSpace method subscribe.

/**
 * This method lets ProB know that the subscriber is interested in the
 * specified formulas. ProB will then evaluate the formulas for every state
 * (after which the values can be retrieved from the
 * {@link State#getValues()} method).
 *
 * @param subscriber
 *            who is interested in the given formulas
 * @param formulas
 *            that are of interest
 * @return whether or not the subscription was successful (will return true
 *         if at least one of the formulas was successfully subscribed)
 */
public boolean subscribe(final Object subscriber, final Collection<? extends IEvalElement> formulas) {
    boolean success = false;
    List<AbstractCommand> subscribeCmds = new ArrayList<>();
    for (IEvalElement formulaOfInterest : formulas) {
        if (formulaOfInterest instanceof CSP) {
            logger.info("CSP formula {} not subscribed because CSP evaluation is not state based. Use eval method instead", formulaOfInterest.getCode());
        } else {
            if (formulaRegistry.containsKey(formulaOfInterest)) {
                formulaRegistry.get(formulaOfInterest).put(subscriber, new WeakReference<Object>(formulaOfInterest));
                success = true;
            } else {
                WeakHashMap<Object, Object> subscribers = new WeakHashMap<>();
                subscribers.put(subscriber, new WeakReference<Object>(subscriber));
                formulaRegistry.put(formulaOfInterest, subscribers);
                subscribeCmds.add(new RegisterFormulaCommand(formulaOfInterest));
                success = true;
            }
        }
    }
    if (!subscribeCmds.isEmpty()) {
        execute(new ComposedCommand(subscribeCmds));
    }
    return success;
}
Also used : CSP(de.prob.animator.domainobjects.CSP) AbstractCommand(de.prob.animator.command.AbstractCommand) ArrayList(java.util.ArrayList) IEvalElement(de.prob.animator.domainobjects.IEvalElement) RegisterFormulaCommand(de.prob.animator.command.RegisterFormulaCommand) ComposedCommand(de.prob.animator.command.ComposedCommand) WeakHashMap(java.util.WeakHashMap)

Example 60 with WeakHashMap

use of java.util.WeakHashMap in project openj9 by eclipse.

the class J9VMInternals method completeInitialization.

/*
	 * Called by the vm after everything else is initialized.
	 */
private static void completeInitialization() {
    initialized = true;
    exceptions = new WeakHashMap();
    ClassLoader.completeInitialization();
    Thread.currentThread().completeInitialization();
    /*[IF Sidecar19-SE]*/
    if (Boolean.getBoolean("ibm.java9.forceCommonCleanerShutdown")) {
        // $NON-NLS-1$
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            CleanerShutdown.shutdownCleaner();
            ThreadGroup threadGroup = Thread.currentThread().group;
            ThreadGroup parent = threadGroup.getParent();
            while (null != parent) {
                threadGroup = parent;
                parent = threadGroup.getParent();
            }
            ThreadGroup[] threadGroups = new ThreadGroup[threadGroup.numGroups];
            threadGroup.enumerate(threadGroups, false);
            /* non-recursive enumeration */
            for (ThreadGroup tg : threadGroups) {
                if ("InnocuousThreadGroup".equals(tg.getName())) {
                    // $NON-NLS-1$
                    Thread[] threads = new Thread[tg.numThreads];
                    tg.enumerate(threads, false);
                    for (Thread t : threads) {
                        if (t.getName().equals("Common-Cleaner")) {
                            // $NON-NLS-1$
                            t.interrupt();
                            try {
                                /* Need to wait for the Common-Cleaner thread to die before 
			 						 * continuing. If not this will result in a race condition where 
			 						 * the VM might attempt to shutdown before Common-Cleaner has a 
			 						 * chance to stop properly. This will result in an unsuccessful 
			 						 * shutdown and we will not release vm resources. 
			 						 */
                                t.join(3000);
                            /* giving this a 3sec timeout. If it works it should work fairly
				 					  * quickly, 3 seconds should be more than enough time. If it doesn't 
				 					  * work it may block indefinitely. Turning on -verbose:shutdown will
				 					  * let us know if it worked or not
				 					  */
                            } catch (Throwable e) {
                            /* empty block  */
                            }
                        }
                    }
                }
            }
        }));
    }
/*[ENDIF]*/
}
Also used : WeakHashMap(java.util.WeakHashMap)

Aggregations

WeakHashMap (java.util.WeakHashMap)65 Map (java.util.Map)19 HashMap (java.util.HashMap)18 TreeMap (java.util.TreeMap)15 IdentityHashMap (java.util.IdentityHashMap)13 AbstractMap (java.util.AbstractMap)12 LinkedHashMap (java.util.LinkedHashMap)12 ICC_ColorSpace (java.awt.color.ICC_ColorSpace)8 ColorTransform (sun.java2d.cmm.ColorTransform)8 PCMM (sun.java2d.cmm.PCMM)8 Hashtable (java.util.Hashtable)6 AttributedString (java.text.AttributedString)5 Properties (java.util.Properties)5 ArrayList (java.util.ArrayList)4 Comparator (java.util.Comparator)4 List (java.util.List)4 TreeSet (java.util.TreeSet)4 WeakReference (java.lang.ref.WeakReference)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 AttributedCharacterIterator (java.text.AttributedCharacterIterator)3