switch(slider.getOrientation()) {
                    case JSlider.VERTICAL:
                        offset = currentMouseY - upperThumbRect.y;
                        break;
                    case JSlider.HORIZONTAL:
                        offset = currentMouseX - upperThumbRect.x;
                        break;
                }

package slider;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.plaf.basic.BasicSliderUI;

/**
 * UI delegate for the RangeSlider component.  RangeSliderUI paints two thumbs,
 * one for the lower value and one for the upper value.
 * author Ernest Yu
 */
class RangeSliderUI extends BasicSliderUI {

    /**
     * Color of selected range.
     */
    private Color rangeColor = Color.GRAY;

    /**
     * Location and size of thumb for upper value.
     */
    private Rectangle upperThumbRect;

    /**
     * Indicator that determines whether upper thumb is selected.
     */
    private boolean upperThumbSelected;

    /**
     * Indicator that determines whether lower thumb is being dragged.
     */
    private transient boolean lowerDragging;

    /**
     * Indicator that determines whether upper thumb is being dragged.
     */
    private transient boolean upperDragging;

    /**
     * Constructs a RangeSliderUI for the specified slider component.
     *
     * @param b RangeSlider
     */
    public RangeSliderUI(RangeSlider b) {
        super(b);
    }

    /**
     * Installs this UI delegate on the specified component.
     */
    @Override
    public void installUI(JComponent c) {
        upperThumbRect = new Rectangle();
        super.installUI(c);
    }

    /**
     * Creates a listener to handle track events in the specified slider.
     */
    @Override
    protected TrackListener createTrackListener(JSlider slider) {
        return new RangeTrackListener();
    }

    /**
     * Creates a listener to handle change events in the specified slider.
     */
    @Override
    protected ChangeListener createChangeListener(JSlider slider) {
        return new ChangeHandler();
    }

    /**
     * Updates the dimensions for both thumbs.
     */
    @Override
    protected void calculateThumbSize() {
        // Call superclass method for lower thumb size.
        super.calculateThumbSize();
        // Set upper thumb size.
        upperThumbRect.setSize(thumbRect.width, thumbRect.height);
    }

    /**
     * Updates the locations for both thumbs.
     */
    @Override
    protected void calculateThumbLocation() {
        // Call superclass method for lower thumb location.
        super.calculateThumbLocation();
        // Adjust upper value to snap to ticks if necessary.
        if (slider.getSnapToTicks()) {
            int upperValue = slider.getValue() + slider.getExtent();
            int snappedValue = upperValue;
            int majorTickSpacing = slider.getMajorTickSpacing();
            int minorTickSpacing = slider.getMinorTickSpacing();
            int tickSpacing = 0;
            if (minorTickSpacing > 0) {
                tickSpacing = minorTickSpacing;
            } else if (majorTickSpacing > 0) {
                tickSpacing = majorTickSpacing;
            }
            if (tickSpacing != 0) {
                // If it's not on a tick, change the value
                if ((upperValue - slider.getMinimum()) % tickSpacing != 0) {
                    float temp = (float) (upperValue - slider.getMinimum()) / (float) tickSpacing;
                    int whichTick = Math.round(temp);
                    snappedValue = slider.getMinimum() + (whichTick * tickSpacing);
                }
                if (snappedValue != upperValue) {
                    slider.setExtent(snappedValue - slider.getValue());
                }
            }
        }
        // Calculate upper thumb location.  The thumb is centered over its
        // value on the track.
        if (slider.getOrientation() == JSlider.HORIZONTAL) {
            int upperPosition = xPositionForValue(slider.getValue() + slider.getExtent());
            upperThumbRect.x = upperPosition - (upperThumbRect.width / 2);
            upperThumbRect.y = trackRect.y;
        } else {
            int upperPosition = yPositionForValue(slider.getValue() + slider.getExtent());
            upperThumbRect.x = trackRect.x;
            upperThumbRect.y = upperPosition - (upperThumbRect.height / 2);
        }
    }

    /**
     * Returns the size of a thumb.
     */
    @Override
    protected Dimension getThumbSize() {
        return new Dimension(12, 12);
    }

    /**
     * Paints the slider.  The selected thumb is always painted on top of the
     * other thumb.
     */
    @Override
    public void paint(Graphics g, JComponent c) {
        super.paint(g, c);
        Rectangle clipRect = g.getClipBounds();
        if (upperThumbSelected) {
            // Paint lower thumb first, then upper thumb.
            if (clipRect.intersects(thumbRect)) {
                paintLowerThumb(g);
            }
            if (clipRect.intersects(upperThumbRect)) {
                paintUpperThumb(g);
            }
        } else {
            // Paint upper thumb first, then lower thumb.
            if (clipRect.intersects(upperThumbRect)) {
                paintUpperThumb(g);
            }
            if (clipRect.intersects(thumbRect)) {
                paintLowerThumb(g);
            }
        }
    }

    /**
     * Paints the track.
     */
    @Override
    public void paintTrack(Graphics g) {
        // Draw track.
        super.paintTrack(g);
        Rectangle trackBounds = trackRect;
        if (slider.getOrientation() == JSlider.HORIZONTAL) {
            // Determine position of selected range by moving from the middle
            // of one thumb to the other.
            int lowerX = thumbRect.x + (thumbRect.width / 2);
            int upperX = upperThumbRect.x + (upperThumbRect.width / 2);
            // Determine track position.
            int cy = (trackBounds.height / 2) - 2;
            // Save color and shift position.
            Color oldColor = g.getColor();
            g.translate(trackBounds.x, trackBounds.y + cy);
            // Draw selected range.
            g.setColor(rangeColor);
            for (int y = 0; y <= 3; y++) {
                g.drawLine(lowerX - trackBounds.x, y, upperX - trackBounds.x, y);
            }
            // Restore position and color.
            g.translate(-trackBounds.x, -(trackBounds.y + cy));
            g.setColor(oldColor);
        } else {
            // Determine position of selected range by moving from the middle
            // of one thumb to the other.
            int lowerY = thumbRect.x + (thumbRect.width / 2);
            int upperY = upperThumbRect.x + (upperThumbRect.width / 2);
            // Determine track position.
            int cx = (trackBounds.width / 2) - 2;
            // Save color and shift position.
            Color oldColor = g.getColor();
            g.translate(trackBounds.x + cx, trackBounds.y);
            // Draw selected range.
            g.setColor(rangeColor);
            for (int x = 0; x <= 3; x++) {
                g.drawLine(x, lowerY - trackBounds.y, x, upperY - trackBounds.y);
            }
            // Restore position and color.
            g.translate(-(trackBounds.x + cx), -trackBounds.y);
            g.setColor(oldColor);
        }
    }

    /**
     * Overrides superclass method to do nothing.  Thumb painting is handled
     * within the paint() method.
     */
    @Override
    public void paintThumb(Graphics g) {
        // Do nothing.
    }

    /**
     * Paints the thumb for the lower value using the specified graphics object.
     */
    private void paintLowerThumb(Graphics g) {
        Rectangle knobBounds = thumbRect;
        super.paintThumb(g);
    }

    /**
     * Paints the thumb for the upper value using the specified graphics object.
     */
    private void paintUpperThumb(Graphics g) {
        Rectangle tmp = thumbRect;
        thumbRect = upperThumbRect;
        super.paintThumb(g);
        thumbRect = tmp;
    }

    /**
     * Sets the location of the upper thumb, and repaints the slider.  This is
     * called when the upper thumb is dragged to repaint the slider.  The
     * setThumbLocation() method performs the same task for the
     * lower thumb.
     */
    private void setUpperThumbLocation(int x, int y) {
        Rectangle upperUnionRect = new Rectangle();
        upperUnionRect.setBounds(upperThumbRect);
        upperThumbRect.setLocation(x, y);
        SwingUtilities.computeUnion(upperThumbRect.x, upperThumbRect.y, upperThumbRect.width, upperThumbRect.height, upperUnionRect);
        slider.repaint(upperUnionRect.x, upperUnionRect.y, upperUnionRect.width, upperUnionRect.height);
    }

