switch(dataSampler.getSide()) {
                case BODY_SIDE_RIGHT:
                    handX -= SIDE_OFFSET;
                    break;
                case BODY_SIDE_LEFT:
                    handX += SIDE_OFFSET;
                    break;
                case BODY_SIDE_UNKNOWN:
                default:
                    handX -= SIDE_OFFSET;
                    break;
            }

package org.geogebra.desktop.geogebra3D.input3D.intelRealSense;

import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.geogebra.common.GeoGebraConstants;
import org.geogebra.common.geogebra3D.input3D.Input3D;
import org.geogebra.common.geogebra3D.input3D.Input3D.OutOfField;
import org.geogebra.common.jre.util.DownloadManager;
import org.geogebra.common.main.App;
import org.geogebra.common.main.Localization;
import org.geogebra.common.util.debug.Log;
import org.geogebra.desktop.geogebra3D.input3D.Input3DFactory.Input3DException;
import org.geogebra.desktop.geogebra3D.input3D.Input3DFactory.Input3DExceptionType;
import intel.rssdk.PXCMCaptureManager;
import intel.rssdk.PXCMHandConfiguration;
import intel.rssdk.PXCMHandConfiguration.AlertHandler;
import intel.rssdk.PXCMHandData;
import intel.rssdk.PXCMHandData.AlertData;
import intel.rssdk.PXCMHandData.AlertType;
import intel.rssdk.PXCMHandData.BodySideType;
import intel.rssdk.PXCMHandModule;
import intel.rssdk.PXCMPoint3DF32;
import intel.rssdk.PXCMPoint4DF32;
import intel.rssdk.PXCMSenseManager;
import intel.rssdk.PXCMSession;
import intel.rssdk.pxcmStatus;

/**
 * socket of realsense
 *
 * @author mathieu
 */
public class Socket {

    private static final String QUERY_REGISTERY_KEY_FRONT_CAM = "reg query HKLM\\Software\\Intel\\RSSDK\\Components\\ivcam";

    // version embedded in ggb is 1.4.27.41944
    private static final int VERSION_MAJOR = 1;

    private static final int VERSION_MINOR = 4;

    /**
     * factor screen / real world
     */
    static double SCREEN_REAL_DIM_FACTOR = 1 / 0.1;

    /**
     * right/left side offset
     */
    static double SIDE_OFFSET = 0.75;

    /**
     * origin point depth
     */
    static float DEPTH_ZERO = 0.4f;

    /**
     * samples used for average
     */
    static int SAMPLES = 7;

    /**
     * hand x position
     */
    public double handX;

    /**
     * hand y position
     */
    public double handY;

    /**
     * hand z position
     */
    public double handZ;

    /**
     * hand orientation vector (x value)
     */
    public double handOrientationX;

    /**
     * hand orientation vector (y value)
     */
    public double handOrientationY;

    /**
     * hand orientation vector (z value)
     */
    public double handOrientationZ;

    /**
     * hand orientation vector (w value)
     */
    public double handOrientationW;

    /**
     * right button state
     */
    public boolean rightButton = false;

    /**
     * left button state
     */
    public boolean leftButton = false;

    /**
     * says if it has got a message from realsense
     */
    public boolean gotMessage = false;

    static private PXCMSenseManager SENSE_MANAGER;

    static private PXCMCaptureManager CAPTURE_MANAGER;

    private pxcmStatus sts;

    private PXCMHandData handData;

    private PXCMHandData.IHand hand;

    private DataSampler dataSampler;

    private abstract class DataSampler {

        protected int samples;

        protected int index;

        protected BodySideType side;

        protected int leftSideCount, rightSideCount;

        protected float[] worldX, worldY, worldZ;

        protected float[] orientationX, orientationY, orientationZ, orientationW;

        public DataSampler(int samples) {
            this.samples = samples;
            index = 0;
            worldX = new float[samples];
            worldY = new float[samples];
            worldZ = new float[samples];
            orientationX = new float[samples];
            orientationY = new float[samples];
            orientationZ = new float[samples];
            orientationW = new float[samples];
            resetSide();
        }

        protected void resetSide() {
            leftSideCount = 0;
            rightSideCount = 0;
            side = BodySideType.BODY_SIDE_UNKNOWN;
        }

        protected void addSideDetected(BodySideType type) {
            if (type == BodySideType.BODY_SIDE_RIGHT) {
                rightSideCount++;
                if (rightSideCount > 10000) {
                    rightSideCount /= 10;
                    leftSideCount /= 10;
                }
                updateSide();
            } else if (type == BodySideType.BODY_SIDE_LEFT) {
                leftSideCount++;
                if (leftSideCount > 10000) {
                    rightSideCount /= 10;
                    leftSideCount /= 10;
                }
                updateSide();
            }
        }

        private void updateSide() {
            if (side == BodySideType.BODY_SIDE_UNKNOWN) {
                // check if we can decide side
                if (rightSideCount > leftSideCount) {
                    side = BodySideType.BODY_SIDE_RIGHT;
                } else if (rightSideCount < leftSideCount) {
                    side = BodySideType.BODY_SIDE_LEFT;
                }
            } else {
                // check if we should decide side
                if (rightSideCount > 2 * leftSideCount) {
                    side = BodySideType.BODY_SIDE_RIGHT;
                } else if (2 * rightSideCount < leftSideCount) {
                    side = BodySideType.BODY_SIDE_LEFT;
                }
            }
        }

        public abstract void addData(BodySideType handSide, float wx, float wy, float wz, float ox, float oy, float oz, float ow);

        public abstract double getWorldX();

        public abstract double getWorldY();

        public abstract double getWorldZ();

        public abstract double getHandOrientationX();

        public abstract double getHandOrientationY();

        public abstract double getHandOrientationZ();

        public abstract double getHandOrientationW();

        public BodySideType getSide() {
            return side;
        }
    }

    private class DataAverage extends DataSampler {

        private float worldXSum, worldYSum, worldZSum;

        private float handOrientationXSum, handOrientationYSum, handOrientationZSum, handOrientationWSum;

        public DataAverage(int samples) {
            super(samples);
            worldXSum = 0f;
            worldYSum = 0f;
            worldZSum = 0f;
            handOrientationXSum = 0f;
            handOrientationYSum = 0f;
            handOrientationZSum = 0f;
            handOrientationWSum = 0f;
        }

        @Override
        public void addData(BodySideType handSide, float wx, float wy, float wz, float ox, float oy, float oz, float ow) {
            if (resetAllValues) {
                resetSide();
                addSideDetected(handSide);
                for (int i = 0; i < samples; i++) {
                    // reset all values
                    worldX[i] = wx;
                    worldY[i] = wy;
                    worldZ[i] = wz;
                    orientationX[i] = ox;
                    orientationY[i] = oy;
                    orientationZ[i] = oz;
                    orientationW[i] = ow;
                }
                worldXSum = wx * samples;
                worldYSum = wy * samples;
                worldZSum = wz * samples;
                handOrientationXSum = ox * samples;
                handOrientationYSum = oy * samples;
                handOrientationZSum = oz * samples;
                handOrientationWSum = ow * samples;
                index = 0;
                resetAllValues = false;
                return;
            }
            addSideDetected(handSide);
            worldXSum -= worldX[index];
            worldYSum -= worldY[index];
            worldZSum -= worldZ[index];
            worldX[index] = wx;
            worldY[index] = wy;
            worldZ[index] = wz;
            worldXSum += worldX[index];
            worldYSum += worldY[index];
            worldZSum += worldZ[index];
            handOrientationXSum -= orientationX[index];
            handOrientationYSum -= orientationY[index];
            handOrientationZSum -= orientationZ[index];
            handOrientationWSum -= orientationW[index];
            orientationX[index] = ox;
            orientationY[index] = oy;
            orientationZ[index] = oz;
            orientationW[index] = ow;
            handOrientationXSum += orientationX[index];
            handOrientationYSum += orientationY[index];
            handOrientationZSum += orientationZ[index];
            handOrientationWSum += orientationW[index];
            index++;
            if (index >= samples) {
                index = 0;
            }
        }

