View onCreateView(View parent, String name, Context context, AttributeSet attrs);

package skin.support.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

public interface LayoutInflaterFactory {

    /**
     * Hook you can supply that is called when inflating from a LayoutInflater.
     * You can use this to customize the tag names available in your XML
     * layout files.
     *
     * @param parent The parent that the created view will be placed
     * in; note that this may be null.
     * @param name Tag name to be inflated.
     * @param context The context the view is being created in.
     * @param attrs Inflation attributes as specified in XML file.
     *
     * @return View Newly created view. Return null for the default
     *         behavior.
     */


package org.switchyard.admin;

import java.util.List;
import javax.xml.namespace.QName;

/**
 * Service
 *
 * Represents an application service exported through the SwitchYard runtime.
 */
public interface Service extends MessageMetricsAware {

    /**
     * @return the name of this service.
     */
    QName getName();

    /**
     * @return the component service promoted by this service.
     */
    ComponentService getPromotedService();

    /**
     * @return the gateway bindings for this service.
     */
    List<Binding> getGateways();

    /**
     * @return the interface implemented by this service.
     */
    String getInterface();

    /**
     * @return the application which exports this service.
     */
    Application getApplication();

    /**
     * @param gatewayName the name of a gateway on this service.
     * @return the named gateway
     */

    /**
     * @return throttling details associated with this service.
     */
    Throttling getThrottling();
}


switch(attribute) {
            case ENGLISH:
                return "en";
            case GERMAN:
                return "de";
        }

package org.javaee7.jpa.listeners;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * The presence of a converter causes injection to fail in Eclipselink 2.7.4
 * @author Patrik Dudits
 */
@Converter(autoApply = true)
public class LanguageConverter implements AttributeConverter<Language, String> {

    @Override
    public String convertToDatabaseColumn(Language attribute) {
        if (attribute == null) {
            return "Unknown";
        }

        return null;
    }

    @Override
    public Language convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        switch(dbData) {
            case "en":
                return Language.ENGLISH;
            case "de":
                return Language.GERMAN;
            default:
                return null;
        }
    }
}


while (reader.hasNext()) {
            CityGML chunk = reader.nextFeature();
            if (chunk instanceof AbstractCityObject) {
                AbstractFeature feature = (AbstractFeature) chunk;
                System.out.println(df.format(new Date()) + "applying stylesheet to feature " + feature.getId());
                // note that the stylesheets are automatically applied - no further action has to be taken
                writer.writeFeatureMember(feature);
            }
        }

/*
 * citygml4j - The Open Source Java API for CityGML
 * http://example.com
 *
 *
 */
package writing_citygml.applying_xslt;

import org.citygml4j.CityGMLContext;
import org.citygml4j.builder.jaxb.CityGMLBuilder;
import org.citygml4j.model.citygml.CityGML;
import org.citygml4j.model.citygml.core.AbstractCityObject;
import org.citygml4j.model.gml.feature.AbstractFeature;
import org.citygml4j.model.module.citygml.CityGMLVersion;
import org.citygml4j.model.module.citygml.CoreModule;
import org.citygml4j.xml.io.CityGMLInputFactory;
import org.citygml4j.xml.io.CityGMLOutputFactory;
import org.citygml4j.xml.io.reader.CityGMLReader;
import org.citygml4j.xml.io.reader.FeatureReadMode;
import org.citygml4j.xml.io.writer.CityModelWriter;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ApplyXSLTWhenWriting {

    public static void main(String[] args) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("[HH:mm:ss] ");
        System.out.println(df.format(new Date()) + "setting up citygml4j context and CityGML builder");
        CityGMLContext ctx = CityGMLContext.getInstance();
        CityGMLBuilder builder = ctx.createCityGMLBuilder();
        // we are parsing one top-level feature after the other
        System.out.println(df.format(new Date()) + "reading CityGML file LOD2_Buildings_v100.gml chunk-wise");
        CityGMLInputFactory in = builder.createCityGMLInputFactory();
        in.setProperty(CityGMLInputFactory.FEATURE_READ_MODE, FeatureReadMode.SPLIT_PER_COLLECTION_MEMBER);
        CityGMLReader reader = in.createCityGMLReader(new File("datasets/LOD2_Buildings_v100.gml"));
        System.out.println(df.format(new Date()) + "creating CityGML 2.0.0 model writer");
        CityGMLOutputFactory out = builder.createCityGMLOutputFactory();
        out.setCityGMLVersion(CityGMLVersion.v2_0_0);
        // you can pass one or more XSLT stylesheets to a CityGMLOutputFactory. The stylesheets
        // are applied before writing the data. If you provide more than one stylesheet,
        // the stylesheets are automatically chained, i.e., the output of the first one is taken as input
        // for the second one, and so on. The order in which you pass the stylesheets to the CityGMLOutputFactory
        // is therefore important.
        // Note: If you parse the document chunk-wise (as in this example), make sure that your XSLT
        // transformations use a local scope that matches the chunks.
        // In this example, the stylesheet formats all coordinate values to have exactly three digits after the
        // the decimal separator.
        System.out.println(df.format(new Date()) + "reading XSLT stylesheet CoordinateFormatter.xsl");
        SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
        Templates stylesheet = factory.newTemplates(new StreamSource(new File("datasets/stylesheets/CoordinateFormatter.xsl")));
        out.setTransformationTemplates(stylesheet);
        // create a CityGML writer
        CityModelWriter writer = out.createCityModelWriter(new File("output/LOD2_Buildings_formatted_v200.gml"), StandardCharsets.UTF_8.name());
        writer.setPrefixes(CityGMLVersion.v2_0_0);
        writer.setDefaultNamespace(CoreModule.v2_0_0);
        writer.setSchemaLocations(CityGMLVersion.v2_0_0);
        writer.setIndentString("  ");
        writer.setHeaderComment("written by citygml4j");
        writer.writeStartDocument();
        // copy the top-level features to the target file

        writer.writeEndDocument();
        reader.close();
        writer.close();
        System.out.println(df.format(new Date()) + "CityGML file LOD2_Buildings_formatted_v200.gml written");
        System.out.println(df.format(new Date()) + "sample citygml4j application successfully finished");
    }
}


while (i.hasNext()) {
                String nextValue = (String) i.next();
                if (nextValue != null) {
                    value.append(nextValue);
                    if (i.hasNext()) {
                        value.append(",");
                    }
                }
            }

package com.sun.enterprise.v3.admin;

import org.jvnet.hk2.config.ConfigBeanProxy;
import org.jvnet.hk2.config.Dom;
import org.glassfish.api.admin.config.Named;
import org.glassfish.api.admin.config.ReferenceContainer;
import java.util.*;
import com.sun.enterprise.config.serverbeans.*;

/**
 * Utility class for all V2 style related dotted names commands.
 *
 * User: Jerome Dochez
 * Date: Jul 9, 2008
 * Time: 11:38:50 PM
 */
public class V2DottedNameSupport {

    public Map<Dom, String> getAllDottedNodes(ConfigBeanProxy proxy) {
        return getAllDottedNodes(Dom.unwrap(proxy));
    }

    public Map<Dom, String> getAllDottedNodes(Dom root) {
        Map<Dom, String> result = new HashMap<Dom, String>();
        getAllSubDottedNames(null, root, result);
        return result;
    }