    /**
     * Moves the selected thumb in the specified direction by a block increment.
     * This method is called when the user presses the Page Up or Down keys.
     */
    public void scrollByBlock(int direction) {
        synchronized (slider) {
            int blockIncrement = (slider.getMaximum() - slider.getMinimum()) / 10;
            if (blockIncrement <= 0 && slider.getMaximum() > slider.getMinimum()) {
                blockIncrement = 1;
            }
            int delta = blockIncrement * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL);
            if (upperThumbSelected) {
                int oldValue = ((RangeSlider) slider).getUpperValue();
                ((RangeSlider) slider).setUpperValue(oldValue + delta);
            } else {
                int oldValue = slider.getValue();
                slider.setValue(oldValue + delta);
            }
        }
    }

    /**
     * Moves the selected thumb in the specified direction by a unit increment.
     * This method is called when the user presses one of the arrow keys.
     */
    public void scrollByUnit(int direction) {
        synchronized (slider) {
            int delta = 1 * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL);
            if (upperThumbSelected) {
                int oldValue = ((RangeSlider) slider).getUpperValue();
                ((RangeSlider) slider).setUpperValue(oldValue + delta);
            } else {
                int oldValue = slider.getValue();
                slider.setValue(oldValue + delta);
            }
        }
    }

    /**
     * Listener to handle model change events.  This calculates the thumb
     * locations and repaints the slider if the value change is not caused by
     * dragging a thumb.
     */
    public class ChangeHandler implements ChangeListener {

        public void stateChanged(ChangeEvent arg0) {
            if (!lowerDragging && !upperDragging) {
                calculateThumbLocation();
                slider.repaint();
            }
        }
    }

    /**
     * Listener to handle mouse movements in the slider track.
     */
    public class RangeTrackListener extends TrackListener {

        @Override
        public void mousePressed(MouseEvent e) {
            if (!slider.isEnabled()) {
                return;
            }
            currentMouseX = e.getX();
            currentMouseY = e.getY();
            if (slider.isRequestFocusEnabled()) {
                slider.requestFocus();
            }
            // Determine which thumb is pressed.  If the upper thumb is
            // selected (last one dragged), then check its position first;
            // otherwise check the position of the lower thumb first.
            boolean lowerPressed = false;
            boolean upperPressed = false;
            if (upperThumbSelected) {
                if (upperThumbRect.contains(currentMouseX, currentMouseY)) {
                    upperPressed = true;
                } else if (thumbRect.contains(currentMouseX, currentMouseY)) {
                    lowerPressed = true;
                }
            } else {
                if (thumbRect.contains(currentMouseX, currentMouseY)) {
                    lowerPressed = true;
                } else if (upperThumbRect.contains(currentMouseX, currentMouseY)) {
                    upperPressed = true;
                }
            }
            // Handle lower thumb pressed.
            if (lowerPressed) {
                switch(slider.getOrientation()) {
                    case JSlider.VERTICAL:
                        offset = currentMouseY - thumbRect.y;
                        break;
                    case JSlider.HORIZONTAL:
                        offset = currentMouseX - thumbRect.x;
                        break;
                }
                upperThumbSelected = false;
                lowerDragging = true;
                return;
            }
            lowerDragging = false;
            // Handle upper thumb pressed.
            if (upperPressed) {

                upperThumbSelected = true;
                upperDragging = true;
                return;
            }
            upperDragging = false;
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            lowerDragging = false;
            upperDragging = false;
            slider.setValueIsAdjusting(false);
            super.mouseReleased(e);
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (!slider.isEnabled()) {
                return;
            }
            currentMouseX = e.getX();
            currentMouseY = e.getY();
            if (lowerDragging) {
                slider.setValueIsAdjusting(true);
                moveLowerThumb();
            } else if (upperDragging) {
                slider.setValueIsAdjusting(true);
                moveUpperThumb();
            }
        }

        @Override
        public boolean shouldScroll(int direction) {
            return false;
        }

        /**
         * Moves the location of the lower thumb, and sets its corresponding
         * value in the slider.
         */
        private void moveLowerThumb() {
            int thumbMiddle = 0;
            switch(slider.getOrientation()) {
                case JSlider.VERTICAL:
                    int halfThumbHeight = thumbRect.height / 2;
                    int thumbTop = currentMouseY - offset;
                    int trackTop = trackRect.y;
                    int trackBottom = trackRect.y + (trackRect.height - 1);
                    int vMax = yPositionForValue(slider.getValue() + slider.getExtent());
                    // Apply bounds to thumb position.
                    if (drawInverted()) {
                        trackBottom = vMax;
                    } else {
                        trackTop = vMax;
                    }
                    thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight);
                    thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight);
                    setThumbLocation(thumbRect.x, thumbTop);
                    // Update slider value.
                    thumbMiddle = thumbTop + halfThumbHeight;
                    slider.setValue(valueForYPosition(thumbMiddle));
                    break;
                case JSlider.HORIZONTAL:
                    int halfThumbWidth = thumbRect.width / 2;
                    int thumbLeft = currentMouseX - offset;
                    int trackLeft = trackRect.x;
                    int trackRight = trackRect.x + (trackRect.width - 1);
                    int hMax = xPositionForValue(slider.getValue() + slider.getExtent());
                    // Apply bounds to thumb position.
                    if (drawInverted()) {
                        trackLeft = hMax;
                    } else {
                        trackRight = hMax;
                    }
                    thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
                    thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);
                    setThumbLocation(thumbLeft, thumbRect.y);
                    // Update slider value.
                    thumbMiddle = thumbLeft + halfThumbWidth;
                    slider.setValue(valueForXPosition(thumbMiddle));
                    break;
                default:
                    return;
            }
        }

        /**
         * Moves the location of the upper thumb, and sets its corresponding
         * value in the slider.
         */
        private void moveUpperThumb() {
            int thumbMiddle = 0;
            switch(slider.getOrientation()) {
                case JSlider.VERTICAL:
                    int halfThumbHeight = thumbRect.height / 2;
                    int thumbTop = currentMouseY - offset;
                    int trackTop = trackRect.y;
                    int trackBottom = trackRect.y + (trackRect.height - 1);
                    int vMin = yPositionForValue(slider.getValue());
                    // Apply bounds to thumb position.
                    if (drawInverted()) {
                        trackTop = vMin;
                    } else {
                        trackBottom = vMin;
                    }
                    thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight);
                    thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight);
                    setUpperThumbLocation(thumbRect.x, thumbTop);
                    // Update slider extent.
                    thumbMiddle = thumbTop + halfThumbHeight;
                    slider.setExtent(valueForYPosition(thumbMiddle) - slider.getValue());
                    break;
                case JSlider.HORIZONTAL:
                    int halfThumbWidth = thumbRect.width / 2;
                    int thumbLeft = currentMouseX - offset;
                    int trackLeft = trackRect.x;
                    int trackRight = trackRect.x + (trackRect.width - 1);
                    int hMin = xPositionForValue(slider.getValue());
                    // Apply bounds to thumb position.
                    if (drawInverted()) {
                        trackRight = hMin;
                    } else {
                        trackLeft = hMin;
                    }
                    thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
                    thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);
                    setUpperThumbLocation(thumbLeft, thumbRect.y);
                    // Update slider extent.
                    thumbMiddle = thumbLeft + halfThumbWidth;
                    slider.setExtent(valueForXPosition(thumbMiddle) - slider.getValue());
                    break;
                default:
                    return;
            }
        }
    }
}


public ActiveMQDestination onSend(String topicName);

package org.apache.activemq.transport.mqtt.strategy;

import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.transport.mqtt.MQTTProtocolConverter;
import org.apache.activemq.transport.mqtt.MQTTProtocolException;
import org.apache.activemq.transport.mqtt.MQTTSubscription;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
import org.fusesource.mqtt.codec.CONNECT;

/**
 * Subscription management strategy used to control how MQTT clients
 * subscribe to destination and how messages are addressed in order to
 * arrive on the appropriate destinations.
 */
public interface MQTTSubscriptionStrategy {