        @Override
        public double getWorldX() {
            return -worldXSum * SCREEN_REAL_DIM_FACTOR / samples;
        }

        @Override
        public double getWorldY() {
            return worldYSum * SCREEN_REAL_DIM_FACTOR / samples;
        }

        @Override
        public double getWorldZ() {
            return (worldZSum / samples - DEPTH_ZERO) * SCREEN_REAL_DIM_FACTOR;
        }

        @Override
        public double getHandOrientationX() {
            return -handOrientationXSum / samples;
        }

        @Override
        public double getHandOrientationY() {
            return -handOrientationYSum / samples;
        }

        @Override
        public double getHandOrientationZ() {
            return handOrientationZSum / samples;
        }

        @Override
        public double getHandOrientationW() {
            return handOrientationWSum / samples;
        }
    }

    private int handId = -1;

    private Input3D.OutOfField handOut;

    /**
     * says if we need to reset all values
     */
    boolean resetAllValues = false;

    /**
     * cam set alert, this updates the hand in/out status
     *
     * @param id
     *            hand id
     * @param type
     *            alert type
     */
    void setAlert(int id, AlertType type) {
        if (handOut != OutOfField.NO) {
            // no hand for now
            if (type == AlertType.ALERT_HAND_INSIDE_BORDERS) {
                Log.debug("hand #" + id + " inside borders");
                handId = id;
                handOut = OutOfField.NO;
                resetAllValues = true;
            } else if (handId == id) {
                switch(type) {
                    case ALERT_HAND_OUT_OF_BOTTOM_BORDER:
                        handOut = OutOfField.BOTTOM;
                        break;
                    case ALERT_HAND_OUT_OF_TOP_BORDER:
                        handOut = OutOfField.TOP;
                        break;
                    case ALERT_HAND_OUT_OF_LEFT_BORDER:
                        handOut = OutOfField.LEFT;
                        break;
                    case ALERT_HAND_OUT_OF_RIGHT_BORDER:
                        handOut = OutOfField.RIGHT;
                        break;
                    case ALERT_HAND_TOO_CLOSE:
                        handOut = OutOfField.NEAR;
                        break;
                    case ALERT_HAND_TOO_FAR:
                        handOut = OutOfField.FAR;
                        break;
                    case ALERT_HAND_CALIBRATED:
                        break;
                    case ALERT_HAND_DETECTED:
                        break;
                    case ALERT_HAND_INSIDE_BORDERS:
                        break;
                    case ALERT_HAND_LOW_CONFIDENCE:
                        break;
                    case ALERT_HAND_NOT_CALIBRATED:
                        break;
                    case ALERT_HAND_NOT_DETECTED:
                        break;
                    case ALERT_HAND_NOT_TRACKED:
                        break;
                    case ALERT_HAND_OUT_OF_BORDERS:
                        break;
                    case ALERT_HAND_TRACKED:
                        break;
                    default:
                        break;
                }
            }
        } else if (handId == id) {
            // new alert from tracked hand
            if (type == AlertType.ALERT_HAND_OUT_OF_BORDERS) {
                Log.debug("hand #" + id + " out of borders");
                handOut = OutOfField.YES;
            }
        }
    }

    /**
     * Create a session to use realsense camera
     *
     * @param app
     *            application
     *
     * @throws Input3DException
     *             if no camera installed or session can't be created
     */
    public static void createSession(final App app) throws Input3DException {
        if (SESSION != null) {
            return;
        }
        // reset sense manager
        SENSE_MANAGER = null;
        // query registry to get installed version
        if (queryRegistry()) {
            try {
                // Create session
                SESSION = PXCMSession.CreateInstance();
                if (SESSION == null) {
                    installRuntimes(app, INSTALL_CORE_AND_HAND);
                    throw new Input3DException(Input3DExceptionType.INSTALL_RUNTIMES, "RealSense: needs to install runtimes (" + INSTALL_CORE_AND_HAND + ")");
                }
            } catch (Input3DException e) {
                throw e;
            } catch (Throwable e) {
                throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: Failed to start session instance creation, maybe unsupported platform?");
            }
        }
        if (SESSION == null) {
            throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: Failed to create a session instance");
        }
    }

    /**
     * Query windows registry to check version
     *
     * @return true if up-to-date
     *
     * @throws Input3DException
     *             if no key in registry
     */
    static public boolean queryRegistry() throws Input3DException {
        // inited to bad value (correct value = 0)
        int registryQueryResult = 1;
        boolean upToDate = false;
        String version = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec(QUERY_REGISTERY_KEY_FRONT_CAM);
            p.waitFor();
            registryQueryResult = p.exitValue();
            Log.debug(QUERY_REGISTERY_KEY_FRONT_CAM + " : " + registryQueryResult);
            // get query result -- so we can check version
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                try {
                    // get version
                    while ((line = reader.readLine()) != null) {
                        String[] items = line.split(" ");
                        int index = 0;
                        while (index < items.length && items[index].length() == 0) {
                            index++;
                        }
                        if (index < items.length) {
                            if (items[index].equals("Version")) {
                                version = items[items.length - 1];
                                if (isUpToDate(version)) {
                                    upToDate = true;
                                } else {
                                    upToDate = false;
                                }
                            }
                        }
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: No key for camera in registry");
            }
        } catch (Throwable e) {
            throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: No key for camera in registry");
        }
        // nothing went wrong but no version found
        if (version == null || version.length() == 0) {
            throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: No key for camera in registry");
        }
        // version is not up to date
        if (!upToDate) {
            throw new Input3DException(Input3DExceptionType.NOT_UP_TO_DATE, version);
        }
        return upToDate;
    }

    private static boolean isUpToDate(String version) {
        String[] versionSplit = version.split("\\.");
        if (versionSplit.length == 0) {
            return false;
        }
        int major = Integer.parseInt(versionSplit[0]);
        if (major > VERSION_MAJOR) {
            return true;
        }
        if (versionSplit.length <= 1) {
            return false;
        }
        int minor = Integer.parseInt(versionSplit[1]);
        if (minor >= VERSION_MINOR) {
            return true;
        }
        return false;
    }

    private final static String REALSENSE_ONLINE_ARCHIVE_BASE = "http://example.com";

    private final static String REALSENSE_WEBSETUP = "intel_rs_sdk_runtime_websetup_6.0.21.6598.exe";

    private final static String REALSENSE_ONLINE_WEBSETUP = REALSENSE_ONLINE_ARCHIVE_BASE + REALSENSE_WEBSETUP;

    private final static String INSTALL_CORE_AND_HAND = "core,hand";

    private final static String INSTALL_HAND = "hand";

    /**
     * whethe runtimes are installed
     */
    static boolean installRuntimes = false;