    protected void getAllSubDottedNames(String prefix, Dom parent, Map<Dom, String> result) {
        Set<String> elementNames = parent.getElementNames();
        for (String childName : elementNames) {
            // by default, it's a collection unless I can find the model for it
            // and ensure this is one or not.
            // not finding the model usually means that it was a "*" element therefore
            // a collection.
            boolean collection = true;
            if (parent.model.findIgnoreCase(childName) != null) {
                // if this is a leaf node, we should really treat it as an attribute.
                if (parent.model.getElement(childName).isLeaf())
                    continue;
                collection = parent.model.getElement(childName).isCollection();
            }
            for (Dom child : parent.nodeElements(childName)) {
                StringBuffer newPrefix = new StringBuffer();
                if (prefix == null) {
                    newPrefix.append(childName);
                } else {
                    newPrefix.append(prefix).append(".").append(childName);
                }
                if (collection) {
                    String name = child.getKey();
                    if (name == null) {
                        name = child.attribute("name");
                    }
                    if (name != null) {
                        newPrefix.append(".").append(name);
                    }
                    // now traverse the child
                    getAllSubDottedNames(newPrefix.toString(), child, result);
                } else {
                    getAllSubDottedNames(newPrefix.toString(), child, result);
                }
            }
        }
        if (prefix != null) {
            result.put(parent, prefix);
        }
    }

    public Map<String, String> getNodeAttributes(Dom node, String prefix) {
        Map<String, String> result = new HashMap<String, String>();
        for (String attrName : node.model.getAttributeNames()) {
            String value = (String) node.model.findIgnoreCase(attrName).get(node, String.class);
            if (value != null) {
                result.put(attrName, value);
            }
        }
        for (String leafName : node.model.getLeafElementNames()) {
            List values = node.leafElements(leafName);
            Iterator i = values.iterator();
            StringBuffer value = new StringBuffer();

            result.put(leafName, value.toString());
        }
        return result;
    }