    /**
     * Initialize the strategy before first use.
     *
     * @param protocol
     *        the MQTTProtocolConverter that is initializing the strategy
     *
     * @throws MQTTProtocolException if an error occurs during initialization.
     */
    public void initialize(MQTTProtocolConverter protocol) throws MQTTProtocolException;

    /**
     * Allows the strategy to perform any needed actions on client connect
     * prior to the CONNACK frame being sent back such as recovering old
     * subscriptions and performing any clean session actions.
     *
     * @throws MQTTProtocolException if an error occurs while processing the connect actions.
     */
    public void onConnect(CONNECT connect) throws MQTTProtocolException;

    /**
     * Called for each Topic that a client requests to subscribe to.  The strategy needs
     * check each Topic for duplicate subscription requests and change of QoS state.
     *
     * @param topic
     *        the MQTT Topic instance being subscribed to.
     *
     * @return the assigned QoS value given to the new subscription.
     *
     * @throws MQTTProtocolException if an error occurs while processing the subscribe actions.
     */
    public byte onSubscribe(Topic topic) throws MQTTProtocolException;

    /**
     * Called when a new Subscription is being requested.  This method allows the
     * strategy to create a specific type of subscription for the client such as
     * mapping topic subscriptions to Queues etc.
     *
     * @param topicName
     *        the requested Topic name to subscribe to.
     * @param requestedQoS
     *        the QoS level that the client has requested for this subscription.
     *
     * @return the assigned QoS value given to the new subscription
     *
     * @throws MQTTProtocolException if an error occurs while processing the subscribe actions.
     */
    public byte onSubscribe(String topicName, QoS requestedQoS) throws MQTTProtocolException;

    /**
     * Called when a client sends a duplicate subscribe request which should
     * force any retained messages on that topic to be replayed again as though
     * the client had just subscribed for the first time.  The method should
     * not unsubscribe the client as it might miss messages sent while the
     * subscription is being recreated.
     *
     * @param subscription
     *        the MQTTSubscription that contains the subscription state.
     */
    public void onReSubscribe(MQTTSubscription subscription) throws MQTTProtocolException;

    /**
     * Called when a client requests an un-subscribe a previous subscription.
     *
     * @param topicName
     *        the name of the Topic the client wishes to unsubscribe from.
     *
     * @throws MQTTProtocolException if an error occurs during the un-subscribe processing.
     */
    public void onUnSubscribe(String topicName) throws MQTTProtocolException;

    /**
     * Intercepts PUBLISH operations from the client and allows the strategy to map the
     * target destination so that the send operation will land in the destinations that
     * this strategy has mapped the incoming subscribe requests to.
     *
     * @param topicName
     *        the targeted Topic that the client sent the message to.
     *
     * @return an ActiveMQ Topic instance that lands the send in the correct destinations.
     */

    /**
     * Intercepts send operations from the broker and allows the strategy to map the
     * target topic name so that the client sees a valid Topic name.
     *
     * @param destination
     *        the destination that the message was dispatched from
     *
     * @return an Topic name that is valid for the receiving client.
     */
    public String onSend(ActiveMQDestination destination);

    /**
     * Allows the protocol handler to interrogate an destination name to determine if it
     * is equivalent to the MQTT control topic (starts with $).  Since the mapped destinations
     * that the strategy might alter the naming scheme the strategy must provide a way to
     * reverse map and determine if the destination was originally an MQTT control topic.
     *
     * @param destination
     *        the destination to query.
     *
     * @return true if the destination is an MQTT control topic.
     */
    public boolean isControlTopic(ActiveMQDestination destination);

    /**
     * Sets the {@link MQTTProtocolConverter} that is the parent of this strategy object.
     *
     * @param parent
     *        the {@link MQTTProtocolConverter} that owns this strategy.
     */
    public void setProtocolConverter(MQTTProtocolConverter parent);

    /**
     * @return the {@link MQTTProtocolConverter} that owns this strategy.
     */
    public MQTTProtocolConverter getProtocolConverter();

    /**
     * Lookup an {@link MQTTSubscription} instance based on known {@link ConsumerId} value.
     *
     * @param consumer
     *        the consumer ID to lookup.
     *
     * @return the {@link MQTTSubscription} for the consumer or null if no subscription exists.
     */
    public MQTTSubscription getSubscription(ConsumerId consumer);
}


public void setNextSOCKSProxy(String host, int port, String proxy_version);

/*
 * Created on 08-Dec-2004
 * Created by Paul Gardner
 *
 *
 * AELITIS, SAS au capital de 46,603.30 euros
 * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
 *
 */
package com.aelitis.azureus.core.proxy.socks;

/**
 * @author parg
 */
public interface AESocksProxy {

    public static final String PV_4 = "V4";

    public static final String PV_4a = "V4a";

    public static final String PV_5 = "V5";

    public int getPort();

    public AESocksProxyPlugableConnection getDefaultPlugableConnection(AESocksProxyConnection basis);

    /**
     * Set the next SOCKS proxy in a chain - i.e. this socks proxy's default plugable connection
     * will connect onwards using this SOCKS proxy
     *
     * @param host
     * @param port
     */

    public String getNextSOCKSProxyHost();

    public int getNextSOCKSProxyPort();

    public String getNextSOCKSProxyVersion();

    public void setAllowExternalConnections(boolean permit);
}


public void toMap(HashMap<String, String> map, String prefix) {
        this.setParamSimple(map, prefix + "RequestId", this.RequestId);
    }

package com.tencentcloudapi.vpc.v20170312.models;

import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;

public class NotifyRoutesResponse extends AbstractModel {

    /**
     * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     */
    @SerializedName("RequestId")
    @Expose
    private String RequestId;

    /**
     * Get 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     * @return RequestId 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     */
    public String getRequestId() {
        return this.RequestId;
    }

    /**
     * Set 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     * @param RequestId 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     */
    public void setRequestId(String RequestId) {
        this.RequestId = RequestId;
    }

    public NotifyRoutesResponse() {
    }

    /**
     * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
     *       and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
     */
    public NotifyRoutesResponse(NotifyRoutesResponse source) {
        if (source.RequestId != null) {
            this.RequestId = new String(source.RequestId);
        }
    }

    /**
     * Internal implementation, normal users should not use it.
     */


public void setLastTownBlock(WorldCoord lastTownBlock) {
        reset();
        this.lastTownBlock = lastTownBlock;
    }

package com.palmergames.bukkit.towny;

import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.palmergames.bukkit.towny.object.Coord;
import com.palmergames.bukkit.towny.object.TownyWorld;
import com.palmergames.bukkit.towny.object.WorldCoord;
import com.palmergames.bukkit.towny.object.TownyPermission.ActionType;

public class PlayerCache {

    private WorldCoord lastTownBlock;

    private Boolean buildPermission, destroyPermission, switchPermission, itemUsePermission;

    private String blockErrMsg;

    private Location lastLocation;

    // TODO: cache last entity attacked
    public PlayerCache(TownyWorld world, Player player) {
        this(new WorldCoord(world, Coord.parseCoord(player)));
        setLastLocation(player.getLocation());
    }

    public PlayerCache(WorldCoord lastTownBlock) {
        this.setLastTownBlock(lastTownBlock);
    }

    /**
     * Update the cache with new coordinates. Reset the other cached permissions.
     * @param lastTownBlock
     */

    public WorldCoord getLastTownBlock() {
        return lastTownBlock;
    }

    public boolean getCachePermission(ActionType action) throws NullPointerException {
        switch(action) {
            case // BUILD
            BUILD:
                if (buildPermission == null)
                    throw new NullPointerException();
                else
                    return buildPermission;
            case // DESTROY
            DESTROY:
                if (destroyPermission == null)
                    throw new NullPointerException();
                else
                    return destroyPermission;
            case // SWITCH
            SWITCH:
                if (switchPermission == null)
                    throw new NullPointerException();
                else
                    return switchPermission;
            case // ITEM_USE
            ITEM_USE:
                if (itemUsePermission == null)
                    throw new NullPointerException();
                else
                    return itemUsePermission;
            default:
                throw new NullPointerException();
        }
    }

    public void setBuildPermission(boolean buildPermission) {
        this.buildPermission = buildPermission;
    }