    private static void installRuntimes(final App app, final String modules) {
        if (installRuntimes) {
            return;
        }
        Thread t = new Thread() {

            @Override
            public void run() {
                installRuntimes = true;
                Log.debug("\n>>>>>>>>>>>>>> install runtimes: " + modules);
                Localization loc = app.getLocalization();
                showMessage(loc.getMenu("RealSense.DownloadRuntimes"), loc.getMenu("RealSenseNotUpToDate2"));
                String filenameWebSetup = null;
                File destWebSetup = null;
                try {
                    String updateDir = System.getenv("APPDATA") + GeoGebraConstants.GEOGEBRA_THIRD_PARTY_UPDATE_DIR;
                    Log.debug("Creating " + updateDir);
                    new File(updateDir).mkdirs();
                    // Downloading web setup
                    filenameWebSetup = updateDir + File.separator + REALSENSE_WEBSETUP;
                    destWebSetup = new File(filenameWebSetup);
                    URL url = new URL(REALSENSE_ONLINE_WEBSETUP);
                    Log.debug("Downloading " + REALSENSE_ONLINE_WEBSETUP);
                    DownloadManager.copyURLToFile(url, destWebSetup);
                    Log.debug("=== done");
                } catch (Exception e) {
                    Log.error("Unsuccessful update");
                    installRuntimes = false;
                }
                boolean installOK = false;
                if (filenameWebSetup != null) {
                    installOK = install(filenameWebSetup, modules);
                }
                if (installOK) {
                    Log.debug("Successful update");
                    showMessage(loc.getMenu("RealSense.UpdatedRuntimes"), loc.getMenu("RealSenseUpdated2"));
                    if (destWebSetup != null) {
                        destWebSetup.delete();
                    }
                }
                installRuntimes = false;
            }
        };
        t.start();
    }

    /**
     * @param filename
     *            executable
     * @param modules
     *            modules
     * @return whether execution ended with 0
     */
    static boolean install(String filename, String modules) {
        Log.debug("installing " + filename + ", modules: " + modules);
        Runtime runtime = Runtime.getRuntime();
        Process p;
        try {
            p = runtime.exec(filename + " --finstall=" + modules + " --fnone=all --silent --noprogress --acceptlicense=yes");
            p.waitFor();
            // all is good
            return p.exitValue() == 0;
        } catch (IOException e) {
            Log.debug("Unsuccesfull install of " + filename + " : " + e.getMessage());
        } catch (InterruptedException e) {
            Log.debug("Unsuccesfull wait for install of " + filename + " : " + e.getMessage());
        }
        return false;
    }

    /**
     * @param message1
     *            first row
     * @param message2
     *            second row
     */
    static void showMessage(String message1, String message2) {
        final JFrame frame = new JFrame();
        Container c = frame.getContentPane();
        JPanel panel = new JPanel();
        c.add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        JLabel label = new JLabel(message1);
        JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        labelPanel.setBackground(Color.WHITE);
        labelPanel.add(label);
        panel.add(labelPanel);
        label = new JLabel(message2);
        labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        labelPanel.setBackground(Color.WHITE);
        labelPanel.add(label);
        panel.add(labelPanel);
        JLabel closeLabel = new JLabel("OK");
        closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        closeLabel.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                frame.setVisible(false);
            }
        });
        JPanel closePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        closePanel.setBackground(Color.WHITE);
        closePanel.add(closeLabel);
        panel.add(closePanel);
        frame.setUndecorated(true);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        try {
            frame.setAlwaysOnTop(true);
        } catch (SecurityException e) {
            // failed to set on top
        }
    }

    static private PXCMSession SESSION = null;

    /**
     * Create a "Socket" for realsense camera
     *
     * @param app
     *            app
     *
     * @throws Input3DException
     *             when fails
     */
    public Socket(final App app) throws Input3DException {
        if (SESSION == null) {
            try {
                createSession(app);
            } catch (Input3DException e) {
                throw e;
            } catch (Throwable e) {
                Log.error(e.getMessage());
                throw new Input3DException(Input3DExceptionType.UNKNOWN, e.getMessage());
            }
        }
        initSession();
        sts = SENSE_MANAGER.EnableHand(null);
        if (sts.compareTo(pxcmStatus.PXCM_STATUS_NO_ERROR) < 0) {
            // we miss hand module: install it
            installRuntimes(app, INSTALL_HAND);
            throw new Input3DException(Input3DExceptionType.INSTALL_RUNTIMES, "RealSense: needs to install runtimes (" + INSTALL_HAND + ")");
        }
        dataSampler = new DataAverage(SAMPLES);
        sts = SENSE_MANAGER.Init();
        if (sts.compareTo(pxcmStatus.PXCM_STATUS_NO_ERROR) >= 0) {
            PXCMHandModule handModule = SENSE_MANAGER.QueryHand();
            PXCMHandConfiguration handConfig = handModule.CreateActiveConfiguration();
            handConfig.EnableAllAlerts();
            AlertHandler alertHandler = new AlertHandler() {

                @Override
                public void OnFiredAlert(AlertData data) {
                    setAlert(data.handId, data.label);
                }
            };
            handConfig.SubscribeAlert(alertHandler);
            handConfig.ApplyChanges();
            handConfig.Update();
            handData = handModule.CreateOutput();
            hand = new PXCMHandData.IHand();
            handOut = OutOfField.YES;
            connected = true;
        }
        if (!connected) {
            throw new Input3DException(Input3DExceptionType.RUN, "RealSense: not connected (" + (sts == null ? "no state" : sts.name() + ")"));
        }
        Log.debug("RealSense: connected");
    }

    private static void initSession() throws Input3DException {
        if (SESSION == null) {
            throw new Input3DException(Input3DExceptionType.INSTALL, "RealSense: no session created");
        }
        if (SENSE_MANAGER != null) {
            throw new Input3DException(Input3DExceptionType.ALREADY_USED, "RealSense: already in use");
        }
        SENSE_MANAGER = SESSION.CreateSenseManager();
        if (SENSE_MANAGER == null) {
            throw new Input3DException(Input3DExceptionType.RUN, "RealSense: Failed to create a SenseManager instance");
        }
        CAPTURE_MANAGER = SENSE_MANAGER.QueryCaptureManager();
        CAPTURE_MANAGER.FilterByDeviceInfo("RealSense", null, 0);
    }

    private boolean connected = false;

    /**
     * get data from camera
     *
     * @return true if data have been produced
     */
    public boolean getData() {
        if (!connected) {
            return false;
        }
        sts = SENSE_MANAGER.AcquireFrame(true);
        if (sts.compareTo(pxcmStatus.PXCM_STATUS_NO_ERROR) < 0) {
            gotMessage = false;
            SENSE_MANAGER.ReleaseFrame();
            return false;
        }
        // Query and Display Joint of Hand or Palm
        handData.Update();
        sts = handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_NEAR_TO_FAR, 0, hand);
        if (sts.compareTo(pxcmStatus.PXCM_STATUS_NO_ERROR) >= 0) {
            PXCMPoint3DF32 world = hand.QueryMassCenterWorld();
            PXCMPoint4DF32 palmOrientation = hand.QueryPalmOrientation();
            BodySideType handSide = hand.QueryBodySide();
            dataSampler.addData(handSide, world.x, world.y, world.z, palmOrientation.x, palmOrientation.y, palmOrientation.z, palmOrientation.w);
            handX = dataSampler.getWorldX();
            handY = dataSampler.getWorldY();
            handZ = dataSampler.getWorldZ();

            handOrientationX = dataSampler.getHandOrientationX();
            handOrientationY = dataSampler.getHandOrientationY();
            handOrientationZ = dataSampler.getHandOrientationZ();
            handOrientationW = dataSampler.getHandOrientationW();
            gotMessage = true;
        } else {
            gotMessage = false;
        }
        SENSE_MANAGER.ReleaseFrame();
        return true;
    }

    /**
     * @return true if a hand is tracked
     */
    public boolean hasTrackedHand() {
        return handOut == OutOfField.NO;
    }

    /**
     * @return out of field type
     */
    public OutOfField getOutOfField() {
        return handOut;
    }

    /**
     * set left button status
     *
     * @param flag
     *            status
     */
    public void setLeftButtonPressed(boolean flag) {
        leftButton = flag;
    }

    /**
     * exit and close manager
     */
    public static void exit() {
        CAPTURE_MANAGER.CloseStreams();
        SENSE_MANAGER.Close();
        SENSE_MANAGER = null;
        SESSION.close();
        SESSION = null;
    }
}