    public Map<Dom, String> getMatchingNodes(Map<Dom, String> nodes, String pattern) {
        Map<Dom, String> result = new HashMap<Dom, String>();
        for (Map.Entry<Dom, String> entry : nodes.entrySet()) {
            String dottedName = entry.getValue();
            if (matches(dottedName, pattern)) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

    public boolean matches(String dottedName, String pattern) {
        StringTokenizer patternToken = new StringTokenizer(pattern, ".");
        if (patternToken.hasMoreElements()) {
            String token = (String) patternToken.nextElement();
            if (token.startsWith("*")) {
                // let's find the end delimiter...
                if (token.length() > 1) {
                    String delim = token.substring(1);
                    if (dottedName.indexOf(delim) != -1) {
                        // found the delimiter...
                        // we have to be careful, the delimiter can be at the end of the string...
                        String remaining = dottedName.substring(dottedName.indexOf(delim) + delim.length());
                        if (remaining.length() == 0) {
                            // no more dotted names, better be done with the pattern
                            return !patternToken.hasMoreElements();
                        } else {
                            remaining = remaining.substring(1);
                        }
                        if (patternToken.hasMoreElements()) {
                            return matches(remaining, pattern.substring(token.length() + 1));
                        } else {
                            return true;
                        }
                    } else {
                        return false;
                    }
                } else {
                    if (patternToken.hasMoreElements()) {
                        // now this can be tricky, seems like the get/set can accept something like *.config
                        // which really means *.*.*.config for the pattern matching mechanism.
                        // so instead of jumping one dotted name token, we may need to jump multiple tokens
                        // until we find the next delimiter, let's find this first.
                        String delim = (String) patternToken.nextElement();
                        if (dottedName.lastIndexOf('.') == -1) {
                            // more pattern, but no more dotted names.
                            // unless the pattern is "*", we don't have a match
                            if (delim.equals("*")) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                        // we are not going to check if the delim is a attribute, it has to be an element name.
                        // we will leave the attribute checking to someone else.
                        if (dottedName.contains("." + delim)) {
                            String remaining = dottedName.substring(dottedName.indexOf("." + delim) + 1);
                            return matches(remaining, pattern.substring(token.length() + 1));
                        } else {
                            return false;
                        }
                    } else {
                        return true;
                    }
                }
            } else {
                String delim;
                if (token.lastIndexOf("*") != -1) {
                    delim = token.substring(0, token.lastIndexOf("*"));
                } else {
                    delim = token;
                }
                if (matchName(dottedName, delim)) {
                    if (patternToken.hasMoreElements()) {
                        if (dottedName.length() <= delim.length() + 1) {
                            if ((pattern.substring(token.length() + 1)).equals("*")) {
                                return true;
                            } else {
                                // end of our name and more pattern to go...
                                return false;
                            }
                        }
                        String remaining = dottedName.substring(delim.length() + 1);
                        return matches(remaining, pattern.substring(token.length() + 1));
                    } else {
                        if (dottedName.length() > delim.length()) {
                            String remaining = dottedName.substring(delim.length() + 1);
                            // if we have more dotted names (with grandchildren elements)
                            // we don't match
                            if (remaining.indexOf('.') != -1) {
                                return false;
                            } else {
                                return true;
                            }
                        } else {
                            // no more pattern, no more dotted name, this is matching.
                            return true;
                        }
                    }
                }
            }
            return false;
        } else {
            // patter is exhausted, only elements one level down should be returned
            return dottedName.indexOf(".") == -1;
        }
    }

    protected boolean matchName(String a, String b) {
        String nextTokenName = a;
        if (a.indexOf('.') != -1) {
            nextTokenName = a.substring(0, a.indexOf('.'));
        }
        if (nextTokenName.equals(b)) {
            return true;
        }
        if (nextTokenName.replace('_', '-').equals(b.replace('_', '-'))) {
            return true;
        }
        return false;
    }

    final static class TreeNode {

        final Dom node;

        final String name;

        final String relativeName;

        public TreeNode(Dom node, String name, String relativeName) {
            this.node = node;
            this.name = name;
            this.relativeName = relativeName;
        }
    }

    public TreeNode[] getAliasedParent(Domain domain, String prefix) {
        // let's get the potential aliased element name
        String name;
        String newPrefix;
        if (prefix.indexOf('.') != -1) {
            name = prefix.substring(0, prefix.indexOf('.'));
            newPrefix = prefix.substring(name.length() + 1);
        } else {
            name = prefix;
            newPrefix = "";
        }
        // check for resources
        if (newPrefix.startsWith("resources")) {
            String relativeName = newPrefix;
            if (newPrefix.indexOf('.') != -1) {
                String str = newPrefix.substring(0, newPrefix.indexOf('.'));
                relativeName = newPrefix.substring(str.length() + 1);
                name += "." + str;
            }
            TreeNode[] result = new TreeNode[1];
            result[0] = new TreeNode(Dom.unwrap(domain.getResources()), name, relativeName);
            return result;
        }
        // server-config
        for (Config config : domain.getConfigs().getConfig()) {
            if (config.getName().equals(name)) {
                return new TreeNode[] { new TreeNode(Dom.unwrap(config), name, newPrefix) };
            }
        }
        // this is getting a bit more complicated, as the name can be the server or cluster name
        // yet, the aliasing should return both the server-config
        // server                                `
        Named[] nodes = getNamedNodes(domain.getServers().getServer(), domain.getConfigs().getConfig(), name);
        if (nodes == null && domain.getClusters() != null) {
            // no luck with server, try cluster.
            nodes = getNamedNodes(domain.getClusters().getCluster(), domain.getConfigs().getConfig(), name);
        }
        if (nodes != null) {
            TreeNode[] result = new TreeNode[nodes.length];
            for (int i = 0; i < nodes.length; i++) {
                result[i] = new TreeNode(Dom.unwrap((ConfigBeanProxy) nodes[i]), name, newPrefix);
            }
            return result;
        }
        return new TreeNode[] { new TreeNode(Dom.unwrap(domain), "", prefix) };
    }

    public Named[] getNamedNodes(List<? extends Named> target, List<? extends Named> references, String name) {
        for (Named config : target) {
            if (config.getName().equals(name)) {
                if (config instanceof ReferenceContainer) {
                    for (Named reference : references) {
                        if (reference.getName().equals(((ReferenceContainer) config).getReference())) {
                            return new Named[] { config, reference };
                        }
                    }
                } else {
                    return new Named[] { config };
                }
            }
        }
        return null;
    }

    public List<Map.Entry> applyOverrideRules(List<Map.Entry> nodes) {
        HashMap<String, Map.Entry> store = new HashMap<String, Map.Entry>();
        for (int i = 0; i < nodes.size(); i++) {
            Map.Entry<Dom, String> currentNode = nodes.get(i);
            Map.Entry<Dom, String> storedNode = store.get(currentNode.getValue());
            if (storedNode == null) {
                store.put(currentNode.getValue(), currentNode);
                continue;
            }
            int storedNodePrecedenceLevel = getPrecedenceLevel(storedNode.getKey());
            int currNodePrecedenceLevel = getPrecedenceLevel(currentNode.getKey());
            if (storedNodePrecedenceLevel < currNodePrecedenceLevel)
                store.put(currentNode.getValue(), currentNode);
        }
        List<Map.Entry> finalList = new ArrayList<Map.Entry>();
        finalList.addAll(store.values());
        store.clear();
        return finalList;
    }

    private int getPrecedenceLevel(Dom entry) {
        String parent = entry.parent().getImplementation();
        int level = 4;
        if (Config.class.getCanonicalName().equals(parent))
            level = 1;
        if (Cluster.class.getCanonicalName().equals(parent))
            level = 2;
        if (Server.class.getCanonicalName().equals(parent))
            level = 3;
        return level;
    }

    public List<Map.Entry> sortNodesByDottedName(Map<Dom, String> nodes) {
        List<Map.Entry> mapEntries = new ArrayList(nodes.entrySet());
        Collections.sort(mapEntries, new Comparator() {

            public int compare(Object o1, Object o2) {
                return (((String) (((Map.Entry) (o1)).getValue())).compareTo((String) (((Map.Entry) (o2)).getValue())));
            }
        });
        return mapEntries;
    }

    public List<org.glassfish.flashlight.datatree.TreeNode> sortTreeNodesByCompletePathName(List<org.glassfish.flashlight.datatree.TreeNode> nodes) {
        Collections.sort(nodes, new Comparator() {

            public int compare(Object o1, Object o2) {
                return (((String) (((org.glassfish.flashlight.datatree.TreeNode) (o1)).getCompletePathName())).compareTo((String) (((org.glassfish.flashlight.datatree.TreeNode) (o2)).getCompletePathName())));
            }
        });
        return nodes;
    }
}


while (!m_open) {
            wait();
        }

package org.apache.felix.httplite.server;

/**
 * This class implements a simple one-shot gate for threads. The gate
 * starts closed and will block any threads that try to wait on it. Once
 * opened, all waiting threads will be released. The gate cannot be reused.
 */
public class ThreadGate {

    private boolean m_open = false;

    /**
     * Open the gate and release any waiting threads.
     */
    public synchronized void open() {
        m_open = true;
        notifyAll();
    }

    /**
     * Wait for the gate to open.
     * @throws java.lang.InterruptedException If the calling thread is interrupted;
     *         the gate still remains closed until opened.
     */
    public synchronized void await() throws InterruptedException {


while (group.getParentThreadGroup() != null) {
                    group = group.getParentThreadGroup();
                }

package org.netbeans.modules.debugger.jpda.ui.models;

import com.sun.jdi.AbsentInformationException;
import java.beans.Customizer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import org.netbeans.api.debugger.Session;
import org.netbeans.api.debugger.jpda.CallStackFrame;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.netbeans.api.debugger.jpda.JPDAThread;
import org.netbeans.api.debugger.jpda.JPDAThreadGroup;
import org.netbeans.modules.debugger.jpda.models.JPDAThreadImpl;
import org.netbeans.modules.debugger.jpda.ui.debugging.DebuggingViewSupportImpl;
import org.netbeans.modules.debugger.jpda.ui.debugging.JPDADVThread;
import org.netbeans.modules.debugger.jpda.ui.debugging.JPDADVThreadGroup;
import org.netbeans.modules.debugger.jpda.ui.models.SourcesModel.AbstractColumn;
import org.netbeans.spi.debugger.ContextProvider;
import org.netbeans.spi.debugger.DebuggerServiceRegistration;
import org.netbeans.spi.debugger.ui.ColumnModelRegistration;
import org.netbeans.spi.debugger.ui.DebuggingView;
import org.netbeans.spi.debugger.ui.DebuggingView.DVThread;
import org.netbeans.spi.debugger.ui.DebuggingView.DVThreadGroup;
import org.netbeans.spi.viewmodel.AsynchronousModelFilter;
import org.netbeans.spi.viewmodel.CachedChildrenTreeModel;
import org.netbeans.spi.viewmodel.ModelEvent;
import org.netbeans.spi.viewmodel.ModelListener;
import org.netbeans.spi.viewmodel.TreeModel;
import org.netbeans.spi.viewmodel.UnknownTypeException;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.RequestProcessor;
import org.openide.util.WeakListeners;

/**
 * @author martin
 */
@DebuggerServiceRegistration(path = "netbeans-JPDASession/DebuggingView", types = { TreeModel.class, AsynchronousModelFilter.class }, position = 10000)
public class DebuggingTreeModel extends CachedChildrenTreeModel {

    public static final String SORT_ALPHABET = "sort.alphabet";

    public static final String SORT_SUSPEND = "sort.suspend";

    public static final String SHOW_SYSTEM_THREADS = "show.systemThreads";

    public static final String SHOW_THREAD_GROUPS = "show.threadGroups";

    public static final String SHOW_SUSPENDED_THREADS_ONLY = "show.suspendedThreadsOnly";

    private static final Set<String> SYSTEM_THREAD_NAMES = new HashSet<String>(Arrays.asList(new String[] { "Reference Handler", "Signal Dispatcher", "Finalizer", "Java2D Disposer", "TimerQueue", "Attach Listener" }));

    private static final Set<String> SYSTEM_MAIN_THREAD_NAMES = new HashSet<String>(Arrays.asList(new String[] { "DestroyJavaVM", "AWT-XAWT", "AWT-Shutdown" }));

    private final JPDADebugger debugger;

    private Listener listener;

    private PreferenceChangeListener prefListener;

    private final PropertyChangeListener debuggerListener = new DebuggerFinishListener();

    private final Collection<ModelListener> listeners = new HashSet<ModelListener>();

    private final Map<JPDAThread, ThreadStateListener> threadStateListeners = new WeakHashMap<JPDAThread, ThreadStateListener>();

    private final Preferences preferences = DebuggingViewSupportImpl.getFilterPreferences();

    private final DebuggingViewSupportImpl dvSupport;

    private final DebuggingMonitorModel.Children monitorChildrenFilter;

    private final TreeModel childrenModelImpl;

    // NOI18N
    private final RequestProcessor RP = new RequestProcessor("Debugging Tree View Refresh", 1);

    public DebuggingTreeModel(ContextProvider lookupProvider) {
        debugger = lookupProvider.lookupFirst(null, JPDADebugger.class);
        dvSupport = (DebuggingViewSupportImpl) lookupProvider.lookupFirst(null, DebuggingView.DVSupport.class);
        debugger.addPropertyChangeListener(JPDADebugger.PROP_STATE, debuggerListener);
        if (debugger.getState() == JPDADebugger.STATE_DISCONNECTED) {
            debugger.removePropertyChangeListener(JPDADebugger.PROP_STATE, debuggerListener);
        } else {
            prefListener = new DebuggingPreferenceChangeListener();
            preferences.addPreferenceChangeListener(prefListener);
        }
        monitorChildrenFilter = new DebuggingMonitorModel.Children(debugger, dvSupport, new ModelListener() {

            @Override
            public void modelChanged(ModelEvent event) {
                fireModelChange(event);
            }
        }, this);
        childrenModelImpl = new ChildrenImplModel();
    }

    @Override
    protected Object[] computeChildren(Object parent) throws UnknownTypeException {
        return monitorChildrenFilter.getChildren(childrenModelImpl, parent, 0, Integer.MAX_VALUE);
    }

    void doRefreshCache(Object node) {
        refreshCache(node);
    }

    private class ChildrenImplModel implements TreeModel {

        @Override
        public Object[] getChildren(Object parent, int from, int to) throws UnknownTypeException {
            if (parent == ROOT) {
                boolean showThreadGroups = preferences.getBoolean(SHOW_THREAD_GROUPS, false);
                if (showThreadGroups) {
                    return getTopLevelThreadsAndGroups();
                } else {
                    JPDAThread[] threads = debugger.getThreadsCollector().getAllThreads().toArray(new JPDAThread[0]);
                    for (JPDAThread t : threads) {
                        watchState(t);
                    }
                    return dvSupport.get(threads);
                }
            }
            if (parent instanceof JPDADVThread) {
                JPDADVThread dvt = (JPDADVThread) parent;
                JPDAThread t = dvt.getKey();
                watchState(t);
                try {
                    return t.getCallStack();
                } catch (AbsentInformationException aiex) {
                    return new Object[0];
                }
            }
            if (parent instanceof JPDADVThreadGroup) {
                JPDAThreadGroup group = ((JPDADVThreadGroup) parent).getKey();
                JPDAThread[] threads = group.getThreads();
                for (JPDAThread t : threads) {
                    watchState(t);
                }
                JPDAThreadGroup[] groups = group.getThreadGroups();
                Object[] result = new Object[threads.length + groups.length];
                System.arraycopy(dvSupport.get(threads), 0, result, 0, threads.length);
                System.arraycopy(dvSupport.get(groups), 0, result, threads.length, groups.length);
                return result;
            }
            if (parent instanceof CallStackFrame) {
                return new Object[0];
            }
            throw new UnknownTypeException(parent.toString());
        }

        @Override
        public int getChildrenCount(Object node) throws UnknownTypeException {
            if (node instanceof CallStackFrame) {
                return 0;
            }
            if (node instanceof JPDADVThread) {
                if (!((JPDADVThread) node).isSuspended()) {
                    return 0;
                }
            }
            return Integer.MAX_VALUE;
        }

        @Override
        public Object getRoot() {
            return ROOT;
        }

        @Override
        public boolean isLeaf(Object node) throws UnknownTypeException {
            if (node instanceof CallStackFrame) {
                return true;
            }
            if (node instanceof JPDADVThread) {
                JPDAThreadImpl t = ((JPDADVThread) node).getKey();
                if (!t.isSuspended() && !t.isMethodInvoking()) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public void addModelListener(ModelListener l) {
        }

        @Override
        public void removeModelListener(ModelListener l) {
        }
    }

    protected Object[] reorder(Object[] nodes) {
        boolean showSystemThreads = preferences.getBoolean(SHOW_SYSTEM_THREADS, false);
        boolean showSuspendedThreadsOnly = preferences.getBoolean(SHOW_SUSPENDED_THREADS_ONLY, false);
        if (!showSystemThreads || showSuspendedThreadsOnly) {
            nodes = filterThreadsAndGroups(nodes, !showSystemThreads, showSuspendedThreadsOnly);
        }
        boolean alphabet = preferences.getBoolean(SORT_ALPHABET, true);
        if (!alphabet) {
            boolean suspend = preferences.getBoolean(SORT_SUSPEND, false);
            if (suspend) {
                Object[] newNodes = new Object[nodes.length];
                System.arraycopy(nodes, 0, newNodes, 0, nodes.length);
                nodes = newNodes;
                Arrays.sort(nodes, new ThreadSuspendComparator());
            }
        } else {
            Object[] newNodes = new Object[nodes.length];
            System.arraycopy(nodes, 0, newNodes, 0, nodes.length);
            nodes = newNodes;
            Arrays.sort(nodes, new ThreadAlphabetComparator());
        }
        return nodes;
    }

    private Object[] filterThreadsAndGroups(Object[] nodes, boolean filterSystem, boolean filterRunning) {
        List list = null;
        JPDAThread currentThread = debugger.getCurrentThread();
        for (Object node : nodes) {
            if (node instanceof JPDADVThread) {
                JPDAThread t = ((JPDADVThread) node).getKey();
                watchState(t);
                if (!t.isSuspended() && (filterSystem && isSystem(t) || (filterRunning && t != currentThread))) {
                    if (list == null) {
                        list = new ArrayList(Arrays.asList(nodes));
                    }
                    list.remove(node);
                }
            } else if (filterRunning && node instanceof JPDADVThreadGroup) {
                if (!containsThread((JPDADVThreadGroup) node, dvSupport.get(currentThread))) {
                    if (list == null) {
                        list = new ArrayList(Arrays.asList(nodes));
                    }
                    list.remove(node);
                }
            }
        }
        return (list != null) ? list.toArray() : nodes;
    }

    private boolean containsThread(DVThreadGroup group, DVThread currentThread) {
        DVThread[] threads = group.getThreads();
        for (int x = 0; x < threads.length; x++) {
            if (threads[x].isSuspended() || threads[x] == currentThread) {
                return true;
            }
        }
        DVThreadGroup[] groups = group.getThreadGroups();
        for (int x = 0; x < groups.length; x++) {
            if (containsThread(groups[x], currentThread)) {
                return true;
            }
        }
        return false;
    }

    private Object[] getTopLevelThreadsAndGroups() {
        List result = new LinkedList();
        Set groups = new HashSet();
        for (JPDAThread thread : debugger.getThreadsCollector().getAllThreads()) {
            JPDAThreadGroup group = thread.getParentThreadGroup();
            if (group == null) {
                result.add(dvSupport.get(thread));
            } else {

groups.add(dvSupport.get(group));
            }
        }
        result.addAll(groups);
        return result.toArray();
    }

    private boolean isSystem(JPDAThread t) {
        if (SYSTEM_THREAD_NAMES.contains(t.getName())) {
            JPDAThreadGroup g = t.getParentThreadGroup();
            return (g != null && "system".equals(g.getName()));
        }
        if (SYSTEM_MAIN_THREAD_NAMES.contains(t.getName())) {
            JPDAThreadGroup g = t.getParentThreadGroup();
            return (g != null && "main".equals(g.getName()));
        }
        return false;
    }

    @Override
    public int getChildrenCount(Object node) throws UnknownTypeException {
        return monitorChildrenFilter.getChildrenCount(childrenModelImpl, node);
    }

    @Override
    public Object getRoot() {
        return ROOT;
    }

    @Override
    public boolean isLeaf(Object node) throws UnknownTypeException {
        return monitorChildrenFilter.isLeaf(childrenModelImpl, node);
    }

    public void addModelListener(ModelListener l) {
        synchronized (listeners) {
            listeners.add(l);
            if (listener == null) {
                listener = new Listener(this, debugger);
            }
        }
    }

    public void removeModelListener(ModelListener l) {
        boolean destroyListeners = false;
        synchronized (listeners) {
            listeners.remove(l);
            if (listeners.size() == 0 && listener != null) {
                listener.destroy();
                listener = null;
                destroyListeners = true;
            }
        }
        if (destroyListeners) {
            destroyThreadStateListeners();
            clearCache();
        }
    }

    private void destroyThreadStateListeners() {
        synchronized (threadStateListeners) {
            for (Map.Entry<JPDAThread, ThreadStateListener> entry : threadStateListeners.entrySet()) {
                PropertyChangeListener pcl = entry.getValue().getThreadPropertyChangeListener();
                ((Customizer) entry.getKey()).removePropertyChangeListener(pcl);
            }
            threadStateListeners.clear();
        }
    }

    private void fireModelChange(ModelEvent me) {
        ModelListener[] ls;
        synchronized (listeners) {
            ls = listeners.toArray(new ModelListener[0]);
        }
        for (int i = 0; i < ls.length; i++) {
            ls[i].modelChanged(me);
        }
    }

    public void fireNodeChanged(Object node) {
        // System.err.println("FIRE node changed ("+node+")");
        try {
            recomputeChildren();
        } catch (UnknownTypeException ex) {
            Exceptions.printStackTrace(ex);
            return;
        }
        ModelEvent ev = new ModelEvent.NodeChanged(this, node);
        fireModelChange(ev);
    }

    private void fireNodeChildrenChanged(Object node) {
        // System.err.println("FIRE node children changed ("+node+")");
        try {
            recomputeChildren();
        } catch (UnknownTypeException ex) {
            Exceptions.printStackTrace(ex);
            return;
        }
        ModelEvent ev = new ModelEvent.NodeChanged(this, node, ModelEvent.NodeChanged.CHILDREN_MASK);
        fireModelChange(ev);
    }

    /**
     * Listens on JPDADebugger state property and updates all threads hierarchy.
     */
    private static class Listener implements PropertyChangeListener {

        private JPDADebugger debugger;

        private WeakReference<DebuggingTreeModel> model;

        // currently waiting / running refresh task
        // there is at most one
        private RequestProcessor.Task task;

        private Set<Object> nodesToRefresh;

        private Preferences preferences = DebuggingViewSupportImpl.getFilterPreferences();

        public Listener(DebuggingTreeModel tm, JPDADebugger debugger) {
            this.debugger = debugger;
            model = new WeakReference<DebuggingTreeModel>(tm);
            debugger.addPropertyChangeListener(this);
        }

        private DebuggingTreeModel getModel() {
            DebuggingTreeModel tm = model.get();
            if (tm == null) {
                destroy();
            }
            return tm;
        }

        void destroy() {
            debugger.removePropertyChangeListener(this);
            synchronized (this) {
                if (task != null) {
                    // cancel old task
                    task.cancel();
                    task = null;
                }
            }
        }

        private RequestProcessor.Task createTask() {
            RequestProcessor rp = null;
            try {
                Session s = (Session) debugger.getClass().getMethod("getSession").invoke(debugger);
                rp = s.lookupFirst(null, RequestProcessor.class);
            } catch (Exception e) {
                Exceptions.printStackTrace(e);
            }
            if (rp == null) {
                rp = RequestProcessor.getDefault();
            }
            RequestProcessor.Task task = rp.create(new RefreshTree());
            return task;
        }

        public void propertyChange(PropertyChangeEvent e) {
            boolean showThreadGroups = preferences.getBoolean(SHOW_THREAD_GROUPS, false);
            JPDAThreadGroup tg = null;
            if (e.getPropertyName() == JPDADebugger.PROP_THREAD_STARTED) {
                JPDAThread t = (JPDAThread) e.getNewValue();
                if (showThreadGroups) {
                    tg = t.getParentThreadGroup();
                }
            } else if (e.getPropertyName() == JPDADebugger.PROP_THREAD_DIED) {
                JPDAThread t = (JPDAThread) e.getOldValue();
                if (showThreadGroups) {
                    tg = t.getParentThreadGroup();
                }
            } else if (e.getPropertyName() == JPDADebugger.PROP_THREAD_GROUP_ADDED) {
                if (showThreadGroups) {
                    tg = (JPDAThreadGroup) e.getNewValue();
                    tg = tg.getParentThreadGroup();
                }
            } else {
                return;
            }
            List nodes = new ArrayList();
            DebuggingTreeModel tm = getModel();
            if (tg == null || !showThreadGroups) {
                nodes.add(ROOT);
            } else if (tg != null && tm != null) {
                do {
                    nodes.add(0, tm.dvSupport.get(tg));
                    tg = tg.getParentThreadGroup();
                } while (tg != null);
                if (showThreadGroups) {
                    nodes.add(0, ROOT);
                }
            }
            synchronized (this) {
                if (task == null) {
                    task = createTask();
                }
                if (nodesToRefresh == null) {
                    nodesToRefresh = new LinkedHashSet<Object>();
                }
                nodesToRefresh.addAll(nodes);
                task.schedule(100);
            }
        }

        private class RefreshTree implements Runnable {

            public RefreshTree() {
            }

            public void run() {
                DebuggingTreeModel tm = getModel();
                if (tm == null)
                    return;
                List nodes;
                synchronized (Listener.this) {
                    nodes = new ArrayList(nodesToRefresh);
                    nodesToRefresh.clear();
                }
                for (Object node : nodes) {
                    tm.fireNodeChildrenChanged(node);
                }
            }
        }
    }

    private void fireThreadStateChanged(JPDAThread node) {
        JPDADVThread dvnode = dvSupport.get(node);
        boolean showThreadGroups = preferences.getBoolean(SHOW_THREAD_GROUPS, false);
        if (preferences.getBoolean(SHOW_SUSPENDED_THREADS_ONLY, false)) {
            Object parent = null;
            if (showThreadGroups) {
                parent = dvSupport.get(node.getParentThreadGroup());
            }
            if (parent == null)
                parent = ROOT;
            fireNodeChildrenChanged(parent);
        } else if (!preferences.getBoolean(SHOW_SYSTEM_THREADS, false) && isSystem(node)) {
            Object parent = null;
            if (showThreadGroups) {
                parent = dvSupport.get(node.getParentThreadGroup());
            }
            if (parent == null)
                parent = ROOT;
            fireNodeChildrenChanged(parent);
        }
        try {
            recomputeChildren(dvnode);
        } catch (UnknownTypeException ex) {
            refreshCache(dvnode);
        }
        ModelEvent event = new ModelEvent.NodeChanged(this, dvnode, ModelEvent.NodeChanged.CHILDREN_MASK | ModelEvent.NodeChanged.EXPANSION_MASK);
        fireModelChange(event);
    }

    private void watchState(JPDAThread t) {
        synchronized (threadStateListeners) {
            if (!threadStateListeners.containsKey(t)) {
                threadStateListeners.put(t, new ThreadStateListener(t));
            }
        }
    }

    private class ThreadStateListener implements PropertyChangeListener {

        private Reference<JPDAThread> tr;

        // currently waiting / running refresh task
        // there is at most one
        private RequestProcessor.Task task;

        private final PropertyChangeListener propertyChangeListener;

        private boolean wasMethodInvoke = false;

        public ThreadStateListener(JPDAThread t) {
            this.tr = new WeakReference(t);
            this.propertyChangeListener = WeakListeners.propertyChange(this, t);
            ((Customizer) t).addPropertyChangeListener(propertyChangeListener);
        }

        public void propertyChange(PropertyChangeEvent evt) {
            if (!evt.getPropertyName().equals(JPDAThread.PROP_SUSPENDED))
                return;
            JPDAThread t = tr.get();
            if (t == null)
                return;
            // Refresh the children of the thread (stack frames) when the thread
            // gets suspended or is resumed
            // When thread is resumed because of a method invocation, do the
            // refresh only if the method takes a long time.
            // NOI18N
            boolean isMethodInvoking = "methodInvoke".equals(evt.getPropagationId());
            boolean suspended = t.isSuspended();
            if (suspended || !isMethodInvoking) {
                synchronized (this) {
                    if (task == null) {
                        task = RP.create(new Refresher());
                    }
                    int delay;
                    if (!suspended || wasMethodInvoke) {
                        delay = 1000;
                    } else {
                        delay = 200;
                    }
                    task.schedule(delay);
                }
            }
            wasMethodInvoke = isMethodInvoking;
        }

        PropertyChangeListener getThreadPropertyChangeListener() {
            return propertyChangeListener;
        }

        private class Refresher extends Object implements Runnable {

            public void run() {
                JPDAThread t = tr.get();
                if (t != null) {
                    fireThreadStateChanged(t);
                }
            }
        }
    }

    /**
     * Defines model for one table view column. Can be used together with
     * {@link org.netbeans.spi.viewmodel.TreeModel} for tree table view representation.
     */
    @ColumnModelRegistration(path = "netbeans-JPDASession/DebuggingView", position = 100)
    public static class DefaultDebuggingColumn extends AbstractColumn {

        /**
         * Returns unique ID of this column.
         *
         * @return unique ID of this column
         */
        public String getID() {
            return "DefaultDebuggingColumn";
        }

        /**
         * Returns display name of this column.
         *
         * @return display name of this column
         */
        public String getDisplayName() {
            return NbBundle.getBundle(DebuggingTreeModel.class).getString("CTL_Debugging_Column_Name_Name");
        }

        /**
         * Returns tooltip for given column.
         *
         * @return  tooltip for given node
         */
        @Override
        public String getShortDescription() {
            return NbBundle.getBundle(DebuggingTreeModel.class).getString("CTL_Debugging_Column_Name_Desc");
        }

        /**
         * Returns type of column items.
         *
         * @return type of column items
         */
        public Class getType() {
            return null;
        }
    }

    /**
     * Defines model for one table view column. Can be used together with
     * {@link org.netbeans.spi.viewmodel.TreeModel} for tree table view representation.
     */
    @ColumnModelRegistration(path = "netbeans-JPDASession/DebuggingView", position = 200)
    public static class DebuggingSuspendColumn extends AbstractColumn {

        /**
         * Returns unique ID of this column.
         *
         * @return unique ID of this column
         */
        public String getID() {
            return "suspend";
        }

        /**
         * Returns display name of this column.
         *
         * @return display name of this column
         */
        public String getDisplayName() {
            return NbBundle.getBundle(DebuggingTreeModel.class).getString("CTL_Debugging_Column_Suspend_Name");
        }

        /**
         * Returns type of column items.
         *
         * @return type of column items
         */
        public Class getType() {
            return Boolean.TYPE;
        }

        /**
         * Returns tooltip for given column. Default implementation returns
         * null - do not use tooltip.
         *
         * @return  tooltip for given node or null
         */
        @Override
        public String getShortDescription() {
            return NbBundle.getBundle(DebuggingTreeModel.class).getString("CTL_Debugging_Column_Suspend_Desc");
        }

        /**
         * True if column should be visible by default. Default implementation
         * returns true.
         *
         * @return true if column should be visible by default
         */
        public boolean initiallyVisible() {
            return true;
        }
    }

    private static final class ThreadAlphabetComparator implements Comparator {

        public int compare(Object o1, Object o2) {
            if (o1 instanceof JPDADVThreadGroup) {
                if (o2 instanceof JPDADVThreadGroup) {
                    String tgn1 = ((JPDADVThreadGroup) o1).getName();
                    String tgn2 = ((JPDADVThreadGroup) o2).getName();
                    return java.text.Collator.getInstance().compare(tgn1, tgn2);
                }
                return 1;
            } else if (o2 instanceof JPDADVThreadGroup) {
                return -1;
            }
            if (!(o1 instanceof JPDADVThread) && !(o2 instanceof JPDADVThread)) {
                return 0;
            }
            String n1 = ((JPDADVThread) o1).getName();
            String n2 = ((JPDADVThread) o2).getName();
            return java.text.Collator.getInstance().compare(n1, n2);
        }
    }

    private static final class ThreadSuspendComparator implements Comparator {

        public int compare(Object o1, Object o2) {
            if (o1 instanceof JPDADVThreadGroup) {
                if (o2 instanceof JPDADVThreadGroup) {
                    return 0;
                }
                return 1;
            } else if (o2 instanceof JPDADVThreadGroup) {
                return -1;
            }
            if (!(o1 instanceof JPDADVThread) && !(o2 instanceof JPDADVThread)) {
                return 0;
            }
            boolean s1 = ((JPDADVThread) o1).isSuspended();
            boolean s2 = ((JPDADVThread) o2).isSuspended();
            if (s1 && !s2)
                return -1;
            if (!s1 && s2)
                return +1;
            return 0;
        }
    }

    private final class DebuggingPreferenceChangeListener implements PreferenceChangeListener {

        public void preferenceChange(PreferenceChangeEvent evt) {
            String key = evt.getKey();
            if (SORT_ALPHABET.equals(key) || SORT_SUSPEND.equals(key) || SHOW_SYSTEM_THREADS.equals(key) || SHOW_THREAD_GROUPS.equals(key) || SHOW_SUSPENDED_THREADS_ONLY.equals(key) || DebuggingNodeModel.SHOW_PACKAGE_NAMES.equals(key)) {
                // We have to catch the Throwables, so that the AbstractPreferences.EventDispatchThread
                // is not killed. See http://example.com
                try {
                    fireNodeChanged(ROOT);
                } catch (ThreadDeath td) {
                    throw td;
                } catch (Throwable t) {
                    Exceptions.printStackTrace(t);
                }
            }
        }
    }

    private final class DebuggerFinishListener implements PropertyChangeListener {

        public void propertyChange(PropertyChangeEvent evt) {
            if (JPDADebugger.PROP_STATE.equals(evt.getPropertyName())) {
                if (debugger.getState() == JPDADebugger.STATE_DISCONNECTED) {
                    if (prefListener != null) {
                        try {
                            preferences.removePreferenceChangeListener(prefListener);
                        } catch (IllegalArgumentException e) {
                        }
                    }
                    debugger.removePropertyChangeListener(JPDADebugger.PROP_STATE, this);
                }
            }
        }
    }
}


while (actualItem.getChildCount() > 0) {
            actualItem.getChild(0).remove();
        }

/**
 * OpenKM, Open Document Management System (http://www.openkm.com)
 *

 * No bytes were intentionally harmed during the development of this application.
 *

 */
package com.openkm.frontend.client.widget.categories;

import java.util.Iterator;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTFolder;
import com.openkm.frontend.client.service.OKMFolderService;
import com.openkm.frontend.client.service.OKMFolderServiceAsync;
import com.openkm.frontend.client.service.OKMRepositoryService;
import com.openkm.frontend.client.service.OKMRepositoryServiceAsync;
import com.openkm.frontend.client.util.Util;

/**
 * Folder tree
 *
 * @author jllort
 */
public class FolderSelectTree extends Composite {

    private Tree tree;

    private TreeItem actualItem;

    private final OKMFolderServiceAsync folderService = (OKMFolderServiceAsync) GWT.create(OKMFolderService.class);

    private final OKMRepositoryServiceAsync repositoryService = (OKMRepositoryServiceAsync) GWT.create(OKMRepositoryService.class);

    TreeItem rootItem = new TreeItem();

    /**
     * Folder Tree
     */
    public FolderSelectTree() {
        tree = new Tree();
        rootItem.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", "root_schema", "top"));
        rootItem.setStyleName("okm-TreeItem");
        rootItem.setUserObject(new GWTFolder());
        rootItem.setSelected(true);
        rootItem.setState(true);
        tree.setStyleName("okm-Tree");
        tree.addItem(rootItem);
        tree.addSelectionHandler(new SelectionHandler<TreeItem>() {

            @Override
            public void onSelection(SelectionEvent<TreeItem> event) {
                boolean refresh = true;
                TreeItem item = event.getSelectedItem();
                // Enables or disables move button ( evalues security to move to folder with permissions )
                if (rootItem.equals(item)) {
                    Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.enable(false);
                } else {
                    Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.enable(true);
                }
                // Case that not refreshing tree and file browser ( right click )
                if (actualItem.equals(item)) {
                    refresh = false;
                } else {
                    // Disables actual item because on changing active node by
                    // application this it's not changed automatically
                    if (!actualItem.equals(item)) {
                        actualItem.setSelected(false);
                        actualItem = item;
                    } else {
                        refresh = false;
                    }
                }
                if (refresh) {
                    refresh(true);
                }
            }
        });
        actualItem = tree.getItem(0);
        initWidget(tree);
    }

    /**
     * Resets all tree values
     */
    public void reset() {
        actualItem = rootItem;
        actualItem.setSelected(true);

        getCategories();
    }

    /**
     * Refresh asyncronous subtree branch
     */
    final AsyncCallback<List<GWTFolder>> callbackGetChilds = new AsyncCallback<List<GWTFolder>>() {

        @Override
        public void onSuccess(List<GWTFolder> result) {
            boolean directAdd = true;
            // If has no childs directly add values is permited
            if (actualItem.getChildCount() > 0) {
                directAdd = false;
                // to prevent remote folder remove it disables all tree branch
                // items and after sequentially activate
                hideAllBranch(actualItem);
            }
            // On refreshing not refreshed the actual item values but must
            // ensure that has childs value is consistent
            if (result.isEmpty()) {
                ((GWTFolder) actualItem.getUserObject()).setHasChildren(false);
            } else {
                ((GWTFolder) actualItem.getUserObject()).setHasChildren(true);
            }
            // Ads folders childs if exists
            for (Iterator<GWTFolder> it = result.iterator(); it.hasNext(); ) {
                GWTFolder folder = it.next();
                TreeItem folderItem = new TreeItem();
                folderItem.setHTML(folder.getName());
                folderItem.setUserObject(folder);
                folderItem.setStyleName("okm-TreeItem");
                // If has no childs directly add values is permited, else
                // evalues each node to refresh, remove or add
                if (directAdd) {
                    evaluesFolderIcon(folderItem);
                    actualItem.addItem(folderItem);
                } else {
                    // sequentially activate items and refreshes values
                    addFolder(actualItem, folderItem);
                }
            }
            actualItem.setState(true);
            evaluesFolderIcon(actualItem);
            Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.unsetFlagChilds();
        }

        @Override
        public void onFailure(Throwable caught) {
            Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.unsetFlagChilds();
            Main.get().showError("GetChilds", caught);
        }
    };

    /**
     * Gets asyncronous root node
     */
    final AsyncCallback<GWTFolder> callbackGetCategoriesFolder = new AsyncCallback<GWTFolder>() {

        @Override
        public void onSuccess(GWTFolder result) {
            // Only executes on initalization and the actualItem is root
            // element on initialization
            // We put the id on root
            actualItem.setUserObject(result);
            evaluesFolderIcon(actualItem);
            actualItem.setState(true);
            actualItem.setSelected(true);
            Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.unsetFlagRoot();
            getChilds(result.getPath());
        }

        @Override
        public void onFailure(Throwable caught) {
            Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.unsetFlagRoot();
            Main.get().showError("GetTCategories", caught);
        }
    };

    /**
     * Refresh the folders on a item node
     *
     * @param path The folder path selected to list items
     */
    public void getChilds(String path) {
        Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.setFlagChilds();
        folderService.getChilds(path, false, null, callbackGetChilds);
    }

    /**
     * Gets the root
     */
    public void getCategories() {
        Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.status.setFlagRoot();
        repositoryService.getCategoriesFolder(callbackGetCategoriesFolder);
    }

    /**
     * Refresh the tree node
     */
    public void refresh(boolean reset) {
        String path = ((GWTFolder) actualItem.getUserObject()).getPath();
        getChilds(path);
    }

    /**
     * Hides all items on a brach
     *
     * @param actualItem The actual item active
     */
    public void hideAllBranch(TreeItem actualItem) {
        int i = 0;
        int count = actualItem.getChildCount();
        for (i = 0; i < count; i++) {
            actualItem.getChild(i).setVisible(false);
        }
    }

    /**
     * Adds folders to actual item if not exists or refreshes it values
     *
     * @param actualItem The actual item active
     * @param newItem New item to be added, or refreshed
     */
    public void addFolder(TreeItem actualItem, TreeItem newItem) {
        int i = 0;
        boolean found = false;
        int count = actualItem.getChildCount();
        GWTFolder folder;
        GWTFolder newFolder = (GWTFolder) newItem.getUserObject();
        String folderPath = newFolder.getPath();
        for (i = 0; i < count; i++) {
            folder = (GWTFolder) actualItem.getChild(i).getUserObject();
            // If item is found actualizate values
            if ((folder).getPath().equals(folderPath)) {
                found = true;
                actualItem.getChild(i).setVisible(true);
                actualItem.getChild(i).setUserObject(newFolder);
                evaluesFolderIcon(actualItem.getChild(i));
            }
        }
        if (!found) {
            evaluesFolderIcon(newItem);
            actualItem.addItem(newItem);
        }
    }

    /**
     * Gets the actual Uuid of the selected directory tree
     *
     * @return The actual path of selected directory
     */
    public GWTFolder getCategory() {
        return ((GWTFolder) actualItem.getUserObject());
    }

    /**
     * Evalues actual folder icon to prevent other user interaction with the same folder
     * this ensures icon and object hasChildsValue are consistent
     */
    public void evaluesFolderIcon(TreeItem item) {
        GWTFolder folderItem = (GWTFolder) item.getUserObject();
        preventFolderInconsitences(item);
        // Looks if must change icon on parent if now has no childs and properties with user security atention
        if (folderItem.isHasChildren()) {
            item.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", folderItem.getName(), "top"));
        } else {
            item.setHTML(Util.imageItemHTML("img/menuitem_empty.gif", folderItem.getName(), "top"));
        }
    }

    /**
     * Prevents folder incosistences between server ( multi user deletes folder ) and tree
     * nodes drawed
     *
     * @param item The tree node
     */
    public void preventFolderInconsitences(TreeItem item) {
        GWTFolder folderItem = (GWTFolder) item.getUserObject();
        // Case that must remove all items node
        if (item.getChildCount() > 0 && !folderItem.isHasChildren()) {
            while (item.getChildCount() > 0) {
                item.getChild(0).remove();
            }
        }
        if (item.getChildCount() < 1 && !folderItem.isHasChildren()) {
            folderItem.setHasChildren(false);
        }
    }
}


while (true) {
                    delimiter = text.charAt(start++);
                    if (isDigit(delimiter))
                        buffer.append(delimiter);
                    else
                        break;
                }

/*
    This file is part of RouteConverter.

*/
package slash.common.type;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.TimeZone;
import static java.lang.Character.isDigit;
import static java.lang.Integer.parseInt;
import static java.util.Calendar.*;
import static java.util.GregorianCalendar.AD;
import static java.util.GregorianCalendar.BC;
import static java.util.TimeZone.getTimeZone;
import static slash.common.type.CompactCalendar.UTC;

/**
 * The ISO8601 utility class provides helper methods
 * to deal with date/time formatting using a specific ISO8601-compliant
 * format (see ISO 8601).
 *
 * The currently supported format is:
 *

 *   +-YYY-MM-DDThh:mm:ss[.SSS]TZD
 *

 * where:
 *

 *  +-YYYY = four-digit year with optional sign where values ;lteq; 0 are
 *           denoting years BCE and values > 0 are denoting years CE,
 *           e.g. -0001 denotes the year 2 BCE, 0000 denotes the year 1 BCE,
 *           0001 denotes the year 1 CE, and so on...
 *   MM    = two-digit month (01=January, etc.)
 *   DD    = two-digit day of month (01 through 31)
 *   hh    = two digits of hour (00 through 23) (am/pm NOT allowed)
 *   mm    = two digits of minute (00 through 59)
 *   ss    = two digits of second (00 through 59)
 *   SSS   = optionally: three digits of milliseconds (000 through 999)
 *   TZD   = time zone designator (Z or +hh:mm or -hh:mm)
 *

 *
 * @author Unknown
 */
public class ISO8601 {

    private static final DecimalFormat XX_FORMAT = new DecimalFormat("00");

    private static final DecimalFormat XXX_FORMAT = new DecimalFormat("000");

    private static final DecimalFormat XXXX_FORMAT = new DecimalFormat("0000");

    /**
     * Parses an ISO8601-compliant date/time string.
     *
     * @param text the date/time string to be parsed
     * @return a Calendar, or null if the input could not be parsed
     */
    public static Calendar parseDate(String text) {
        if (text == null)
            return null;
        // check optional leading sign
        char sign;
        int start;
        if (text.startsWith("-")) {
            sign = '-';
            start = 1;
        } else if (text.startsWith("+")) {
            sign = '+';
            start = 1;
        } else {
            // no sign specified, implied '+'
            sign = '+';
            start = 0;
        }
        /*
         * the expected format of the remainder of the string is:
         * YYYY-MM-DDThh:mm:ss
         *
         * note that we cannot use java.text.SimpleDateFormat for
         * parsing because it can't handle years <= 0 and TZD's
         */
        TimeZone timeZone = UTC;
        int year, month, day, hour, minutes, seconds, milliseconds = 0;
        try {
            year = parseInt(text.substring(start, start + 4));
            start += 4;
            if (text.charAt(start) != '-') {
                return null;
            }
            start++;
            month = parseInt(text.substring(start, start + 2));
            start += 2;
            if (text.charAt(start) != '-') {
                return null;
            }
            start++;
            day = parseInt(text.substring(start, start + 2));
            start += 2;
            if (text.charAt(start) != 'T' && text.charAt(start) != ' ') {
                return null;
            }
            start++;
            hour = parseInt(text.substring(start, start + 2));
            start += 2;
            if (text.charAt(start) != ':') {
                return null;
            }
            start++;
            minutes = parseInt(text.substring(start, start + 2));
            start += 2;
            if (text.charAt(start) != ':') {
                return null;
            }
            start++;
            seconds = parseInt(text.substring(start, start + 2));
            start += 2;
        } catch (IndexOutOfBoundsException | NumberFormatException e) {
            return null;
        }
        try {
            char delimiter = text.charAt(start++);
            if (delimiter == '.') {
                StringBuilder buffer = new StringBuilder();

while (buffer.length() < 3) {
                    buffer.append('0');
                }
                milliseconds = parseInt(buffer.toString());
            }
            if (delimiter == 'T')
                delimiter = '+';
            if (delimiter == 'Z') {
                timeZone = UTC;
            } else if (delimiter == '+' || delimiter == '-') {
                String tzString = text.substring(start, start + 5);
                timeZone = getTimeZone("GMT" + delimiter + tzString);
            } else
                return null;
        } catch (IndexOutOfBoundsException | NumberFormatException e) {
            // default timezone is UTC
        }
        // initialize Calendar object
        Calendar calendar = Calendar.getInstance(timeZone);
        calendar.setLenient(false);
        // year and era
        if (sign == '-' || year == 0) {
            // not CE, need to set era (BCE) and adjust year
            calendar.set(YEAR, year + 1);
            calendar.set(ERA, BC);
        } else {
            calendar.set(YEAR, year);
            calendar.set(ERA, AD);
        }
        calendar.set(MONTH, month - 1);
        // day of month
        calendar.set(DAY_OF_MONTH, day);
        // hour
        calendar.set(HOUR_OF_DAY, hour);
        // minute
        calendar.set(MINUTE, minutes);
        // second
        calendar.set(SECOND, seconds);
        // millisecond
        calendar.set(MILLISECOND, milliseconds);
        try {
            /*
             * the following call will trigger an IllegalArgumentException
             * if any of the set values are illegal or out of range
             */
            calendar.getTime();
        } catch (IllegalArgumentException e) {
            return null;
        }
        return calendar;
    }

    /**
     * Formats a {@link CompactCalendar} value into an ISO8601-compliant date/time string.
     *
     * @param calendar the time value to be formatted into a date/time string
     * @return the formatted date/time string
     * @throws IllegalArgumentException if a null argument is passed
     */
    public static String formatDate(CompactCalendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException("argument can not be null");
        }
        return formatDate(calendar.getCalendar(), false);
    }

    /**
     * Formats a {@link Calendar} value into an ISO8601-compliant date/time string.
     *
     * @param calendar            the time value to be formatted into a date/time string
     * @param includeMilliseconds if milli seconds should be included although the spec does not include them
     * @return the formatted date/time string
     * @throws IllegalArgumentException if a null argument is passed
     */
    public static String formatDate(Calendar calendar, boolean includeMilliseconds) {
        if (calendar == null) {
            throw new IllegalArgumentException("argument can not be null");
        }
        // determine era and adjust year if necessary
        int year = calendar.get(YEAR);
        if (calendar.isSet(ERA) && calendar.get(ERA) == BC) {
            /*
             * calculate year using astronomical system:
             * year n BCE => astronomical year -n + 1
             */
            year = 0 - year + 1;
        }
        /*
         * the format of the date/time string is:
         * YYYY-MM-DDThh:mm:ss
         *
         * note that we cannot use java.text.SimpleDateFormat for
         * formatting because it can't handle years <= 0 and TZD's
         */
        StringBuilder buffer = new StringBuilder();
        buffer.append(XXXX_FORMAT.format(year));
        buffer.append('-');
        buffer.append(XX_FORMAT.format(calendar.get(MONTH) + 1));
        buffer.append('-');
        buffer.append(XX_FORMAT.format(calendar.get(DAY_OF_MONTH)));
        buffer.append('T');
        buffer.append(XX_FORMAT.format(calendar.get(HOUR_OF_DAY)));
        buffer.append(':');
        buffer.append(XX_FORMAT.format(calendar.get(MINUTE)));
        buffer.append(':');
        buffer.append(XX_FORMAT.format(calendar.get(SECOND)));
        if (includeMilliseconds) {
            buffer.append('.');
            buffer.append(XXX_FORMAT.format(calendar.get(MILLISECOND)));
        }
        if (calendar.getTimeZone().equals(UTC))
            buffer.append('Z');
        else {
            buffer.append('+');
            int offsetHours = calendar.getTimeZone().getRawOffset() / 1000 / 3600;
            int offsetMinutes = calendar.getTimeZone().getRawOffset() / 1000 / 60 - offsetHours * 60;
            buffer.append(XX_FORMAT.format(offsetHours));
            buffer.append(':');
            buffer.append(XX_FORMAT.format(offsetMinutes));
        }
        return buffer.toString();
    }
}