    public boolean getBuildPermission() throws NullPointerException {
        if (buildPermission == null)
            throw new NullPointerException();
        else
            return buildPermission;
    }

    public void setDestroyPermission(boolean destroyPermission) {
        this.destroyPermission = destroyPermission;
    }

    public boolean getDestroyPermission() throws NullPointerException {
        if (destroyPermission == null)
            throw new NullPointerException();
        else
            return destroyPermission;
    }

    public void setSwitchPermission(boolean switchPermission) {
        this.switchPermission = switchPermission;
    }

    public boolean getSwitchPermission() throws NullPointerException {
        if (switchPermission == null)
            throw new NullPointerException();
        else
            return switchPermission;
    }

    public boolean updateCoord(WorldCoord pos) {
        if (!getLastTownBlock().equals(pos)) {
            setLastTownBlock(pos);
            return true;
        } else
            return false;
    }

    private void reset() {
        lastTownBlock = null;
        buildPermission = null;
        destroyPermission = null;
        townBlockStatus = null;
        switchPermission = null;
        itemUsePermission = null;
        blockErrMsg = null;
    }

    public enum TownBlockStatus {

        UNKOWN,
        NOT_REGISTERED,
        // In a world untouched by towny.
        OFF_WORLD,
        ADMIN,
        UNCLAIMED_ZONE,
        LOCKED,
        WARZONE,
        OUTSIDER,
        PLOT_OWNER,
        PLOT_FRIEND,
        PLOT_ALLY,
        TOWN_OWNER,
        TOWN_RESIDENT,
        TOWN_ALLY,
        ENEMY
    }

    private TownBlockStatus townBlockStatus = TownBlockStatus.UNKOWN;

    public void setStatus(TownBlockStatus townBlockStatus) {
        this.townBlockStatus = townBlockStatus;
    }

    public TownBlockStatus getStatus() throws NullPointerException {
        if (townBlockStatus == null)
            throw new NullPointerException();
        else
            return townBlockStatus;
    }

    public void setBlockErrMsg(String blockErrMsg) {
        this.blockErrMsg = blockErrMsg;
    }

    public String getBlockErrMsg() {
        String temp = blockErrMsg;
        // Delete error msg after reading it.
        setBlockErrMsg(null);
        return temp;
    }

    public boolean hasBlockErrMsg() {
        return blockErrMsg != null;
    }

    public void setItemUsePermission(Boolean itemUsePermission) {
        this.itemUsePermission = itemUsePermission;
    }

    public Boolean getItemUsePermission() throws NullPointerException {
        if (itemUsePermission == null)
            throw new NullPointerException();
        else
            return itemUsePermission;
    }

    public void setLastLocation(Location lastLocation) {
        this.lastLocation = lastLocation.clone();
    }

    public Location getLastLocation() throws NullPointerException {
        if (lastLocation == null)
            throw new NullPointerException();
        else
            return lastLocation;
    }
}


public void setHttpData(@Nullable HttpData httpData) {
        setBackground(JBColor.background());
        myTabs.forEach(tab -> tab.populateFor(httpData));
        setVisible(httpData != null);
        revalidate();
        repaint();
    }

package com.android.tools.profilers.network.details;

import com.android.tools.adtui.stdui.CommonTabbedPane;
import com.android.tools.adtui.TabularLayout;
import com.android.tools.profilers.CloseButton;
import com.android.tools.profilers.analytics.FeatureTracker;
import com.android.tools.profilers.network.NetworkProfilerStageView;
import com.android.tools.profilers.network.httpdata.HttpData;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.JBEmptyBorder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.android.tools.profilers.ProfilerFonts.STANDARD_FONT;

/**
 * View to display a single network request and its detailed information.
 */
public class ConnectionDetailsView extends JPanel {

    @NotNull
    private final NetworkProfilerStageView myStageView;

    @NotNull
    private final CommonTabbedPane myTabsPanel;

    @NotNull
    private final List<TabContent> myTabs = new ArrayList<>();

    public ConnectionDetailsView(@NotNull NetworkProfilerStageView stageView) {
        super(new BorderLayout());
        myStageView = stageView;
        // Create 2x2 pane
        // Fit _ _
        // *   _ _
        // where main contents span the whole area and a close button fits into the top right
        JPanel rootPanel = new JPanel(new TabularLayout("*,Fit-", "Fit-,*"));
        myTabsPanel = new CommonTabbedPane();
        myTabsPanel.setFont(STANDARD_FONT);
        populateTabs();
        myTabsPanel.addChangeListener(e -> {
            // Repaint required on tab change or else close button sometimes disappears (seen on Mac)
            repaint();
            trackActiveTab();
        });
        CloseButton closeButton = new CloseButton(e -> myStageView.getStage().setSelectedConnection(null));
        // Add a wrapper to move the close button center vertically.
        JPanel closeButtonWrapper = new JPanel(new BorderLayout());
        closeButtonWrapper.add(closeButton, BorderLayout.CENTER);
        closeButtonWrapper.setBorder(new JBEmptyBorder(3, 0, 0, 0));
        rootPanel.add(closeButtonWrapper, new TabularLayout.Constraint(0, 1));
        rootPanel.add(myTabsPanel, new TabularLayout.Constraint(0, 0, 2, 2));
        add(rootPanel);
    }

    private void populateTabs() {
        myTabs.add(new OverviewTabContent(myStageView.getStage().getStudioProfilers().getIdeServices().getFeatureConfig(), myStageView.getIdeComponents(), myStageView.getStage().getConnectionsModel()));
        myTabs.add(new ResponseTabContent(myStageView.getIdeComponents(), myStageView.getStage().getConnectionsModel()));
        myTabs.add(new RequestTabContent(myStageView.getIdeComponents(), myStageView.getStage().getConnectionsModel()));
        myTabs.add(new CallStackTabContent(myStageView.getStage().getConnectionsModel(), myStageView.getIdeComponents().createStackView(myStageView.getStage().getStackTraceModel())));
        for (TabContent tab : myTabs) {
            myTabsPanel.addTab(tab.getTitle(), tab.getIcon(), tab.getComponent());
        }
    }

    private void trackActiveTab() {
        Optional<TabContent> selected = myTabs.stream().filter(t -> t.getComponent() == myTabsPanel.getSelectedComponent()).findFirst();
        if (selected.isPresent()) {
            FeatureTracker featureTracker = myStageView.getStage().getStudioProfilers().getIdeServices().getFeatureTracker();
            selected.get().trackWith(featureTracker);
        }
    }

    /**
     * Updates the view to show given data. If {@code httpData} is {@code null}, this clears the view
     * and closes it.
     */

    @NotNull
    @VisibleForTesting
    List<TabContent> getTabs() {
        return myTabs;
    }
}


package com.edgenius.wiki.service;

import java.util.List;
import com.edgenius.core.Constants.REGISTER_METHOD;
import com.edgenius.core.model.User;
import com.edgenius.core.repository.FileNode;
import com.edgenius.wiki.gwt.client.model.RenderMarkupModel;
import com.edgenius.wiki.model.ActivityLog;
import com.edgenius.wiki.model.Page;
import com.edgenius.wiki.model.PageComment;
import com.edgenius.wiki.model.Space;

/**
 * @author Dapeng.Ni
 */
public interface ActivityLogService {

    String SERVICE_NAME = "activityLog";

    /**
     * Get specified user's activities, i.e., the user is activity creator.
     * @param startUid is the ActivityLog.uid, return list has uid less than it. Return from latest activity if it is less or equal to zero.
     * @param count
     * @param user
     * @return
     */
    List<ActivityLog> getUserActivities(int startUid, int count, User user, User viewer);

    /**
     * Get all activities.
     * @param startUid
     * @param count
     * @param viewer
     * @return
     */
    List<ActivityLog> getActivities(int startUid, int count, User viewer);

    void logPageSaved(Page page);

    void logPageRestored(Page page);

    void logPageRemoved(Page page, boolean permanent, User activityRequester);

    void logPageCopied(Page src, Page tgt);

    void logPageMoved(Page src, Page tgt);

    void logPageReverted(Page page, int version);

    void logComment(PageComment comment);