switch(trans) {
            case RET_IMG_DOC_SET:
                isXDSI = false;
            case RET_IMG_DOC_SET_GW:
            case XC_RET_IMG_DOC_SET:
                isXDSI = true;
                transactionType = trans;
                break;
            default:
                throw new XdsInternalException(trans.getName() + " not handled by this class");
        }

package gov.nist.toolkit.testengine.transactions;

import gov.nist.toolkit.configDatatypes.client.TransactionType;
import gov.nist.toolkit.configDatatypes.server.SimulatorProperties;
import gov.nist.toolkit.installation.shared.TestSession;
import gov.nist.toolkit.registrymetadata.Metadata;
import gov.nist.toolkit.registrymsg.repository.RetrievedDocumentModel;
import gov.nist.toolkit.registrymsg.repository.RetrievedDocumentsModel;
import gov.nist.toolkit.simcommon.client.SimId;
import gov.nist.toolkit.simcommon.client.SimulatorConfig;
import gov.nist.toolkit.simcommon.server.SimDb;
import gov.nist.toolkit.testengine.engine.Linkage;
import gov.nist.toolkit.testengine.engine.Rad69;
import gov.nist.toolkit.testengine.engine.RetContext;
import gov.nist.toolkit.testengine.engine.StepContext;
import gov.nist.toolkit.utilities.io.Sha1Bean;
import gov.nist.toolkit.utilities.xml.OMFormatter;
import gov.nist.toolkit.utilities.xml.Util;
import gov.nist.toolkit.utilities.xml.XmlUtil;
import gov.nist.toolkit.xdsexception.XdsPreparsedException;
import gov.nist.toolkit.xdsexception.client.MetadataException;
import gov.nist.toolkit.xdsexception.client.XdsException;
import gov.nist.toolkit.xdsexception.client.XdsInternalException;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import javax.xml.namespace.QName;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class RetrieveImgDocSetTransaction extends BasicTransaction {

    TransactionType transactionType = null;

    String uri = null;

    OMElement uri_ref = null;

    HashMap<String, String> referenced_documents = new HashMap<String, String>();

    // filename
    Metadata reference_metadata = null;

    boolean isXDSI;

    static Logger logger = Logger.getLogger(RetrieveImgDocSetTransaction.class);

    @Override
    public String toString() {
        return "IDSRetrieveTransaction: *************" + "\nuri = " + uri + "\nuri_ref = " + isNull(uri_ref) + "\nreferenced_documents = " + referenced_documents + "\nuse_document_unique_id = " + use_repository_unique_id + "\nuse_id = " + use_id + "\nuse_xpath = " + use_xpath + "\nlinkage = " + local_linkage_data + "\nendpoint = " + endpoint + "\nisXDSI = " + isXDSI + "\nactor config = " + ((testConfig == null) ? "null" : testConfig.site) + "\n****************";
    }

    String metadataStructure(Metadata m) {
        try {
            return m.structure();
        } catch (Exception e) {
        }
        return null;
    }

    String isNull(Object thing) {
        return (thing == null) ? "null" : "not null";
    }

    /**
     * @param s_ctx StepContext instance creating this instance.
     * @param instruction Instruction Element from testplan.xml
     * @param instruction_output Instruction output element from log.xml
     * @param trans transaction type being processed. One of RET_IMG_DOC_SET,
     * RET_IMG_DOC_SET_GW, XC_RET_IMG_DOC_SET:
     * @throws XdsInternalException if null or invalid transaction type.
     */
    public RetrieveImgDocSetTransaction(StepContext s_ctx, OMElement instruction, OMElement instruction_output, TransactionType trans) throws XdsInternalException {
        super(s_ctx, instruction, instruction_output);
        xds_version = BasicTransaction.xds_b;
        defaultEndpointProcessing = false;
        parse_metadata = false;
        noMetadataProcessing = true;

    }

    @Override
    public void run(OMElement request_ele) throws Exception {
        logger.debug("RetrieveImgDocSetTransaction#run");
        if (request_ele == null)
            throw new XdsInternalException("Retrieve transaction - request is null");
        logger.debug(" Request Element: " + request_ele.toString());
        applyLinkage(request_ele);
        reportManagerPreRun(request_ele);
        logger.debug(" Repository Unique ID: " + repositoryUniqueId);
        if (repositoryUniqueId == null) {
            // if managed by ReportManager then need to extract it from request
            try {
                AXIOMXPath xpathExpression = new AXIOMXPath("//*[local-name()='RepositoryUniqueId']");
                repositoryUniqueId = xpathExpression.stringValueOf(request_ele);
            } catch (Exception e) {
                fatal("Error extracting repositoryUniqueId from Retrieve request - " + e.getMessage() + "\nRequest is..." + new OMFormatter(request_ele).toString() + "\n...End of Request");
            }
        }
        if (s_ctx.getPlan().getExtraLinkage() != null)
            testLog.add_name_value(instruction_output, "TemplateParams", s_ctx.getPlan().getExtraLinkage());
        if (StringUtils.isNotBlank(target))
            endpoint = target;
        parseIDSEndpoint(repositoryUniqueId, transactionType, testConfig.secure);
        testLog.add_name_value(instruction_output, "InputMetadata", Util.deep_copy(request_ele));
        testLog.add_name_value(instruction_output, "Linkage", this.local_linkage_data.toString());
        RetContext r_ctx = null;
        try {
            // map from doc uid -> info about doc
            // RetInfo holds size, hash, home etc
            HashMap<String, RetrievedDocumentModel> request_info = build_request_info(request_ele);
            // Bean that holds the context of the retrieve operation
            r_ctx = new RetContext();
            r_ctx.setRequestInfo(new RetrievedDocumentsModel().setMap(request_info));
            r_ctx.setRequest(request_ele);
            r_ctx.setExpectedError(s_ctx.getExpectedErrorMessage());
            Rad69 rad69 = new Rad69(this, r_ctx, endpoint, transactionType);
            rad69.setUseReportManager(useReportManager);
            rad69.setAsync(async);
            rad69.setExpectedMimeType("application/dicom");
            rad69.setStepContext(instruction_output);
            rad69.setIsXca(isXDSI);
            rad69.setSoap12(true);
            rad69.setReferenceMetadata(reference_metadata);
            logger.debug("ImagingDocSetRetrieveTransaction about to call ret_b.run()");
            OMElement result = rad69.run();
            logger.debug("ImagingDocSetRetrieveTransaction after rad69.run()");
            rad69.validate();
        } catch (XdsPreparsedException e) {
            throw new XdsInternalException("Retrieve Error: endpoint was: " + endpoint + " " + e.getMessage(), e);
        } catch (Exception e) {
            throw new XdsInternalException("Retrieve Error: endpoint was: " + endpoint + " " + e.getMessage(), e);
        }
        add_step_status_to_output();
        // check that status == success
        String status = r_ctx.getRrp().get_registry_response_status();
        eval_expected_status(status, r_ctx.getRrp().get_error_code_contexts());
        String expErrorCode = s_ctx.getExpectedErrorCode();
        if (expErrorCode != null && !expErrorCode.equals("")) {
            List<String> errCodesReturned = r_ctx.getRrp().get_error_codes();
            if (!errCodesReturned.contains(expErrorCode)) {
                s_ctx.set_error("Expected errorCode of " + expErrorCode + "\nDid getRetrievedDocumentsModel errorCodes of " + errCodesReturned);
                step_failure = true;
            }
        }
        reportManagerPostRun();
    }

    @SuppressWarnings("unchecked")
    boolean containsVariable(OMElement ele) {
        String valueStr = ele.getText();
        if (containsVariable(valueStr))
            return true;
        for (Iterator<OMElement> it = ele.getChildElements(); it.hasNext(); ) {
            OMElement child = it.next();
            if (containsVariable(child))
                return true;
        }
        return false;
    }

    boolean containsVariable(String str) {
        if (str == null)
            return false;
        int i = str.indexOf("$");
        if (i == -1)
            return false;
        return true;
    }

    void update_referenced_documents() {
        HashMap<String, String> new_entries = new HashMap<String, String>();
        for (String ref_id : referenced_documents.keySet()) {
            if (local_linkage_data.containsKey(ref_id)) {
                new_entries.put(local_linkage_data.get(ref_id), referenced_documents.get(ref_id));
            }
        }
        referenced_documents.putAll(new_entries);
    }

    HashMap<String, String> parse_rep_request(OMElement rdsr) {
        HashMap<String, String> map = new HashMap<String, String>();
        // repuid
        for (OMElement document_request : XmlUtil.childrenWithLocalName(rdsr, "DocumentRequest")) {
            OMElement doc_uid_ele = XmlUtil.firstChildWithLocalName(document_request, "DocumentUniqueId");
            String doc_uid = doc_uid_ele.getText();
            OMElement rep_uid_ele = XmlUtil.firstChildWithLocalName(document_request, "RepositoryUniqueId");
            String rep_uid = rep_uid_ele.getText();
            map.put(doc_uid, rep_uid);
        }
        return map;
    }

    private HashMap<String, RetrievedDocumentModel> build_request_info(OMElement metadata_ele) throws XdsException {
        HashMap<String, RetrievedDocumentModel> request;
        request = new HashMap<String, RetrievedDocumentModel>();
        for (OMElement document_request : XmlUtil.childrenWithLocalName(metadata_ele, "DocumentRequest")) {
            OMElement doc_uid_ele = XmlUtil.firstChildWithLocalName(document_request, "DocumentUniqueId");
            String doc_uid = doc_uid_ele.getText();
            OMElement rep_uid_ele = XmlUtil.firstChildWithLocalName(document_request, "RepositoryUniqueId");
            String rep_uid = rep_uid_ele.getText();
            RetrievedDocumentModel rqst = new RetrievedDocumentModel();
            rqst.setDocUid(doc_uid);
            rqst.setRepUid(rep_uid);
            request.put(doc_uid, rqst);
        }
        return request;
    }

    @Override
    protected void parseInstruction(OMElement part) throws XdsInternalException, MetadataException {
        String part_name = part.getLocalName();
        if (part_name.equals("MetadataFile")) {
            metadata_filename = testConfig.testplanDir + File.separator + part.getText();
            testLog.add_name_value(instruction_output, "MetadataFile", metadata_filename);
        } else if (part_name.equals("ExpectedContents")) {
            testLog.add_name_value(instruction_output, "ExpectedContents", part);
        } else if (part_name.equals("ExpectedMimeType")) {
            testLog.add_name_value(instruction_output, "ExpectedMimeType", part);
        } else if (part_name.equals("ReferenceDocument")) {
            String filename = null;
            String uid = null;
            filename = testConfig.testplanDir + File.separator + part.getText();
            uid = part.getAttributeValue(new QName("uid"));
            referenced_documents.put(uid, filename);
            testLog.add_name_value(instruction_output, "ReferenceDocument", part);
        } else if (part_name.equals("ReferenceMetadata")) {
            String testdir = part.getAttributeValue(new QName("testdir"));
            String step = part.getAttributeValue(new QName("step"));
            if (testdir == null || testdir.equals("") || step == null || step.equals(""))
                throw new XdsInternalException("ReferenceMetadata instruction: both testdir and step are required attributes");
            reference_metadata = new Linkage(testConfig).getResult(testdir, step);
        } else if (part_name.equals("UseId")) {
            use_id.add(part);
            testLog.add_name_value(instruction_output, "UseId", part);
        } else if (part_name.equals("UseRepositoryUniqueId")) {
            this.use_repository_unique_id.add(part);
            testLog.add_name_value(instruction_output, "UseRepositoryUniqueId", part);
        } else if (part_name.equals("UseXPath")) {
            use_xpath.add(part);
            testLog.add_name_value(instruction_output, "UseXRef", part);
        } else if (part_name.equals("URI")) {
            uri = part.getText();
        } else if (part_name.equals("URIRef")) {
            uri_ref = part;
        } else if (part_name.equals("Target")) {
            parseTargetInstruction(part);
        } else {
            // throw new XdsException("Don't understand instruction " + part_name +
            parseBasicInstruction(part);
        }
    }

    private String target = null;

    private void parseTargetInstruction(OMElement part) {
        try {
            String sim = part.getAttributeValue(new QName("sim"));
            TestSession testSession = testConfig.testInstance.getTestSession();
            SimulatorConfig simConfig = new SimDb().getSimulator(new SimId(testSession, sim));
            target = simConfig.getConfigEle(SimulatorProperties.idsrEndpoint).asString();
        } catch (Exception e) {
        }
    }

    String sha1(byte[] buf) throws Exception {
        Sha1Bean sb = new Sha1Bean();
        sb.setByteStream(buf);
        return sb.getSha1String();
    }

    @Override
    protected String getRequestAction() {
        return transactionType.getRequestAction();
    }

    @Override
    protected String getBasicTransactionName() {
        return transactionType.getShortName();
    }

    private boolean abbrFlag;

    private void abbreviate(OMElement msg) {
        try {
            abbrFlag = false;
            prs(msg);
            if (abbrFlag) {
                String str = msg.toStringWithConsume();
                FileUtils.writeStringToFile(new File("/opt/xdsi/last-trans.xml"), str);
            }
        } catch (Exception e) {
            logger.warn("abbreviate error: " + e.getMessage());
        }
    }

    /**
     * recursive rtn find descendant {@code <Document>} elements and replaces
     * their text with ...
     * @param ele to process
     */
    private void prs(OMElement ele) {
        if (ele.getLocalName().equals("Document")) {
            ele.setText("...");
            abbrFlag = true;
            return;
        }
        @SuppressWarnings("unchecked")
        Iterator<OMElement> i = ele.getChildElements();
        while (i.hasNext()) {
            prs(i.next());
        }
    }
}


switch(transferType) {
            case DOWNLOAD:
                return transferFile.hasRemoteChildrenFetched();
            case UPLOAD:
                return transferFile.hasLocalChildrenFetched();
            default:
                throw new IllegalStateException("Unknown transfer type: " + transferType);
        }

package org.netbeans.modules.php.project.connections.ui.transfer.tree;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.netbeans.modules.php.project.connections.common.RemoteUtils;
import org.netbeans.modules.php.project.connections.transfer.TransferFile;
import org.netbeans.modules.php.project.connections.ui.transfer.TransferFilesChangeSupport;
import org.netbeans.modules.php.project.connections.ui.transfer.TransferFilesChooser;
import org.netbeans.modules.php.project.connections.ui.transfer.TransferFilesChooserPanel.TransferFilesChangeListener;
import org.openide.nodes.Node;

final class TransferSelectorModel {

    private final TransferFilesChooser.TransferType transferType;

    private final Set<TransferFile> transferFiles;

    private final Set<TransferFile> selected = Collections.synchronizedSet(new HashSet<TransferFile>());

    private final TransferFilesChangeSupport filesChangeSupport = new TransferFilesChangeSupport(this);

    private final long timestamp;

    public TransferSelectorModel(TransferFilesChooser.TransferType transferType, Set<TransferFile> transferFiles, long timestamp) {
        assert transferType != null;
        assert transferFiles != null;
        this.transferType = transferType;
        this.transferFiles = Collections.synchronizedSet(copyNoProjectRoot(transferFiles));
        this.timestamp = timestamp;
        for (TransferFile file : this.transferFiles) {
            preselect(file);
        }
    }