    void logAttachmentUploaded(String spaceUname, String pageTitle, User creator, List<FileNode> attachment);

    void logAttachmentRemoved(String spaceUname, String pageTitle, User creator, FileNode attachment);

    void logSpaceCreated(Space space);

    void logSpaceRemoved(Space space, User requestor, boolean permanent);

    void logSpaceRestored(String spaceUname, String name, User user);

    /**
     * @param user
     * @param registerStatus signup or approval. If null, treat as sign-up is approved.
     */
    void logUserSignup(User user, REGISTER_METHOD registerStatus);

    void logUserStatusUpdate(User user);

    void logUserFollowing(User user, User follower);

    void logUserUnFollowing(User user, User follower);

    /**
     * Please ensure only "SAVE" but not "UPDATE" by activity because of pagination sorted by an incremental UID.
     * Update won't impact the UID then may reflect wrong pagination list.
     *
     * @param activity
     */
    void save(ActivityLog activity);

    List<ActivityLog> getByTarget(int typeCode, int subTypeCode, int tgtResourceType, String tgtResourceName);

    List<ActivityLog> getBySource(int typeCode, int subTypeCode, int srcResourceType, String srcResourceName);

    void purgeActivityLog(int days);

    /**
     * @param list
     * @return
     */


boolean select(Object object, DBPPropertyDescriptor property);

/*
 * DBeaver - Universal Database Manager
 *
 */
package org.jkiss.dbeaver.runtime.properties;

import org.jkiss.dbeaver.model.preferences.DBPPropertyDescriptor;

/**
 * Interface for filters. Can accept or reject items.
 */
public interface IPropertyFilter {

    /**
     * Determines if the given property passes this filter.
     */


static NamedNodeMap emptyNamedNodeMap() {
        return INSTANCE;
    }

package com.hazelcast.internal.config.yaml;

import com.hazelcast.internal.yaml.YamlMapping;
import com.hazelcast.internal.yaml.YamlNode;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Empty {@link NamedNodeMap} implementation. Used by {@link YamlElementAdapter#getAttributes()}
 * when wrapping {@link YamlNode}s other than {@link YamlMapping}.
 */
final class EmptyNamedNodeMap implements NamedNodeMap {

    private static final NamedNodeMap INSTANCE = new EmptyNamedNodeMap();

    private EmptyNamedNodeMap() {
    }

    @Override
    public Node getNamedItem(String name) {
        return null;
    }

    @Override
    public Node setNamedItem(Node arg) throws DOMException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Node removeNamedItem(String name) throws DOMException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Node item(int index) {
        return null;
    }

    @Override
    public int getLength() {
        return 0;
    }

    @Override
    public Node getNamedItemNS(String namespaceURI, String localName) throws DOMException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Node setNamedItemNS(Node arg) throws DOMException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns the singleton instance of this class
     *
     * @return an empty {@link NamedNodeMap}
     * @see #INSTANCE
     */


List<ColumnInfo> listByTableName(@Param("tableName") String tableName);

package com.fisher.gen.mapper;

import com.fisher.gen.model.entity.ColumnInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface ColumnInfoMapper {

    /**
     * 查询单个表的列详细信息
     * @param tableName
     * @return
     */


switch(xmlTag) {
                        case WARNUNGEN_GEMEINDEN:
                            if (!gemeindeData.isTest() && !gemeindeData.isCancel()) {
                                cityData.add(gemeindeData);
                            }
                            insideGemeinde = false;
                            break;
                        default:
                            break;
                    }

package org.openhab.binding.dwdunwetter.internal.dto;

import java.io.StringReader;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import org.openhab.core.cache.ExpiringCache;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.unit.ImperialUnits;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Contains the Data for all retrieved warnings for one thing.
 *
 * @author Martin Koehler - Initial contribution
 */
public class DwdWarningsData {

    private static final int MIN_REFRESH_WAIT_MINUTES = 5;

    private final Logger logger = LoggerFactory.getLogger(DwdWarningsData.class);

    private List<DwdWarningData> cityData = new LinkedList<>();

    private DwdWarningCache cache = new DwdWarningCache();

    private ExpiringCache<String> dataAccessCached;

    private DateTimeFormatter formatter = new DateTimeFormatterBuilder().// date/time
    append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).optionalStart().appendOffset("+HH:MM", "+00:00").optionalEnd().optionalStart().appendOffset("+HHMM", "+0000").optionalEnd().// offset (hh - "Z" when it's zero)
    optionalStart().appendOffset("+HH", "Z").optionalEnd().// create formatter
    toFormatter();

    public DwdWarningsData(String cellId) {
        DwdWarningDataAccess dataAccess = new DwdWarningDataAccess();
        this.dataAccessCached = new ExpiringCache<>(Duration.ofMinutes(MIN_REFRESH_WAIT_MINUTES), () -> dataAccess.getDataFromEndpoint(cellId));
    }

    private String getValue(XMLEventReader eventReader) throws XMLStreamException {
        XMLEvent event = eventReader.nextEvent();
        return event.asCharacters().getData();
    }

    private BigDecimal getBigDecimalValue(XMLEventReader eventReader) throws XMLStreamException {
        XMLEvent event = eventReader.nextEvent();
        try {
            return new BigDecimal(event.asCharacters().getData());
        } catch (NumberFormatException e) {
            logger.debug("Exception while parsing a BigDecimal", e);
            return BigDecimal.ZERO;
        }
    }

    private Instant getTimestampValue(XMLEventReader eventReader) throws XMLStreamException {
        XMLEvent event = eventReader.nextEvent();
        String dateTimeString = event.asCharacters().getData();
        try {
            OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString, formatter);
            return dateTime.toInstant();
        } catch (DateTimeParseException e) {
            logger.debug("Exception while parsing a DateTime", e);
            return Instant.MIN;
        }
    }

    /**
     * Refreshes the Warnings Data
     */
    public boolean refresh() {
        String rawData = dataAccessCached.getValue();
        if (rawData == null || rawData.isEmpty()) {
            logger.debug("No Data from Endpoint");
            return false;
        }
        cityData.clear();
        try {
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(rawData));
            XMLEventReader eventReader = inputFactory.createXMLEventReader(reader);
            DwdWarningData gemeindeData = new DwdWarningData();
            boolean insideGemeinde = false;
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                if (!insideGemeinde && event.isStartElement()) {
                    DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart());
                    switch(xmlTag) {
                        case WARNUNGEN_GEMEINDEN:
                            gemeindeData = new DwdWarningData();
                            insideGemeinde = true;
                            break;
                        default:
                            break;
                    }
                } else if (insideGemeinde && event.isStartElement()) {
                    DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart());
                    switch(xmlTag) {
                        case SEVERITY:
                            gemeindeData.setSeverity(Severity.getSeverity(getValue(eventReader)));
                            break;
                        case DESCRIPTION:
                            gemeindeData.setDescription(getValue(eventReader));
                            break;
                        case EFFECTIVE:
                            gemeindeData.setEffective(getTimestampValue(eventReader));
                            break;
                        case EXPIRES:
                            gemeindeData.setExpires(getTimestampValue(eventReader));
                            break;
                        case EVENT:
                            gemeindeData.setEvent(getValue(eventReader));
                            break;
                        case STATUS:
                            gemeindeData.setStatus(getValue(eventReader));
                            break;
                        case MSGTYPE:
                            gemeindeData.setMsgType(getValue(eventReader));
                            break;
                        case HEADLINE:
                            gemeindeData.setHeadline(getValue(eventReader));
                            break;
                        case ONSET:
                            gemeindeData.setOnset(getTimestampValue(eventReader));
                            break;
                        case ALTITUDE:
                            gemeindeData.setAltitude(getBigDecimalValue(eventReader));
                            break;
                        case CEILING:
                            gemeindeData.setCeiling(getBigDecimalValue(eventReader));
                            break;
                        case IDENTIFIER:
                            gemeindeData.setId(getValue(eventReader));
                            break;
                        case INSTRUCTION:
                            gemeindeData.setInstruction(getValue(eventReader));
                            break;
                        case URGENCY:
                            gemeindeData.setUrgency(Urgency.getUrgency(getValue(eventReader)));
                            break;
                        default:
                            break;
                    }
                } else if (insideGemeinde && event.isEndElement()) {
                    DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asEndElement().getName().getLocalPart());

                }
            }
        } catch (XMLStreamException e) {
            logger.warn("Exception occurred while parsing the XML response: {}", e.getMessage());
            logger.debug("Exception trace", e);
            return false;
        }
        Collections.sort(cityData, new SeverityComparator());
        return true;
    }

    private DwdWarningData getGemeindeData(int number) {
        return cityData.size() <= number ? null : cityData.get(number);
    }

    public State getWarning(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? OnOffType.OFF : OnOffType.ON;
    }

    public State getSeverity(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getSeverity().getText());
    }

    public State getDescription(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getDescription());
    }

    public State getEffective(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return UnDefType.UNDEF;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getEffective(), ZoneId.systemDefault());
        return new DateTimeType(zoned);
    }

    public State getExpires(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return UnDefType.UNDEF;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getExpires(), ZoneId.systemDefault());
        return new DateTimeType(zoned);
    }

    public State getOnset(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return UnDefType.UNDEF;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getOnset(), ZoneId.systemDefault());
        return new DateTimeType(zoned);
    }

    public State getEvent(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getEvent());
    }

    public State getHeadline(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getHeadline());
    }

    public State getAltitude(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return UnDefType.UNDEF;
        }
        return new QuantityType<>(data.getAltitude(), ImperialUnits.FOOT);
    }

    public State getCeiling(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return UnDefType.UNDEF;
        }
        return new QuantityType<>(data.getCeiling(), ImperialUnits.FOOT);
    }

    public State getInstruction(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getInstruction());
    }

    public State getUrgency(int number) {
        DwdWarningData data = getGemeindeData(number);
        return data == null ? UnDefType.UNDEF : StringType.valueOf(data.getUrgency().getText());
    }

    public boolean isNew(int number) {
        DwdWarningData data = getGemeindeData(number);
        if (data == null) {
            return false;
        }
        return cache.addEntry(data);
    }

    public void updateCache() {
        cache.deleteOldEntries();
    }

    protected void setDataAccess(DwdWarningDataAccess dataAccess) {
        dataAccessCached = new ExpiringCache<>(Duration.ofMinutes(MIN_REFRESH_WAIT_MINUTES), () -> dataAccess.getDataFromEndpoint(""));
    }
}