    private boolean preselect(TransferFile file) {
        boolean select = timestamp == -1;
        if (timestamp != -1) {
            // we have some timestamp
            select = file.getTimestamp() > timestamp;
        }
        if (select) {
            // intentionally not addChildren()!
            selected.add(file);
        }
        return select;
    }

    public void addChangeListener(TransferFilesChangeListener listener) {
        filesChangeSupport.addChangeListener(listener);
    }

    public void removeChangeListener(TransferFilesChangeListener listener) {
        filesChangeSupport.removeChangeListener(listener);
    }

    public boolean isNodeSelected(Node node) {
        TransferFile transferFile = getTransferFile(node);
        if (transferFile == null) {
            // not known yet
            return false;
        }
        return selected.contains(transferFile);
    }

    public boolean isNodePartiallySelected(Node node) {
        TransferFile transferFile = getTransferFile(node);
        if (transferFile == null) {
            // not known yet
            return false;
        }
        if (transferFile.isFile() || !selected.contains(transferFile)) {
            return false;
        }
        return !hasAllChildrenSelected(transferFile);
    }

    public void setNodeSelected(Node node, boolean select) {
        TransferFile transferFile = getTransferFile(node);
        if (transferFile == null) {
            // dblclick on root node or not known yet
            return;
        }
        if (select) {
            addChildren(transferFile);
            addParents(transferFile);
        } else {
            removeChildren(transferFile);
        }
        filesChangeSupport.fireSelectedFilesChange();
    }

    public void addNode(Node node) {
        TransferFile transferFile = getTransferFile(node);
        if (transferFile == null) {
            // dblclick on root node or not known yet
            return;
        }
        transferFiles.add(transferFile);
        boolean selectNode = false;
        if (!RemoteUtils.allFilesFetched(transferType == TransferFilesChooser.TransferType.DOWNLOAD)) {
            // lazy children
            selectNode = selected.contains(transferFile.getParent());
        }
        if (selectNode || preselect(transferFile)) {
            setNodeSelected(node, true);
        }
    }

    public void selectAll() {
        selected.addAll(transferFiles);
        filesChangeSupport.fireSelectedFilesChange();
    }

    public void unselectAll() {
        selected.clear();
        filesChangeSupport.fireSelectedFilesChange();
    }

    public boolean isAllSelected() {
        return selected.size() == transferFiles.size();
    }

    public Set<TransferFile> getData() {
        return transferFiles;
    }

    public Set<TransferFile> getSelected() {
        return new HashSet<>(selected);
    }

    public int getSelectedSize() {
        return selected.size();
    }

    /**
     * Get {@link TransferFile} or {@code null} if the transfer file is nor known yet.
     * @param node node to get {@link TransferFile} for
     * @return {@link TransferFile} or {@code null} if the transfer file is nor known yet
     */
    private TransferFile getTransferFile(Node node) {
        return node.getLookup().lookup(TransferFile.class);
    }

    private void addChildren(TransferFile file) {
        if (file.isProjectRoot()) {
            // ignored
            return;
        }
        selected.add(file);
        if (hasChildrenFetched(file)) {
            for (TransferFile child : getChildren(file)) {
                addChildren(child);
            }
        }
    }

    private void addParents(TransferFile fromFile) {
        TransferFile parent = fromFile.getParent();
        if (parent != null) {
            if (parent.isProjectRoot()) {
                // ignored
                return;
            }
            selected.add(parent);
            addParents(parent);
        }
    }

    private void removeChildren(TransferFile file) {
        selected.remove(file);
        if (hasChildrenFetched(file)) {
            for (TransferFile child : getChildren(file)) {
                removeChildren(child);
            }
        }
    }

    private boolean hasAllChildrenSelected(TransferFile transferFile) {
        if (!selected.contains(transferFile)) {
            return false;
        }
        if (hasChildrenFetched(transferFile)) {
            for (TransferFile child : getChildren(transferFile)) {
                if (!hasAllChildrenSelected(child)) {
                    return false;
                }
            }
        }
        return true;
    }

    private Set<TransferFile> copyNoProjectRoot(Set<TransferFile> transferFiles) {
        Set<TransferFile> files = new HashSet<>();
        for (TransferFile file : transferFiles) {
            if (!file.isProjectRoot()) {
                files.add(file);
            }
        }
        return files;
    }

    private boolean hasChildrenFetched(TransferFile transferFile) {

    }

    private List<TransferFile> getChildren(TransferFile transferFile) {
        switch(transferType) {
            case DOWNLOAD:
                return transferFile.getRemoteChildren();
            case UPLOAD:
                return transferFile.getLocalChildren();
            default:
                throw new IllegalStateException("Unknown transfer type: " + transferType);
        }
    }
}


switch(nd) {
            case DISTRIBUTION_BINOMIAL:
                return new BinomialDistribution(params);
            case DISTRIBUTION_GAUSSIAN:
                return new GaussianDistribution(params);
            case DISTRIBUTION_FLAT:
                return new FlatNumberDistribution(params);
            case DISTRIBUTION_ZIPF:
                return new ZipfDistribution(params);
        }

package edu.brown.oltpgenerator.env.RandomDistribution;

import java.util.Map;
import edu.brown.oltpgenerator.gui.common.RandomDistribution.NumberDistribution;

public class NumericDistributionFactory {

    public static NumericDistribution createNumberColumnEditProperty(NumberDistribution nd, Map<String, Object> params) {

        throw new RuntimeException("Invalid NumberDistribution type");
    }
}


switch(face) {
            case NORTH:
                data = 0x3;
                break;
            case SOUTH:
                data = 0x2;
                break;
            case EAST:
            default:
                data = 0x0;
                break;
            case WEST:
                data = 0x1;
                break;
        }

package org.bukkit.material;

import org.bukkit.Material;
import org.bukkit.block.BlockFace;

public class Stairs extends MaterialData implements Directional {

    /**
     * @param type the raw type id
     * @deprecated Magic value
     */
    @Deprecated
    public Stairs(final int type) {
        super(type);
    }

    public Stairs(final Material type) {
        super(type);
    }

    /**
     * @param type the raw type id
     * @param data the raw data value
     * @deprecated Magic value
     */
    @Deprecated
    public Stairs(final int type, final byte data) {
        super(type, data);
    }

    /**
     * @param type the type
     * @param data the raw data value
     * @deprecated Magic value
     */
    @Deprecated
    public Stairs(final Material type, final byte data) {
        super(type, data);
    }

    /**
     * @return the direction the stairs ascend towards
     */
    public BlockFace getAscendingDirection() {
        byte data = getData();
        switch(data & 0x3) {
            case 0x0:
            default:
                return BlockFace.EAST;
            case 0x1:
                return BlockFace.WEST;
            case 0x2:
                return BlockFace.SOUTH;
            case 0x3:
                return BlockFace.NORTH;
        }
    }

    /**
     * @return the direction the stairs descend towards
     */
    public BlockFace getDescendingDirection() {
        return getAscendingDirection().getOppositeFace();
    }

    /**
     * Set the direction the stair part of the block is facing
     */
    public void setFacingDirection(BlockFace face) {
        byte data;

        setData((byte) ((getData() & 0xC) | data));
    }

    /**
     * @return the direction the stair part of the block is facing
     */
    public BlockFace getFacing() {
        return getDescendingDirection();
    }

    /**
     * Test if step is inverted
     *
     * @return true if inverted (top half), false if normal (bottom half)
     */
    public boolean isInverted() {
        return ((getData() & 0x4) != 0);
    }

    /**
     * Set step inverted state
     *
     * @param inv - true if step is inverted (top half), false if step is
     *            normal (bottom half)
     */
    public void setInverted(boolean inv) {
        int dat = getData() & 0x3;
        if (inv) {
            dat |= 0x4;
        }
        setData((byte) dat);
    }

    @Override
    public String toString() {
        return super.toString() + " facing " + getFacing() + (isInverted() ? " inverted" : "");
    }

    @Override
    public Stairs clone() {
        return (Stairs) super.clone();
    }
}


switch(t.getKind()) {
            case ASSIGNMENT:
            case PREFIX_INCREMENT:
            case PREFIX_DECREMENT:
            case POSTFIX_INCREMENT:
            case POSTFIX_DECREMENT:
            case METHOD_INVOCATION:
            case NEW_CLASS:
                return true;
            default:
                return false;
        }

package org.javacs.rewrite;

import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.Trees;
import java.nio.file.Path;
import java.util.Map;
import org.javacs.CompilerProvider;
import org.javacs.ParseTask;
import org.javacs.lsp.Position;
import org.javacs.lsp.Range;
import org.javacs.lsp.TextEdit;

public class ConvertVariableToStatement implements Rewrite {

    final Path file;

    final int position;

    public ConvertVariableToStatement(Path file, int position) {
        this.file = file;
        this.position = position;
    }