/* Name.java -- Name build up from different components

*/
package javax.naming;

import java.util.Enumeration;
import java.io.Serializable;

/**
 * Interface descriping a name build up from different components.
 * The components are represented as Strings which are
 * ordered from most significant to least significant. There are methods to
 * get the number of components. Methods to get a particular component or group
 * of components. Components can be added as Strings or
 * Names and a component can be removed from any position in the
 * Name.
 * A Name can be compared to another Name and it can
 * be checked if a particular Name starts or ends with the same
 * components as another Name. Finally Names can be
 * serialized and cloned.
 *

 * Since Names can be empty (have no components) methods that
 * return a Name will never return null.
 *
 * @since 1.3
 * @author Anthony Green (example@nnthink.com)
 * @author Mark Wielaard (example@nnthink.com)
 */
public interface Name extends Cloneable, Serializable {

    long serialVersionUID = -3617482732056931635L;

    /**
     * Returns the number of components of this Name.
     * The returned number can be zero.
     */
    int size();

    /**
     * Returns true if the number of components of this
     * Name is zero, false otherwise.
     */
    boolean isEmpty();

    /**
     * Returns a non-null (but possibly empty) Enumeration of the
     * components of the Name as Strings.
     */
    Enumeration getAll();

    /**
     * Gets the component at the given index.
     *
     * @exception ArrayIndexOutOfBoundsException if the given index is smaller
     *            then zero or greater then or equal to size().
     */
    String get(int i);

    /**
     * Returns the components till the given index as a Name.
     * The returned Name can be modified without changing the
     * original.
     *
     * @exception ArrayIndexOutOfBoundsException if the given index is smaller
     *            then zero or greater then or equal to size().
     */
    Name getPrefix(int i);

    /**
     * Returns the components from the given index till the end as a
     * Name.
     * The returned Name can be modified without changing the
     * original.
     *
     * @exception ArrayIndexOutOfBoundsException if the given index is smaller
     *            then zero or greater then or equal to size().
     */

/**
     * Adds the given String component to the end of this
     * Name. The method modifies the current Name and
     * then returns it.
     *
     * @exception InvalidNameException if the given String is not a
     *            valid component for this Name.
     */
    Name add(String comp) throws InvalidNameException;

    /**
     * Inserts the given String component to this Name
     * at the given index. The method modifies the current Name and
     * then returns it.
     *
     * @exception ArrayIndexOutOfBoundsException if the given index is smaller
     *            then zero or greater then or equal to size().
     * @exception InvalidNameException if the given String is not a
     *            valid component for this Name.
     */
    Name add(int posn, String comp) throws InvalidNameException;

    /**
     * Adds all the components of the given Name to the end of this
     * Name. The method modifies the current Name and
     * then returns it.
     *
     * @exception InvalidNameException if any of the given components is not a
     *            valid component for this Name.
     */
    Name addAll(Name suffix) throws InvalidNameException;

    /**
     * Inserts all the components of the given Name to this
     * Name at the given index. The method modifies the current
     * Name and then returns it.
     *
     * @exception ArrayIndexOutOfBoundsException if the given index is smaller
     *            then zero or greater then or equal to size().
     * @exception InvalidNameException if any of the given components is not a
     *            valid component for this Name.
     */
    Name addAll(int posn, Name n) throws InvalidNameException;

    /**
     * Removes the component at the given index from this Name.
     * The method modifies the current Name and then returns it.
     *
     * @exception InvalidNameException if the given String is not a
     *            valid component for this Name.
     */
    Object remove(int posn) throws InvalidNameException;

    /**
     * Returns true if this Name starts with the
     * components of the given Name, false otherwise.
     */
    boolean startsWith(Name name);

    /**
     * Returns true if this Name ends with the
     * components of the given Name, false otherwise.
     */
    boolean endsWith(Name name);

    /**
     * Compares the given object to this Name.
     * Returns a negative value if the given Object is smaller then
     * this Name, a positive value if the Object is
     * bigger, and zero if the are equal. If the Object is not of
     * a class that can be compared to the class of this Name then
     * a ClassCastException is thrown. Note that it is not
     * guaranteed that Names implemented in different classes can
     * be compared. The definition of smaller, bigger and equal is up to the
     * actual implementing class.
     */
    int compareTo(Object obj);

    /**
     * Returns a clone of this Name. It will be a deep copy of
     * all the components of the Name so that changes to components
     * of the components does not change the component in this Name.
     */
    Object clone();
}


while (it2.hasNext()) {
                            Predecessor p = (Predecessor) it2.next();
                            Task pt = (Task) taskById.get(p.id);
                            Predecessor depend = new Predecessor();
                            depend.id = tsk.id;
                            depend.type = p.type;
                            pt.dependancies.add(depend);
                        }

/**
 * This file is part of Xena.
 *
 * @author Andrew Keeling
 * @author Chris Bitmead
 * @author Justin Waddell
 */
package au.gov.naa.digipres.xena.plugin.project;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;
import au.gov.naa.digipres.xena.kernel.XenaException;
import au.gov.naa.digipres.xena.kernel.plugin.PluginLocator;
import au.gov.naa.digipres.xena.kernel.view.XenaView;
import au.gov.naa.digipres.xena.util.XmlContentHandlerSplitter;

/**
 * View a Xena project file using the Gantt free project planner.
 */
public class GanttProjectView extends XenaView {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    byte[] result;