    @Override
    public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
        var task = compiler.parse(file);
        var trees = Trees.instance(task.task);
        var pos = trees.getSourcePositions();
        var lines = task.root.getLineMap();
        var variable = findVariable(task, position);
        if (variable == null) {
            return CANCELLED;
        }
        var expression = variable.getInitializer();
        if (expression == null) {
            return CANCELLED;
        }
        if (!isExpressionStatement(expression)) {
            return CANCELLED;
        }
        var start = pos.getStartPosition(task.root, variable);
        var end = pos.getStartPosition(task.root, expression);
        var startLine = (int) lines.getLineNumber(start);
        var startColumn = (int) lines.getColumnNumber(start);
        var startPos = new Position(startLine - 1, startColumn - 1);
        var endLine = (int) lines.getLineNumber(end);
        var endColumn = (int) lines.getColumnNumber(end);
        var endPos = new Position(endLine - 1, endColumn - 1);
        var delete = new Range(startPos, endPos);
        var edit = new TextEdit(delete, "");
        TextEdit[] edits = { edit };
        return Map.of(file, edits);
    }

    static VariableTree findVariable(ParseTask task, int position) {
        return new FindVariableAt(task.task).scan(task.root, position);
    }

    static boolean isExpressionStatement(Tree t) {


switch(currentFor) {
            case ElementName:
                length = currentNumberOfElements * 2 * (currentLengthOfString + 5);
                break;
            case AttributeName:
            case AttributeValue:
                length = currentNumberOfElements * (lengthNamespace + 44 + currentLengthOfString);
                break;
            default:
        }

package wsattacker.library.intelligentdos.dos;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import wsattacker.library.intelligentdos.common.DoSParam;
import wsattacker.library.intelligentdos.helper.IterateModel;

public class XmlOverlongNames extends AbstractDoSAttack {

    private static final int MIN_NUMBER_OF_ELEMENTS = 1;

    private static final int MIN_LENGTH_OF_STRING = 1;

    private static final String NODEVALUE = "value";

    public static enum For {

        ElementName, AttributeName, AttributeValue
    }

    private final PayloadPosition[] possiblePossitions = { PayloadPosition.ELEMENT };

    private final For[] defaultOverlongFor = { For.ElementName, For.AttributeName, For.AttributeValue };

    private static final IterateModel defaultLengthOfStrings = IterateModel.custom().startAt(12500).stopAt(200000).setIncrement(4).setIterateStrategie(IterateModel.IterateStrategie.MUL).setIncreaseIncrementStrategie(IterateModel.IncreaseIncrementStrategie.NO).build();

    private static final IterateModel defaultNumberOfElements = IterateModel.custom().startAt(4).stopAt(8).setIncrement(4).setIterateStrategie(IterateModel.IterateStrategie.ADD).setIncreaseIncrementStrategie(IterateModel.IncreaseIncrementStrategie.NO).build();

    private For[] overlongFor;

    // iterator
    private IterateModel lengthOfStrings;

    private IterateModel numberOfElements;

    private Iterator<For> overlongForIterator;

    // current
    private int currentLengthOfString;

    private int currentNumberOfElements;

    private For currentFor;

    public XmlOverlongNames() {
        overlongFor = defaultOverlongFor;
        overlongForIterator = Arrays.asList(overlongFor).iterator();
        try {
            lengthOfStrings = defaultLengthOfStrings.clone();
            numberOfElements = defaultNumberOfElements.clone();
        } catch (CloneNotSupportedException e) {
            // may not happen
        }
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#getName()
     */
    @Override
    public String getName() {
        return "XmlOverlongNames";
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.AbstractDoSAttack#getPossiblePossitions()
     */
    @Override
    public PayloadPosition[] getPossiblePossitions() {
        PayloadPosition[] copy = new PayloadPosition[possiblePossitions.length];
        System.arraycopy(possiblePossitions, 0, copy, 0, possiblePossitions.length);
        return copy;
    }

    public For[] getOverlongNamesFor() {
        For[] copy = new For[overlongFor.length];
        System.arraycopy(overlongFor, 0, copy, 0, overlongFor.length);
        return copy;
    }

    public void setOverlongNamesFor(For[] overlongFor) {
        if (overlongFor == null || overlongFor.length == 0) {
            throw new IllegalArgumentException("elements may not be null");
        }
        this.overlongFor = new For[overlongFor.length];
        System.arraycopy(overlongFor, 0, this.overlongFor, 0, overlongFor.length);
        this.overlongForIterator = Arrays.asList(overlongFor).iterator();
    }

    public IterateModel getLengthOfStringsIterator() {
        try {
            return lengthOfStrings.clone();
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(XmlElementCount.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public void setLengthOfStringsIterator(IterateModel iterateModel) {
        if (iterateModel == null) {
            throw new IllegalArgumentException("NumberOfElementsIterator may not be null");
        }
        lengthOfStrings = iterateModel;
    }

    public IterateModel getNumberOfElementsIterator() {
        try {
            return numberOfElements.clone();
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(XmlElementCount.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public void setNumberOfElementsIterator(IterateModel iterateModel) {
        if (iterateModel == null) {
            throw new IllegalArgumentException("NumberOfElementsIterator may not be null");
        }
        numberOfElements = iterateModel;
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#hasFurtherParams()
     */
    @Override
    public boolean hasFurtherParams() {
        return lengthOfStrings.hasNext() || numberOfElements.hasNext() || overlongForIterator.hasNext();
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#nextParam()
     */
    @Override
    public void nextParam() {
        if (!initialized) {
            currentLengthOfString = lengthOfStrings.next();
            currentNumberOfElements = numberOfElements.next();
            currentFor = overlongForIterator.next();
            initialized = true;
        } else if (lengthOfStrings.hasNext()) {
            currentLengthOfString = lengthOfStrings.next();
        } else if (numberOfElements.hasNext()) {
            lengthOfStrings.reset();
            currentLengthOfString = lengthOfStrings.next();
            currentNumberOfElements = numberOfElements.next();
        } else if (overlongForIterator.hasNext()) {
            lengthOfStrings.reset();
            currentLengthOfString = lengthOfStrings.next();
            numberOfElements.reset();
            currentNumberOfElements = numberOfElements.next();
            currentFor = overlongForIterator.next();
        }
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#getCurrentParams()
     */
    @Override
    public List<DoSParam<?>> getCurrentParams() {
        List<DoSParam<?>> list = new ArrayList<DoSParam<?>>();
        list.add(new DoSParam<Integer>("Length of the String", currentLengthOfString));
        list.add(new DoSParam<Integer>("Number of Elements", currentNumberOfElements));
        list.add(new DoSParam<For>("Overlong Attack for", currentFor));
        return list;
    }

    @Override
    int getCommentLength(PayloadPosition payloadPosition) {
        int length = 0;
        int lengthNamespace = 0;
        if (useNamespace) {
            lengthNamespace = namespace.length();
        }

        return length;
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#getTamperedRequest(java.lang.String,
     * wsattacker.library.intelligentdos.dos.DoSAttack.PayloadPosition)
     */
    @Override
    public String getTamperedRequest(String xml, PayloadPosition payloadPosition) {
        verifyPayloadPosition(payloadPosition);
        String nodeValue = NODEVALUE;
        StringBuilder sb = new StringBuilder("");
        switch(currentFor) {
            case ElementName:
                for (int i = 0; i < currentNumberOfElements; i++) {
                    sb.append("<");
                    for (int j = 0; j < (currentLengthOfString); j++) {
                        sb.append("A");
                    }
                    sb.append(">").append(nodeValue).append("</");
                    for (int j = 0; j < (currentLengthOfString); j++) {
                        sb.append("A");
                    }
                    sb.append(">");
                }
                break;
            case AttributeName:
                for (int i = 0; i < currentNumberOfElements; i++) {
                    sb.append("<attackElement ");
                    if (useNamespace) {
                        sb.append(namespace);
                    }
                    for (int j = 0; j < (currentLengthOfString); j++) {
                        sb.append("B");
                    }
                    sb.append("=\"test\">").append(nodeValue).append("</attackElement>");
                }
                break;
            case AttributeValue:
                for (int i = 0; i < currentNumberOfElements; i++) {
                    sb.append("<attackElement ");
                    if (useNamespace) {
                        sb.append(namespace);
                    }
                    sb.append("long=\"");
                    for (int j = 0; j < (currentLengthOfString); j++) {
                        sb.append("C");
                    }
                    sb.append("\">").append(nodeValue).append("</attackElement>");
                }
                break;
            default:
                break;
        }
        return payloadPosition.replacePlaceholder(xml, sb.toString());
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#minimal()
     */
    @Override
    public DoSAttack minimal() {
        XmlOverlongNames xmlOverlongNames = new XmlOverlongNames();
        xmlOverlongNames.currentFor = this.currentFor;
        xmlOverlongNames.currentLengthOfString = MIN_LENGTH_OF_STRING;
        xmlOverlongNames.currentNumberOfElements = MIN_NUMBER_OF_ELEMENTS;
        return xmlOverlongNames;
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.DoSAttack#middle(wsattacker.library.intelligentdos.dos.DoSAttack)
     */
    @Override
    public DoSAttack middle(DoSAttack aThat) {
        if (this == aThat) {
            XmlOverlongNames xmlOverlongNames = new XmlOverlongNames();
            xmlOverlongNames.currentFor = this.currentFor;
            xmlOverlongNames.currentLengthOfString = this.currentLengthOfString;
            xmlOverlongNames.currentNumberOfElements = this.currentNumberOfElements;
            return xmlOverlongNames;
        }
        if (!aThat.getClass().equals(getClass()) || !(aThat instanceof XmlOverlongNames)) {
            throw new IllegalArgumentException(aThat.getClass() + " is not allowed!");
        }
        XmlOverlongNames that = (XmlOverlongNames) aThat;
        XmlOverlongNames xmlOverlongNames = new XmlOverlongNames();
        xmlOverlongNames.currentFor = this.currentFor;
        if (this.currentLengthOfString == that.currentLengthOfString && this.currentNumberOfElements == that.currentNumberOfElements) {
            xmlOverlongNames.currentLengthOfString = this.currentLengthOfString;
            xmlOverlongNames.currentNumberOfElements = this.currentNumberOfElements;
        } else if (this.currentLengthOfString == that.currentLengthOfString) {
            xmlOverlongNames.currentLengthOfString = this.currentLengthOfString;
            xmlOverlongNames.currentNumberOfElements = calculateMiddle(this.currentNumberOfElements, that.currentNumberOfElements);
        } else if (this.currentNumberOfElements == that.currentNumberOfElements) {
            xmlOverlongNames.currentNumberOfElements = this.currentNumberOfElements;
            xmlOverlongNames.currentLengthOfString = calculateMiddle(this.currentLengthOfString, that.currentLengthOfString);
        } else {
            xmlOverlongNames.currentLengthOfString = calculateMiddle(this.currentLengthOfString, that.currentLengthOfString);
            xmlOverlongNames.currentNumberOfElements = calculateMiddle(this.currentNumberOfElements, that.currentNumberOfElements);
        }
        return xmlOverlongNames;
    }

    @Override
    public void initialize() {
        super.initialize();
        lengthOfStrings.reset();
        numberOfElements.reset();
        overlongForIterator = Arrays.asList(overlongFor).iterator();
    }

    /*
     * @see http://example.com (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        assert false : "hashCode not designed";
        // any arbitrary constant will do
        return 42;
    }

    /*
     * (non-Javadoc)
     * @see wsattacker.library.intelligentdos.dos.AbstractDoSAttack#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (!obj.getClass().equals(getClass()))
            return false;
        XmlOverlongNames that = (XmlOverlongNames) obj;
        List<DoSParam<?>> paramThis = this.getCurrentParams();
        List<DoSParam<?>> paramThat = that.getCurrentParams();
        DoSParam<?> forThis = paramThis.get(2);
        DoSParam<?> forThat = paramThat.get(2);
        return forThis.getValueAsString().equals(forThat.getValueAsString());
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    @Override
    public int compareTo(DoSAttack aThat) {
        // this optimization is usually worthwhile, and can
        // always be added
        if (this == aThat)
            return EQUAL;
        if (!aThat.getClass().equals(getClass())) {
            return EQUAL;
        }
        XmlOverlongNames that = (XmlOverlongNames) aThat;
        if (this.currentNumberOfElements < that.currentNumberOfElements)
            return BEFORE;
        if (this.currentNumberOfElements > that.currentNumberOfElements)
            return AFTER;
        if (this.currentLengthOfString < that.currentLengthOfString)
            return BEFORE;
        if (this.currentLengthOfString > that.currentLengthOfString)
            return AFTER;
        return EQUAL;
    }

    public static void main(String[] args) {
    }
}


switch(this) {
            case EMPTY:
                return "Empty";
            case PATTERN:
                return "Pattern";
            case VALUE:
                return "Value";
            case CHARS:
                return "Chars";
            default:
                return "None";
        }

package com.emmasuzuki.easyform;

public enum ErrorType {

    EMPTY, PATTERN, VALUE, CHARS, NONE;

    public static ErrorType valueOf(int value) {
        for (ErrorType errorType : ErrorType.values()) {
            if (value == errorType.ordinal()) {
                return errorType;
            }
        }
        return NONE;
    }

    @Override
    public String toString() {