    public GanttProjectView() {
        try {
            jbInit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean canShowTag(String tag) throws XenaException {
        return tag.equals("Project");
    }

    public String getViewName() {
        return "Gantt Project";
    }

    public ContentHandler getContentHandler() throws XenaException {
        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler write = null;
        ByteArrayOutputStream bao = null;
        try {
            write = tf.newTransformerHandler();
            bao = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(bao);
            write.setResult(streamResult);
        } catch (TransformerConfigurationException x) {
            throw new XenaException(x);
        }
        final TransformerHandler writer = write;
        final ByteArrayOutputStream baos = bao;
        final AttributesImpl empty = new AttributesImpl();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
        final SimpleDateFormat ganttsdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
        XmlContentHandlerSplitter splitter = new XmlContentHandlerSplitter();
        splitter.addContentHandler(getTmpFileContentHandler());
        splitter.addContentHandler(new XMLFilterImpl() {

            StringBuffer sb;

            Task task;

            Predecessor predecessor;

            Resource resource;

            Allocation allocation;

            Map taskByOutlineNo = new HashMap();

            Map taskById = new HashMap();

            Set roles = new HashSet();

            int depth;

            public void startDocument() throws SAXException {
                writer.startDocument();
            }

            public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
                depth++;
                if (qName.equals("Tasks")) {
                    writer.startElement(null, "tasks", "tasks", empty);
                } else if (qName.equals("Assignments")) {
                    writer.startElement(null, "allocations", "allocations", empty);
                } else if (qName.equals("Resources")) {
                    writer.startElement(null, "resources", "resources", empty);
                } else if (qName.equals("Task")) {
                    assert task == null;
                    depth = 0;
                    task = new Task();
                } else if (qName.equals("Resource")) {
                    assert resource == null;
                    depth = 0;
                    resource = new Resource();
                } else if (qName.equals("Assignment")) {
                    assert allocation == null;
                    depth = 0;
                    allocation = new Allocation();
                } else if (task != null && qName.equals("PredecessorLink")) {
                    assert predecessor == null;
                    predecessor = new Predecessor();
                }
                sb = new StringBuffer();
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (qName.equals("StartDate")) {
                    try {
                        java.util.Date create = sdf.parse(sb.toString());
                        final AttributesImpl att = new AttributesImpl();
                        att.addAttribute(null, "view-date", "view-date", "CDATA", ganttsdf.format(create));
                        writer.startElement(null, "project", "project", att);
                    } catch (ParseException x) {
                        throw new SAXException(x);
                    }
                } else if (qName.equals("Project")) {
                    Iterator it = roles.iterator();
                    while (it.hasNext()) {
                        String role = (String) it.next();
                        AttributesImpl att = new AttributesImpl();
                        att.addAttribute(null, "roleset-name", "roleset-name", "CDATA", role);
                        writer.startElement(null, "roles", "roles", att);
                        writer.endElement(null, "roles", "roles");
                    }
                    writer.endElement(null, null, "project");
                } else if (qName.equals("Tasks")) {
                    List tops = new ArrayList();
                    Iterator it = taskByOutlineNo.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry e = (Map.Entry) it.next();
                        Task tsk = (Task) e.getValue();
                        if (tsk.parent == null) {
                            tops.add(e.getValue());
                        } else {
                            Task t = (Task) taskByOutlineNo.get(tsk.parent);
                            t.children.add(e.getValue());
                        }
                        Iterator it2 = tsk.predecessors.iterator();

                    }
                    Iterator it3 = tops.iterator();
                    while (it3.hasNext()) {
                        Task top = (Task) it3.next();
                        top.print(writer);
                    }
                    writer.endElement(null, null, "tasks");
                } else if (qName.equals("Task")) {
                    taskByOutlineNo.put(task.outlineNumber, task);
                    taskById.put(task.id, task);
                    task = null;
                } else if (qName.equals("Resources")) {
                    writer.endElement(null, null, "resources");
                } else if (qName.equals("Assignments")) {
                    writer.endElement(null, null, "allocations");
                } else if (qName.equals("Resource")) {
                    final AttributesImpl att = new AttributesImpl();
                    att.addAttribute(null, "id", "id", "ID", resource.id);
                    if (resource.name == null) {
                        resource.name = "Unnamed-" + resource.id;
                    }
                    att.addAttribute(null, "name", "name", "CDATA", resource.name);
                    if (resource.group == null) {
                        resource.group = "Default";
                    }
                    roles.add(resource.group);
                    att.addAttribute(null, "function", "function", "CDATA", resource.group + ":0");
                    att.addAttribute(null, "contacts", "contacts", "CDATA", "example@nnthink.com");
                    writer.startElement(null, "resource", "resource", att);
                    writer.endElement(null, "resource", "resource");
                    resource = null;
                } else if (qName.equals("Assignment")) {
                    final AttributesImpl att = new AttributesImpl();
                    att.addAttribute(null, "task-id", "task-id", "CDATA", allocation.taskId);
                    att.addAttribute(null, "resource-id", "resource-id", "CDATA", allocation.resourceId);
                    att.addAttribute(null, "load", "load", "CDATA", Double.toString(allocation.units));
                    writer.startElement(null, "allocation", "allocation", att);
                    writer.endElement(null, "allocation", "allocation");
                    allocation = null;
                } else if (task != null && predecessor != null) {
                    if (qName.equals("PredecessorLink")) {
                        task.predecessors.add(predecessor);
                        predecessor = null;
                    } else if (qName.equals("PredecessorUID")) {
                        predecessor.id = sb.toString();
                    } else if (qName.equals("Type")) {
                        int tp = Integer.parseInt(sb.toString());
                        if (tp == 0) {
                            predecessor.type = "2";
                        } else if (tp == 1) {
                            predecessor.type = "1";
                        } else if (tp == 2) {
                            predecessor.type = "3";
                        } else if (tp == 3) {
                            predecessor.type = "4";
                        } else {
                            assert false : "unknown type";
                        }
                    }
                } else if (task != null && depth == 1) {
                    if (qName.equals("OutlineNumber")) {
                        task.outlineNumber = sb.toString();
                        if (task.outlineNumber.endsWith(".0")) {
                            task.outlineNumber = task.outlineNumber.substring(0, task.outlineNumber.length() - 2);
                        }
                        int c;
                        if (0 <= (c = task.outlineNumber.lastIndexOf('.'))) {
                            task.parent = task.outlineNumber.substring(0, c);
                            task.order = Integer.parseInt(task.outlineNumber.substring(c + 1));
                        }
                    } else if (qName.equals("Name")) {
                        task.name = sb.toString();
                    } else if (qName.equals("UID")) {
                        task.id = sb.toString();
                    } else if (qName.equals("Start")) {
                        try {
                            task.start = sdf.parse(sb.toString());
                        } catch (ParseException x) {
                            throw new SAXException(x);
                        }
                    } else if (qName.equals("Finish")) {
                        try {
                            task.finish = sdf.parse(sb.toString());
                        } catch (ParseException x) {
                            throw new SAXException(x);
                        }
                    } else if (qName.equals("Milestone")) {
                        task.milestone = Integer.parseInt(sb.toString()) != 0;
                    } else if (qName.equals("PercentComplete")) {
                        task.percentComplete = sb.toString();
                    } else if (qName.equals("Priority")) {
                        int p = Integer.parseInt(sb.toString());
                        if (p == 500) {
                            task.priority = 1;
                        } else if (p < 500) {
                            task.priority = 0;
                        } else {
                            task.priority = 2;
                        }
                    }
                } else if (resource != null && depth == 1) {
                    if (qName.equals("Name")) {
                        resource.name = sb.toString();
                    } else if (qName.equals("UID")) {
                        resource.id = sb.toString();
                    } else if (qName.equals("Group")) {
                        resource.group = sb.toString();
                    }
                } else if (allocation != null && depth == 1) {
                    if (qName.equals("TaskUID")) {
                        allocation.taskId = sb.toString();
                    } else if (qName.equals("ResourceUID")) {
                        allocation.resourceId = sb.toString();
                    } else if (qName.equals("Units")) {
                        Double f = Double.parseDouble(sb.toString());
                        allocation.units = f * 100.0;
                    }
                }
                sb = null;
                depth--;
            }

            public void characters(char[] ch, int start, int length) throws SAXException {
                if (sb != null) {
                    sb.append(ch, start, length);
                }
            }

            public void endDocument() throws SAXException {
                writer.endDocument();
                result = baos.toByteArray();
            }
        });
        return splitter;
    }

    private void jbInit() throws Exception {
        launchGanttButton.setText("View in External Window");
        launchGanttButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                launchGanttButton_actionPerformed(e);
            }
        });
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(launchGanttButton);
        this.add(buttonPanel, java.awt.BorderLayout.CENTER);
    }

    private JButton launchGanttButton = new JButton();

    public void launchGanttButton_actionPerformed(ActionEvent e) {
        try {
            File tmpFile = File.createTempFile("gantt", ".xml");
            tmpFile.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            fos.write(result);
            fos.close();
            // TODO: Surely this can be launched using the gantt jar file???
            File gantt = new File(PluginLocator.getExternalDir(), "ganttproject.jar");
            logger.finer("Opening with gantt: " + gantt.toString() + " " + tmpFile.toString() + " " + gantt.exists() + " d:" + System.getProperty("user.dir"));
            Process p = Runtime.getRuntime().exec(new String[] { "java", "-jar", gantt.toString(), tmpFile.toString() }, null, tmpFile.getParentFile());
        } catch (IOException x) {
            JOptionPane.showMessageDialog(this, x.getMessage());
        }
    }

    class Predecessor {

        String id;

        String type;
    }

    private class Task {

        private String parent;

        private int order;

        private List children = new ArrayList();

        private String outlineNumber;

        private List predecessors = new ArrayList();

        private List dependancies = new ArrayList();

        private String id;

        private String name;

        private java.util.Date start;

        private java.util.Date finish;

        private boolean milestone;

        private String percentComplete;

        int priority;

        final long millisPerDay = 1000 * 60 * 60 * 24;

        public void print(ContentHandler ch) throws SAXException {
            java.util.Collections.sort(children, new Comparator() {

                public int compare(Object o1, Object o2) {
                    return ((Task) o1).order - ((Task) o2).order;
                }

                public boolean equals(Object obj) {
                    return false;
                }
            });
            final AttributesImpl att = new AttributesImpl();
            att.addAttribute(null, "id", "id", "ID", id);
            att.addAttribute(null, "name", "name", "CDATA", name);
            att.addAttribute(null, "meeting", "meeting", "CDATA", milestone ? "true" : "false");
            SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
            att.addAttribute(null, "start", "start", "CDATA", sdf.format(start));
            long millis = finish.getTime() - start.getTime();
            if (millis < 0) {
                throw new SAXException("Task duration for task: " + id + " is negative. Looks like the data has an error");
            }
            long days = millis / millisPerDay;
            if ((millis % millisPerDay) != 0) {
                days++;
            }
            att.addAttribute(null, "duration", "duration", "CDATA", Long.toString(days));
            att.addAttribute(null, "complete", "complete", "CDATA", percentComplete);
            ch.startElement(null, "task", "task", att);
            Iterator it = dependancies.iterator();
            while (it.hasNext()) {
                Predecessor depend = (Predecessor) it.next();
                final AttributesImpl datt = new AttributesImpl();
                datt.addAttribute(null, "id", "id", "ID", depend.id);
                datt.addAttribute(null, "type", "type", "CDATA", depend.type);
                ch.startElement(null, "depend", "depend", datt);
                ch.endElement(null, "depend", "depend");
            }
            it = children.iterator();
            while (it.hasNext()) {
                Task e = (Task) it.next();
                e.print(ch);
            }
            ch.endElement(null, "task", "task");
        }
    }

    class Resource {

        String name;

        String id;

        String group;
    }

    class Allocation {

        String taskId;

        String resourceId;

        double units;
    }
}


switch(edgeKey.getStatsType()) {
                case ACTIVITY:
                    edge.setCounts(EdgeValueHelper.decodeActivityHistogram(value));
                    break;
                case DURATION:
                    edge.setCounts(EdgeValueHelper.decodeDurationHistogram(value));
                    break;
                case LINKS:
                    break;
            }

package datawave.query.transformer;

import com.google.protobuf.InvalidProtocolBufferException;
import datawave.edge.model.EdgeModelAware;
import datawave.edge.util.EdgeKey;
import datawave.edge.util.EdgeValue;
import datawave.edge.util.EdgeValueHelper;
import datawave.marking.MarkingFunctions;
import datawave.util.time.DateHelper;
import datawave.webservice.query.Query;
import datawave.webservice.query.cachedresults.CacheableLogic;
import datawave.webservice.query.result.edge.EdgeBase;
import datawave.webservice.query.result.event.ResponseObjectFactory;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class EdgeQueryTransformer extends EdgeQueryTransformerSupport<Entry<Key, Value>, EdgeBase> implements CacheableLogic, EdgeModelAware {

    private Logger log = Logger.getLogger(EdgeQueryTransformer.class);

    public EdgeQueryTransformer(Query settings, MarkingFunctions markingFunctions, ResponseObjectFactory responseObjectFactory) {
        super(settings, markingFunctions, responseObjectFactory);
    }

    @Override
    public EdgeBase transform(Entry<Key, Value> entry) {
        EdgeKey edgeKey = EdgeKey.decode(entry.getKey());
        Value value = entry.getValue();
        EdgeBase edge = (EdgeBase) this.responseObjectFactory.getEdge();
        boolean statsEdge = edgeKey.isStatsKey();
        try {
            Map<String, String> markings = markingFunctions.translateFromColumnVisibilityForAuths(new ColumnVisibility(edgeKey.getColvis()), auths);
            edge.setMarkings(markings);
            edge.setEdgeType(edgeKey.getType());
            edge.setEdgeRelationship(edgeKey.getRelationship());
            edge.setEdgeAttribute1Source(edgeKey.getAttribute1());
            if (edgeKey.getDateType() == EdgeKey.DATE_TYPE.ACTIVITY_ONLY || edgeKey.getDateType() == EdgeKey.DATE_TYPE.ACTIVITY_AND_EVENT) {
                edge.setActivityDate(edgeKey.getYyyymmdd());
            }
            // the aquisition time is always in the key timestamp field
            edge.setDate(DateHelper.format(entry.getKey().getTimestamp()));
        } catch (Exception ex) {
            log.error("cound not get markings for " + new ColumnVisibility(edgeKey.getColvis()), ex);
        }
        EdgeValue edgeValue = null;
        try {
            edgeValue = EdgeValue.decode(value);
            // the source and sink values in the protobuf are un-normalized, so use them if they are present
            edge.setSource(edgeValue.getSourceValue());
            edge.setSink(edgeValue.getSinkValue());
            if (edgeValue.hasLoadDate()) {
                edge.setLoadDate(edgeValue.getLoadDate());
            } else {
                edge.setLoadDate(edgeKey.getYyyymmdd());
            }
        } catch (InvalidProtocolBufferException e) {
            // bad protobuf, get source and sink from key
            log.error("Invalid protobuff edge encountered!");
        }
        // value for source and sink will get set if they were not in the protobuf
        if (edge.getSource() == null) {
            edge.setSource(edgeKey.getSourceData());
        }
        if (edge.getSink() == null) {
            edge.setSink(edgeKey.getSinkData());
        }
        if (statsEdge) {
            edge.setStatsType(edgeKey.getStatsType().name());

            edge.setCount(null);
        } else {
            // Added to support displaying the hourly activity bitmask for regular edge queries
            boolean[] hourlyActivity;
            try {
                hourlyActivity = decodeHourlyActivityToBooleanArray(value);
                if (hourlyActivity != null) {
                    List<Long> counts = new ArrayList<>();
                    for (boolean hourActive : hourlyActivity) {
                        counts.add(hourActive ? 1L : 0L);
                    }
                    edge.setCounts(counts);
                } else {
                    edge.setCounts(null);
                }
            } catch (InvalidProtocolBufferException ex) {
                log.error("invalid protocol buffer encountered when attempting to parse bitmask.");
            }
            if (edgeValue != null) {
                edge.setCount(edgeValue.getCount());
            }
        }
        if (edgeKey.hasAttribute2()) {
            edge.setEdgeAttribute2(edgeKey.getAttribute2());
        }
        if (edgeKey.hasAttribute3()) {
            edge.setEdgeAttribute3(edgeKey.getAttribute3());
        }
        return edge;
    }
}