for (int i = segmentsForKeys; i < totalNumSegments; i++) {
                recordsMemory.add(memory.get(i));
            }

package org.apache.flink.runtime.operators.sort;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.base.LongSerializer;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.api.java.typeutils.runtime.TupleComparator;
import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.FileChannelInputView;
import org.apache.flink.runtime.io.disk.FileChannelOutputView;
import org.apache.flink.runtime.io.disk.InputViewIterator;
import org.apache.flink.runtime.io.disk.SeekableFileChannelInputView;
import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
import org.apache.flink.runtime.memory.MemoryAllocationException;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.types.NullKeyFieldException;
import org.apache.flink.util.MutableObjectIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

public class LargeRecordHandler<T> {

    private static final Logger LOG = LoggerFactory.getLogger(LargeRecordHandler.class);

    private static final int MIN_SEGMENTS_FOR_KEY_SPILLING = 1;

    private static final int MAX_SEGMENTS_FOR_KEY_SPILLING = 4;

    private final TypeSerializer<T> serializer;

    private final TypeComparator<T> comparator;

    private TupleSerializer<Tuple> keySerializer;

    private TupleComparator<Tuple> keyComparator;

    private FileChannelOutputView recordsOutFile;

    private FileChannelOutputView keysOutFile;

    private Tuple keyTuple;

    private FileChannelInputView keysReader;

    private SeekableFileChannelInputView recordsReader;

    private FileIOChannel.ID recordsChannel;

    private FileIOChannel.ID keysChannel;

    private final IOManager ioManager;

    private final MemoryManager memManager;

    private final List<MemorySegment> memory;

    private Sorter<Tuple> keySorter;

    private final TaskInvokable memoryOwner;

    private long recordCounter;

    private int numKeyFields;

    private final int maxFilehandles;

    private volatile boolean closed;

    private final ExecutionConfig executionConfig;

    public LargeRecordHandler(TypeSerializer<T> serializer, TypeComparator<T> comparator, IOManager ioManager, MemoryManager memManager, List<MemorySegment> memory, TaskInvokable memoryOwner, int maxFilehandles, ExecutionConfig executionConfig) {
        this.serializer = checkNotNull(serializer);
        this.comparator = checkNotNull(comparator);
        this.ioManager = checkNotNull(ioManager);
        this.memManager = checkNotNull(memManager);
        this.memory = checkNotNull(memory);
        this.memoryOwner = checkNotNull(memoryOwner);
        this.maxFilehandles = maxFilehandles;
        this.executionConfig = checkNotNull(executionConfig);
        checkArgument(maxFilehandles >= 2);
    }

    @SuppressWarnings("unchecked")
    public long addRecord(T record) throws IOException {
        if (recordsOutFile == null) {
            if (closed) {
                throw new IllegalStateException("The large record handler has been closed.");
            }
            if (recordsReader != null) {
                throw new IllegalStateException("The handler has already switched to sorting.");
            }
            LOG.debug("Initializing the large record spilling...");
            // initialize the utilities
            {
                final TypeComparator<?>[] keyComps = comparator.getFlatComparators();
                numKeyFields = keyComps.length;
                Object[] keyHolder = new Object[numKeyFields];
                comparator.extractKeys(record, keyHolder, 0);
                TypeSerializer<?>[] keySers = new TypeSerializer<?>[numKeyFields];
                TypeSerializer<?>[] tupleSers = new TypeSerializer<?>[numKeyFields + 1];
                int[] keyPos = new int[numKeyFields];
                for (int i = 0; i < numKeyFields; i++) {
                    keyPos[i] = i;
                    keySers[i] = createSerializer(keyHolder[i], i);
                    tupleSers[i] = keySers[i];
                }
                // add the long serializer for the offset
                tupleSers[numKeyFields] = LongSerializer.INSTANCE;
                keySerializer = new TupleSerializer<>((Class<Tuple>) Tuple.getTupleClass(numKeyFields + 1), tupleSers);
                keyComparator = new TupleComparator<>(keyPos, keyComps, keySers);
                keyTuple = keySerializer.createInstance();
            }
            // initialize the spilling
            final int totalNumSegments = memory.size();
            final int segmentsForKeys = (totalNumSegments >= 2 * MAX_SEGMENTS_FOR_KEY_SPILLING) ? MAX_SEGMENTS_FOR_KEY_SPILLING : Math.max(MIN_SEGMENTS_FOR_KEY_SPILLING, totalNumSegments - MAX_SEGMENTS_FOR_KEY_SPILLING);
            List<MemorySegment> recordsMemory = new ArrayList<MemorySegment>();
            List<MemorySegment> keysMemory = new ArrayList<MemorySegment>();
            for (int i = 0; i < segmentsForKeys; i++) {
                keysMemory.add(memory.get(i));
            }

            recordsChannel = ioManager.createChannel();
            keysChannel = ioManager.createChannel();
            recordsOutFile = new FileChannelOutputView(ioManager.createBlockChannelWriter(recordsChannel), memManager, recordsMemory, memManager.getPageSize());
            keysOutFile = new FileChannelOutputView(ioManager.createBlockChannelWriter(keysChannel), memManager, keysMemory, memManager.getPageSize());
        }
        final long offset = recordsOutFile.getWriteOffset();
        if (offset < 0) {
            throw new RuntimeException("wrong offset");
        }
        Object[] keyHolder = new Object[numKeyFields];
        comparator.extractKeys(record, keyHolder, 0);
        for (int i = 0; i < numKeyFields; i++) {
            keyTuple.setField(keyHolder[i], i);
        }
        keyTuple.setField(offset, numKeyFields);
        keySerializer.serialize(keyTuple, keysOutFile);
        serializer.serialize(record, recordsOutFile);
        recordCounter++;
        return offset;
    }

    public MutableObjectIterator<T> finishWriteAndSortKeys(List<MemorySegment> memory) throws IOException {
        if (recordsOutFile == null || keysOutFile == null) {
            throw new IllegalStateException("The LargeRecordHandler has not spilled any records");
        }
        // close the writers and
        final int lastBlockBytesKeys;
        final int lastBlockBytesRecords;
        recordsOutFile.close();
        keysOutFile.close();
        lastBlockBytesKeys = keysOutFile.getBytesInLatestSegment();
        lastBlockBytesRecords = recordsOutFile.getBytesInLatestSegment();
        recordsOutFile = null;
        keysOutFile = null;
        final int pagesForReaders = Math.max(3 * MIN_SEGMENTS_FOR_KEY_SPILLING, Math.min(2 * MAX_SEGMENTS_FOR_KEY_SPILLING, memory.size() / 50));
        final int pagesForKeyReader = Math.min(pagesForReaders - MIN_SEGMENTS_FOR_KEY_SPILLING, MAX_SEGMENTS_FOR_KEY_SPILLING);
        final int pagesForRecordReader = pagesForReaders - pagesForKeyReader;
        // grab memory for the record reader
        ArrayList<MemorySegment> memForRecordReader = new ArrayList<MemorySegment>();
        ArrayList<MemorySegment> memForKeysReader = new ArrayList<MemorySegment>();
        for (int i = 0; i < pagesForRecordReader; i++) {
            memForRecordReader.add(memory.remove(memory.size() - 1));
        }
        for (int i = 0; i < pagesForKeyReader; i++) {
            memForKeysReader.add(memory.remove(memory.size() - 1));
        }
        keysReader = new FileChannelInputView(ioManager.createBlockChannelReader(keysChannel), memManager, memForKeysReader, lastBlockBytesKeys);
        InputViewIterator<Tuple> keyIterator = new InputViewIterator<Tuple>(keysReader, keySerializer);
        try {
            keySorter = ExternalSorter.newBuilder(memManager, memoryOwner, keySerializer, keyComparator, executionConfig).maxNumFileHandles(maxFilehandles).sortBuffers(1).enableSpilling(ioManager, 1.0f).memory(memory).objectReuse(this.executionConfig.isObjectReuseEnabled()).largeRecords(false).build(keyIterator);
        } catch (MemoryAllocationException e) {
            throw new IllegalStateException("We should not try allocating memory. Instead the sorter should use the provided memory.", e);
        }
        // wait for the sorter to sort the keys
        MutableObjectIterator<Tuple> result;
        try {
            result = keySorter.getIterator();
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
        recordsReader = new SeekableFileChannelInputView(ioManager, recordsChannel, memManager, memForRecordReader, lastBlockBytesRecords);
        return new FetchingIterator<T>(serializer, result, recordsReader, keySerializer, numKeyFields);
    }

    /**
     * Closes all structures and deletes all temporary files. Even in the presence of failures, this
     * method will try and continue closing files and deleting temporary files.
     *
     * @throws IOException Thrown if an error occurred while closing/deleting the files.
     */
    public void close() throws IOException {
        // we go on closing and deleting files in the presence of failures.
        // we remember the first exception to occur and re-throw it later
        Throwable ex = null;
        synchronized (this) {
            if (closed) {
                return;
            }
            closed = true;
            // close the writers
            if (recordsOutFile != null) {
                try {
                    recordsOutFile.close();
                    recordsOutFile = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records spill file.", t);
                    ex = t;
                }
            }
            if (keysOutFile != null) {
                try {
                    keysOutFile.close();
                    keysOutFile = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records key spill file.", t);
                    ex = ex == null ? t : ex;
                }
            }
            // close the readers
            if (recordsReader != null) {
                try {
                    recordsReader.close();
                    recordsReader = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records reader.", t);
                    ex = ex == null ? t : ex;
                }
            }
            if (keysReader != null) {
                try {
                    keysReader.close();
                    keysReader = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records key reader.", t);
                    ex = ex == null ? t : ex;
                }
            }
            // delete the spill files
            if (recordsChannel != null) {
                try {
                    ioManager.deleteChannel(recordsChannel);
                    recordsChannel = null;
                } catch (Throwable t) {
                    LOG.error("Cannot delete the large records spill file.", t);
                    ex = ex == null ? t : ex;
                }
            }
            if (keysChannel != null) {
                try {
                    ioManager.deleteChannel(keysChannel);
                    keysChannel = null;
                } catch (Throwable t) {
                    LOG.error("Cannot delete the large records key spill file.", t);
                    ex = ex == null ? t : ex;
                }
            }
            // close the key sorter
            if (keySorter != null) {
                try {
                    keySorter.close();
                    keySorter = null;
                } catch (Throwable t) {
                    LOG.error("Cannot properly dispose the key sorter and clean up its temporary files.", t);
                    ex = ex == null ? t : ex;
                }
            }
            memManager.release(memory);
            recordCounter = 0;
        }
        if (ex != null) {
            throw new IOException("An error occurred cleaning up spill files in the large record handler.", ex);
        }
    }

    public boolean hasData() {
        return recordCounter > 0;
    }

    private TypeSerializer<Object> createSerializer(Object key, int pos) {
        if (key == null) {
            throw new NullKeyFieldException(pos);
        }
        try {
            TypeInformation<Object> info = TypeExtractor.getForObject(key);
            return info.createSerializer(executionConfig);
        } catch (Throwable t) {
            throw new RuntimeException("Could not create key serializer for type " + key);
        }
    }

    private static final class FetchingIterator<T> implements MutableObjectIterator<T> {

        private final TypeSerializer<T> serializer;

        private final MutableObjectIterator<Tuple> tupleInput;

        private final SeekableFileChannelInputView recordsInputs;

        private Tuple value;

        private final int pointerPos;

        public FetchingIterator(TypeSerializer<T> serializer, MutableObjectIterator<Tuple> tupleInput, SeekableFileChannelInputView recordsInputs, TypeSerializer<Tuple> tupleSerializer, int pointerPos) {
            this.serializer = serializer;
            this.tupleInput = tupleInput;
            this.recordsInputs = recordsInputs;
            this.pointerPos = pointerPos;
            this.value = tupleSerializer.createInstance();
        }

        @Override
        public T next(T reuse) throws IOException {
            return next();
        }

        @Override
        public T next() throws IOException {
            Tuple value = tupleInput.next(this.value);
            if (value != null) {
                this.value = value;
                long pointer = value.<Long>getField(pointerPos);
                recordsInputs.seek(pointer);
                return serializer.deserialize(recordsInputs);
            } else {
                return null;
            }
        }
    }
}


try {
                    ioManager.deleteChannel(keysChannel);
                    keysChannel = null;
                } catch (Throwable t) {
                    LOG.error("Cannot delete the large records key spill file.", t);
                    ex = ex == null ? t : ex;
                }

package org.apache.flink.runtime.operators.sort;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.base.LongSerializer;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.api.java.typeutils.runtime.TupleComparator;
import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.FileChannelInputView;
import org.apache.flink.runtime.io.disk.FileChannelOutputView;
import org.apache.flink.runtime.io.disk.InputViewIterator;
import org.apache.flink.runtime.io.disk.SeekableFileChannelInputView;
import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
import org.apache.flink.runtime.memory.MemoryAllocationException;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.types.NullKeyFieldException;
import org.apache.flink.util.MutableObjectIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

public class LargeRecordHandler<T> {

    private static final Logger LOG = LoggerFactory.getLogger(LargeRecordHandler.class);

    private static final int MIN_SEGMENTS_FOR_KEY_SPILLING = 1;

    private static final int MAX_SEGMENTS_FOR_KEY_SPILLING = 4;

    private final TypeSerializer<T> serializer;

    private final TypeComparator<T> comparator;

    private TupleSerializer<Tuple> keySerializer;

    private TupleComparator<Tuple> keyComparator;

    private FileChannelOutputView recordsOutFile;

    private FileChannelOutputView keysOutFile;

    private Tuple keyTuple;

    private FileChannelInputView keysReader;

    private SeekableFileChannelInputView recordsReader;

    private FileIOChannel.ID recordsChannel;

    private FileIOChannel.ID keysChannel;

    private final IOManager ioManager;

    private final MemoryManager memManager;

    private final List<MemorySegment> memory;

    private Sorter<Tuple> keySorter;

    private final TaskInvokable memoryOwner;

    private long recordCounter;

    private int numKeyFields;

    private final int maxFilehandles;

    private volatile boolean closed;

    private final ExecutionConfig executionConfig;

    public LargeRecordHandler(TypeSerializer<T> serializer, TypeComparator<T> comparator, IOManager ioManager, MemoryManager memManager, List<MemorySegment> memory, TaskInvokable memoryOwner, int maxFilehandles, ExecutionConfig executionConfig) {
        this.serializer = checkNotNull(serializer);
        this.comparator = checkNotNull(comparator);
        this.ioManager = checkNotNull(ioManager);
        this.memManager = checkNotNull(memManager);
        this.memory = checkNotNull(memory);
        this.memoryOwner = checkNotNull(memoryOwner);
        this.maxFilehandles = maxFilehandles;
        this.executionConfig = checkNotNull(executionConfig);
        checkArgument(maxFilehandles >= 2);
    }

    @SuppressWarnings("unchecked")
    public long addRecord(T record) throws IOException {
        if (recordsOutFile == null) {
            if (closed) {
                throw new IllegalStateException("The large record handler has been closed.");
            }
            if (recordsReader != null) {
                throw new IllegalStateException("The handler has already switched to sorting.");
            }
            LOG.debug("Initializing the large record spilling...");
            // initialize the utilities
            {
                final TypeComparator<?>[] keyComps = comparator.getFlatComparators();
                numKeyFields = keyComps.length;
                Object[] keyHolder = new Object[numKeyFields];
                comparator.extractKeys(record, keyHolder, 0);
                TypeSerializer<?>[] keySers = new TypeSerializer<?>[numKeyFields];
                TypeSerializer<?>[] tupleSers = new TypeSerializer<?>[numKeyFields + 1];
                int[] keyPos = new int[numKeyFields];
                for (int i = 0; i < numKeyFields; i++) {
                    keyPos[i] = i;
                    keySers[i] = createSerializer(keyHolder[i], i);
                    tupleSers[i] = keySers[i];
                }
                // add the long serializer for the offset
                tupleSers[numKeyFields] = LongSerializer.INSTANCE;
                keySerializer = new TupleSerializer<>((Class<Tuple>) Tuple.getTupleClass(numKeyFields + 1), tupleSers);
                keyComparator = new TupleComparator<>(keyPos, keyComps, keySers);
                keyTuple = keySerializer.createInstance();
            }
            // initialize the spilling
            final int totalNumSegments = memory.size();
            final int segmentsForKeys = (totalNumSegments >= 2 * MAX_SEGMENTS_FOR_KEY_SPILLING) ? MAX_SEGMENTS_FOR_KEY_SPILLING : Math.max(MIN_SEGMENTS_FOR_KEY_SPILLING, totalNumSegments - MAX_SEGMENTS_FOR_KEY_SPILLING);
            List<MemorySegment> recordsMemory = new ArrayList<MemorySegment>();
            List<MemorySegment> keysMemory = new ArrayList<MemorySegment>();
            for (int i = 0; i < segmentsForKeys; i++) {
                keysMemory.add(memory.get(i));
            }
            for (int i = segmentsForKeys; i < totalNumSegments; i++) {
                recordsMemory.add(memory.get(i));
            }
            recordsChannel = ioManager.createChannel();
            keysChannel = ioManager.createChannel();
            recordsOutFile = new FileChannelOutputView(ioManager.createBlockChannelWriter(recordsChannel), memManager, recordsMemory, memManager.getPageSize());
            keysOutFile = new FileChannelOutputView(ioManager.createBlockChannelWriter(keysChannel), memManager, keysMemory, memManager.getPageSize());
        }
        final long offset = recordsOutFile.getWriteOffset();
        if (offset < 0) {
            throw new RuntimeException("wrong offset");
        }
        Object[] keyHolder = new Object[numKeyFields];
        comparator.extractKeys(record, keyHolder, 0);
        for (int i = 0; i < numKeyFields; i++) {
            keyTuple.setField(keyHolder[i], i);
        }
        keyTuple.setField(offset, numKeyFields);
        keySerializer.serialize(keyTuple, keysOutFile);
        serializer.serialize(record, recordsOutFile);
        recordCounter++;
        return offset;
    }

    public MutableObjectIterator<T> finishWriteAndSortKeys(List<MemorySegment> memory) throws IOException {
        if (recordsOutFile == null || keysOutFile == null) {
            throw new IllegalStateException("The LargeRecordHandler has not spilled any records");
        }
        // close the writers and
        final int lastBlockBytesKeys;
        final int lastBlockBytesRecords;
        recordsOutFile.close();
        keysOutFile.close();
        lastBlockBytesKeys = keysOutFile.getBytesInLatestSegment();
        lastBlockBytesRecords = recordsOutFile.getBytesInLatestSegment();
        recordsOutFile = null;
        keysOutFile = null;
        final int pagesForReaders = Math.max(3 * MIN_SEGMENTS_FOR_KEY_SPILLING, Math.min(2 * MAX_SEGMENTS_FOR_KEY_SPILLING, memory.size() / 50));
        final int pagesForKeyReader = Math.min(pagesForReaders - MIN_SEGMENTS_FOR_KEY_SPILLING, MAX_SEGMENTS_FOR_KEY_SPILLING);
        final int pagesForRecordReader = pagesForReaders - pagesForKeyReader;
        // grab memory for the record reader
        ArrayList<MemorySegment> memForRecordReader = new ArrayList<MemorySegment>();
        ArrayList<MemorySegment> memForKeysReader = new ArrayList<MemorySegment>();
        for (int i = 0; i < pagesForRecordReader; i++) {
            memForRecordReader.add(memory.remove(memory.size() - 1));
        }
        for (int i = 0; i < pagesForKeyReader; i++) {
            memForKeysReader.add(memory.remove(memory.size() - 1));
        }
        keysReader = new FileChannelInputView(ioManager.createBlockChannelReader(keysChannel), memManager, memForKeysReader, lastBlockBytesKeys);
        InputViewIterator<Tuple> keyIterator = new InputViewIterator<Tuple>(keysReader, keySerializer);
        try {
            keySorter = ExternalSorter.newBuilder(memManager, memoryOwner, keySerializer, keyComparator, executionConfig).maxNumFileHandles(maxFilehandles).sortBuffers(1).enableSpilling(ioManager, 1.0f).memory(memory).objectReuse(this.executionConfig.isObjectReuseEnabled()).largeRecords(false).build(keyIterator);
        } catch (MemoryAllocationException e) {
            throw new IllegalStateException("We should not try allocating memory. Instead the sorter should use the provided memory.", e);
        }
        // wait for the sorter to sort the keys
        MutableObjectIterator<Tuple> result;
        try {
            result = keySorter.getIterator();
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
        recordsReader = new SeekableFileChannelInputView(ioManager, recordsChannel, memManager, memForRecordReader, lastBlockBytesRecords);
        return new FetchingIterator<T>(serializer, result, recordsReader, keySerializer, numKeyFields);
    }

    /**
     * Closes all structures and deletes all temporary files. Even in the presence of failures, this
     * method will try and continue closing files and deleting temporary files.
     *
     * @throws IOException Thrown if an error occurred while closing/deleting the files.
     */
    public void close() throws IOException {
        // we go on closing and deleting files in the presence of failures.
        // we remember the first exception to occur and re-throw it later
        Throwable ex = null;
        synchronized (this) {
            if (closed) {
                return;
            }
            closed = true;
            // close the writers
            if (recordsOutFile != null) {
                try {
                    recordsOutFile.close();
                    recordsOutFile = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records spill file.", t);
                    ex = t;
                }
            }
            if (keysOutFile != null) {
                try {
                    keysOutFile.close();
                    keysOutFile = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records key spill file.", t);
                    ex = ex == null ? t : ex;
                }
            }
            // close the readers
            if (recordsReader != null) {
                try {
                    recordsReader.close();
                    recordsReader = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records reader.", t);
                    ex = ex == null ? t : ex;
                }
            }
            if (keysReader != null) {
                try {
                    keysReader.close();
                    keysReader = null;
                } catch (Throwable t) {
                    LOG.error("Cannot close the large records key reader.", t);
                    ex = ex == null ? t : ex;
                }
            }
            // delete the spill files
            if (recordsChannel != null) {
                try {
                    ioManager.deleteChannel(recordsChannel);
                    recordsChannel = null;
                } catch (Throwable t) {
                    LOG.error("Cannot delete the large records spill file.", t);
                    ex = ex == null ? t : ex;
                }
            }
            if (keysChannel != null) {

            }
            // close the key sorter
            if (keySorter != null) {
                try {
                    keySorter.close();
                    keySorter = null;
                } catch (Throwable t) {
                    LOG.error("Cannot properly dispose the key sorter and clean up its temporary files.", t);
                    ex = ex == null ? t : ex;
                }
            }
            memManager.release(memory);
            recordCounter = 0;
        }
        if (ex != null) {
            throw new IOException("An error occurred cleaning up spill files in the large record handler.", ex);
        }
    }

    public boolean hasData() {
        return recordCounter > 0;
    }

    private TypeSerializer<Object> createSerializer(Object key, int pos) {
        if (key == null) {
            throw new NullKeyFieldException(pos);
        }
        try {
            TypeInformation<Object> info = TypeExtractor.getForObject(key);
            return info.createSerializer(executionConfig);
        } catch (Throwable t) {
            throw new RuntimeException("Could not create key serializer for type " + key);
        }
    }

    private static final class FetchingIterator<T> implements MutableObjectIterator<T> {

        private final TypeSerializer<T> serializer;

        private final MutableObjectIterator<Tuple> tupleInput;

        private final SeekableFileChannelInputView recordsInputs;

        private Tuple value;

        private final int pointerPos;

        public FetchingIterator(TypeSerializer<T> serializer, MutableObjectIterator<Tuple> tupleInput, SeekableFileChannelInputView recordsInputs, TypeSerializer<Tuple> tupleSerializer, int pointerPos) {
            this.serializer = serializer;
            this.tupleInput = tupleInput;
            this.recordsInputs = recordsInputs;
            this.pointerPos = pointerPos;
            this.value = tupleSerializer.createInstance();
        }

        @Override
        public T next(T reuse) throws IOException {
            return next();
        }

        @Override
        public T next() throws IOException {
            Tuple value = tupleInput.next(this.value);
            if (value != null) {
                this.value = value;
                long pointer = value.<Long>getField(pointerPos);
                recordsInputs.seek(pointer);
                return serializer.deserialize(recordsInputs);
            } else {
                return null;
            }
        }
    }
}


try {
                        dfsDirectories.add(e.getLocation().toString());
                    } catch (Exception ex) {
                        throw new EntityException(ex);
                    }

package com.airbnb.reair.hive.hooks;

import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.hooks.Entity;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TJSONProtocol;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Log module for adding core query audit data for a query to the DB.
 */
public class AuditCoreLogModule extends BaseLogModule {

    public static Logger LOG = Logger.getLogger(AuditCoreLogModule.class);

    public static final String TABLE_NAME_KEY = "airbnb.reair.audit_log.core.table_name";

    private final Set<ReadEntity> readEntities;

    private final Set<WriteEntity> writeEntities;

    private final UserGroupInformation userGroupInformation;

    /**
     * Constructor.
     *
     * @param connection the connection to use for connecting to the DB
     * @param sessionStateLite session information from Hive for this query
     * @param readEntities the entities that were read by the query
     * @param writeEntities the entities that were written by the query
     * @param userGroupInformation information about the user that ran the query
     *
     * @throws ConfigurationException if there's an error with the configuration for the hook
     */
    public AuditCoreLogModule(final Connection connection, final SessionStateLite sessionStateLite, final Set<ReadEntity> readEntities, final Set<WriteEntity> writeEntities, final UserGroupInformation userGroupInformation) throws ConfigurationException {
        super(connection, TABLE_NAME_KEY, sessionStateLite);
        this.readEntities = readEntities;
        this.writeEntities = writeEntities;
        this.userGroupInformation = userGroupInformation;
    }

    /**
     * Inserts the core audit data into the DB.
     *
     * @return the id for the inserted core audit log entry
     *
     * @throws EntityException if there's an error processing the entities associated with this query
     * @throws SQLException if there's an error querying the DB
     * @throws UnknownHostException if there's an error getting the IP of this host
     */
    public long run() throws EntityException, SerializationException, SQLException, UnknownHostException {
        final String query = String.format("INSERT INTO %s (" + "query_id, " + "command_type, " + "command, " + "inputs, " + "outputs, " + "username, " + "ip) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", tableName);
        // Write the main audit log entry
        int psIndex = 1;
        PreparedStatement ps = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        ps.setString(psIndex++, sessionStateLite.getQueryId());
        ps.setString(psIndex++, sessionStateLite.getCommandType());
        ps.setString(psIndex++, sessionStateLite.getCmd());
        ps.setString(psIndex++, toJson(readEntities, true));
        ps.setString(psIndex++, toJson(writeEntities, true));
        ps.setString(psIndex++, userGroupInformation == null ? null : userGroupInformation.getUserName());
        ps.setString(psIndex++, InetAddress.getLocalHost().getHostAddress());
        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        rs.next();
        return rs.getLong(1);
    }

    /**
     * Converts the entities into a JSON object. Resulting object will look
     * like:
     * {
     *   "tables": [t1, t2...],
     *   "partitions": [p1, p2...],
     *   "dummy_partitions": [p1, p2...],
     *   "local_directories": [d1, d2...],
     *   "dfs_directories": [d1, d2...]
     * }
     *
     * <p>Where t1... and p1... objects are JSON objects that represent the thrift
     * metadata object. If identifierOnly is true, then only a short string
     * representation of the object will be used instead. e.g.
     * "default.my_table" or "default.my_partitioned_table/ds=1"
     *
     * @param entities the entities to convert into JSON
     * @param identifierOnly whether to use identifiers instead of the full JSON representation
     * @return a JSON string representing the entities
     * @throws EntityException if there's an error processing an entity
     * @throws SerializationException if there's an error serializing to JSON
     */
    private static String toJson(Collection<? extends Entity> entities, boolean identifierOnly) throws EntityException, SerializationException {
        if (entities == null) {
            return new JSONObject().toString();
        }
        List<Database> databases = new ArrayList<>();
        List<Table> tables = new ArrayList<>();
        List<Partition> partitions = new ArrayList<>();
        List<Partition> dummyPartitions = new ArrayList<>();
        List<String> localDirectories = new ArrayList<>();
        List<String> dfsDirectories = new ArrayList<>();
        Map<Partition, String> partitionNames = new HashMap<>();
        for (Entity e : entities) {
            switch(e.getType()) {
                case DATABASE:
                    databases.add(e.getDatabase());
                    break;
                case TABLE:
                    tables.add(e.getTable().getTTable());
                    break;
                case PARTITION:
                    partitions.add(e.getPartition().getTPartition());
                    partitionNames.put(e.getPartition().getTPartition(), e.getPartition().getName());
                    break;
                case DUMMYPARTITION:
                    dummyPartitions.add(e.getPartition().getTPartition());
                    partitionNames.put(e.getPartition().getTPartition(), e.getPartition().getName());
                    break;
                case LOCAL_DIR:
                    try {
                        localDirectories.add(e.getLocation().toString());
                    } catch (Exception ex) {
                        throw new EntityException(ex);
                    }
                    break;
                case DFS_DIR:

                    break;
                case UDF:
                    LOG.info("Skipping logging of UDF type to audit log - " + "displayName: " + e.getUDF().getDisplayName());
                    break;
                default:
                    throw new EntityException("Unhandled type: " + e.getType() + " entity: " + e);
            }
        }
        TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
        JSONArray jsonDatabases = new JSONArray();
        JSONArray jsonTables = new JSONArray();
        JSONArray jsonPartitions = new JSONArray();
        JSONArray jsonDummyPartitions = new JSONArray();
        JSONArray jsonLocalDirs = new JSONArray();
        JSONArray jsonDfsDirs = new JSONArray();
        JSONObject obj = new JSONObject();
        try {
            for (Database db : databases) {
                if (identifierOnly) {
                    String jsonDatabase = String.format("%s", db.getName());
                    jsonDatabases.put(jsonDatabase);
                } else {
                    jsonDatabases.put(new JSONObject(serializer.toString(db)));
                }
            }
            for (Table t : tables) {
                if (identifierOnly) {
                    String jsonTable = String.format("%s.%s", t.getDbName(), t.getTableName());
                    jsonTables.put(jsonTable);
                } else {
                    jsonTables.put(new JSONObject(serializer.toString(t)));
                }
            }
            for (Partition p : partitions) {
                if (identifierOnly) {
                    String partitionName = String.format("%s.%s/%s", p.getDbName(), p.getTableName(), partitionNames.get(p));
                    jsonPartitions.put(partitionName);
                } else {
                    jsonPartitions.put(new JSONObject(serializer.toString(p)));
                }
            }
            for (Partition p : dummyPartitions) {
                if (identifierOnly) {
                    String dummyPartitionJson = String.format("%s.%s/%s", p.getDbName(), p.getTableName(), partitionNames.get(p));
                    jsonDummyPartitions.put(dummyPartitionJson);
                } else {
                    jsonDummyPartitions.put(new JSONObject(serializer.toString(p)));
                }
            }
            for (String dir : localDirectories) {
                jsonLocalDirs.put(dir);
            }
            for (String dir : dfsDirectories) {
                jsonDfsDirs.put(dir);
            }
            if (jsonDatabases.length() > 0) {
                obj.put("databases", jsonDatabases);
            }
            if (jsonTables.length() > 0) {
                obj.put("tables", jsonTables);
            }
            if (jsonPartitions.length() > 0) {
                obj.put("partitions", jsonPartitions);
            }
            if (jsonDummyPartitions.length() > 0) {
                obj.put("dummy_partitions", jsonDummyPartitions);
            }
            if (jsonLocalDirs.length() > 0) {
                obj.put("local_directories", jsonLocalDirs);
            }
            if (jsonDfsDirs.length() > 0) {
                obj.put("dfs_directories", jsonDfsDirs);
            }
        } catch (TException | JSONException e) {
            throw new SerializationException(e);
        }
        return obj.toString();
    }
}


public static OpTypeEnum getByCode(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        for (OpTypeEnum type : OpTypeEnum.values()) {
            if (type.getCode().equals(code.toLowerCase())) {
                return type;
            }
        }
        return null;
    }

package com.yiranpay.member.enums;

import org.apache.commons.lang3.StringUtils;

public enum OpTypeEnum {

    LOGIN("login", "登陆");

    /**
     * 代码
     */
    private final String code;

    /**
     * 信息
     */
    private final String message;

    /**
     * 构造
     * @param code
     * @param message
     */
    OpTypeEnum(String code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 根据代码获取
     * @param code
     * @return
     */

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}


void asyncResponse(E exception, AsyncExceptionMapperContext context);

package org.jboss.resteasy.reactive.server.spi;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

/**
 * Allow ExceptionMapper classes that can use resume and suspend when attempting to convert
 * an exception into a response
 */
public interface ResteasyReactiveAsyncExceptionMapper<E extends Throwable> extends ExceptionMapper<E> {

    /**
     * If the handling of the exception involves async handling async results, the implementation can
     * use {@link AsyncExceptionMapperContext#suspend()} and {@link AsyncExceptionMapperContext#resume()}.
     *
     * In all cases, tt is the responsibility of the implementation to call
     * {@link AsyncExceptionMapperContext#setResponse(Response)}
     * when the exception has been properly mapped.
     */

    default Response toResponse(E exception) {
        throw new IllegalStateException("This should never have been called");
    }
}


try {
            inUse = true;
            callable.run();
        } finally {
            inUse = false;
        }

package ghidra.trace.util;

public class MethodProtector {

    private boolean inUse;

    public interface TemperamentalCallable<E extends Throwable> {

        void run() throws E;
    }

    public <E extends Throwable> void take(TemperamentalCallable<E> callable) throws E {
        if (inUse) {
            return;
        }

    }

    public <E extends Throwable> void avoid(TemperamentalCallable<E> callable) throws E {
        if (inUse) {
            return;
        }
        callable.run();
    }
}


while ((r = s.read(buffer)) != -1) {
                        // NOPMD
                        writer.write(buffer, 0, r);
                    }

package kieker.tools.trace.analysis.gui;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Locale;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Nils Christian Ehmke
 *
 * @since 1.10
 */
public class ConversionStep extends AbstractStep {

    private static final long serialVersionUID = 1L;

    private static final String PROPERTY_KEY_IDENTIFIER = ConversionStep.class.getSimpleName();

    private static final String PROPERTY_KEY_PERFORM_STEP = PROPERTY_KEY_IDENTIFIER + ".performStep";

    private static final String PROPERTY_KEY_GRAPHVIZ = PROPERTY_KEY_IDENTIFIER + ".graphvizDirectoryField";

    private static final String PROPERTY_KEY_PIC2PLOT = PROPERTY_KEY_IDENTIFIER + ".pic2plotDirectoryField";

    private static final String PROPERTY_KEY_OUTPUT_FORMAT = PROPERTY_KEY_IDENTIFIER + ".outputFormatField";

    private static final String GRAPHVIZ_DIR_TEXT_FIELD_TOOLTIP = "The graphviz directory contains the path to the graphviz binary. Required for conversion.";

    private static final String PIC2PLOT_DIR_TEXT_FIELD_TOOLTIP = "The pic2plot directory contains the path to the pic2plot binary. Required for conversion.";

    private static final Logger LOGGER = LoggerFactory.getLogger(ConversionStep.class);

    private final String currentPath = new File(".").getAbsolutePath();

    private final JLabel infoLabel = new JLabel("In this step you manage Graphviz and Pic2Plot in order to convert the results from the trace " + "analysis.

WARNING: If selected, this step will overwrite existing files in your output directory.");

    private final JPanel expandingPanel1 = new JPanel();

    private final JPanel expandingPanel2 = new JPanel();

    private final JCheckBox performStep = new JCheckBox("Perform File Conversion");

    private final JLabel graphvizDirectoryLabel = new JLabel("Graphviz Directory: ");

    private final JLabel pic2plotDirectoryLabel = new JLabel("Pic2Plot Directory: ");

    private final JTextField graphvizDirectoryField = new JTextField(this.currentPath);

    private final JTextField pic2plotDirectoryField = new JTextField(this.currentPath);

    private final JButton graphvizDirectoryChooseButton = new JButton("Choose");

    private final JButton pic2plotDirectoryChooseButton = new JButton("Choose");

    private final JLabel outputFormat = new JLabel("Output Format: ");

    private final JComboBox<String> outputFormatField = new JComboBox<>(new String[] { "PNG", "JPEG", "SVG", "PDF" });

    public ConversionStep() {
        this.addAndLayoutComponents();
        this.addLogicToComponents();
        this.addToolTipsToComponents();
    }

    private void addAndLayoutComponents() {
        this.setLayout(new GridBagLayout());
        final GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        this.add(this.infoLabel, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.insets.set(5, 5, 0, 0);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        this.add(this.performStep, gridBagConstraints);
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.weightx = 0.0;
        this.add(this.graphvizDirectoryLabel, gridBagConstraints);
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        this.add(this.graphvizDirectoryField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.weightx = 0.0;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.graphvizDirectoryChooseButton, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.pic2plotDirectoryLabel, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        this.add(this.pic2plotDirectoryField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.pic2plotDirectoryChooseButton, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        this.add(this.outputFormat, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.EAST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        this.add(this.outputFormatField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        this.add(this.expandingPanel1, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        this.add(this.expandingPanel2, gridBagConstraints);
    }

    private void addLogicToComponents() {
        this.graphvizDirectoryChooseButton.addActionListener(new ChooseDirectoryActionListener(this.graphvizDirectoryField, this));
        this.pic2plotDirectoryChooseButton.addActionListener(new ChooseDirectoryActionListener(this.pic2plotDirectoryField, this));
        this.performStep.addActionListener(new ActionListener() {

            @Override
            @SuppressWarnings("synthetic-access")
            public void actionPerformed(final ActionEvent e) {
                ConversionStep.this.graphvizDirectoryField.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.pic2plotDirectoryField.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.graphvizDirectoryChooseButton.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.pic2plotDirectoryChooseButton.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.outputFormatField.setEnabled(ConversionStep.this.performStep.isSelected());
            }
        });
    }

    private void addToolTipsToComponents() {
        this.graphvizDirectoryField.setToolTipText(GRAPHVIZ_DIR_TEXT_FIELD_TOOLTIP);
        this.pic2plotDirectoryField.setToolTipText(PIC2PLOT_DIR_TEXT_FIELD_TOOLTIP);
    }

    @Override
    public void addSelectedTraceAnalysisParameters(final Collection<String> parameters) {
        // Nothing to add here
    }

    public void convert(final String outputDirectory) {
        if (this.performStep.isSelected()) {
            final File outputDir = new File(outputDirectory);
            final File[] dotFiles = outputDir.listFiles(new FileNameExtensionFilter(".dot"));
            if (dotFiles == null) {
                return;
            }
            for (final File dotFile : dotFiles) {
                try {
                    final Process p = Runtime.getRuntime().exec(new String[] { this.graphvizDirectoryField.getText() + "/dot", "-O", "-T" + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH), dotFile.getAbsolutePath() });
                    p.waitFor();
                } catch (final IOException | InterruptedException e) {
                    LOGGER.warn("An exception occurred", e);
                }
            }
            final File[] picFiles = outputDir.listFiles(new FileNameExtensionFilter(".pic"));
            if (picFiles == null) {
                return;
            }
            for (final File picFile : picFiles) {
                OutputStream writer = null;
                try {
                    final Process p = Runtime.getRuntime().exec(new String[] { this.pic2plotDirectoryField.getText() + "/pic2plot", "-T" + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH), picFile.getAbsolutePath() });
                    final InputStream s = p.getInputStream();
                    writer = new FileOutputStream(picFile.getAbsolutePath() + "." + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH));
                    int r;
                    final byte[] buffer = new byte[10 * 1024];

                    writer.close();
                    s.close();
                    p.waitFor();
                } catch (final IOException | InterruptedException e) {
                    LOGGER.warn("An exception occurred", e);
                } finally {
                    if (null != writer) {
                        try {
                            writer.close();
                        } catch (final IOException e) {
                            LOGGER.warn("An exception occurred", e);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void loadDefaultConfiguration() {
        this.graphvizDirectoryField.setText(this.currentPath);
        this.pic2plotDirectoryField.setText(this.currentPath);
        this.outputFormatField.setSelectedIndex(0);
        this.graphvizDirectoryField.setEnabled(false);
        this.pic2plotDirectoryField.setEnabled(false);
        this.graphvizDirectoryChooseButton.setEnabled(false);
        this.pic2plotDirectoryChooseButton.setEnabled(false);
        this.outputFormatField.setEnabled(false);
    }

    @Override
    public void saveCurrentConfiguration(final Properties properties) {
        properties.setProperty(PROPERTY_KEY_PERFORM_STEP, Boolean.toString(this.performStep.isSelected()));
        properties.setProperty(PROPERTY_KEY_GRAPHVIZ, this.graphvizDirectoryField.getText());
        properties.setProperty(PROPERTY_KEY_PIC2PLOT, this.pic2plotDirectoryField.getText());
        properties.setProperty(PROPERTY_KEY_OUTPUT_FORMAT, Integer.toString(this.outputFormatField.getSelectedIndex()));
    }

    @Override
    public void loadCurrentConfiguration(final Properties properties) {
        this.performStep.setSelected(Boolean.parseBoolean(properties.getProperty(PROPERTY_KEY_PERFORM_STEP)));
        this.graphvizDirectoryField.setText(properties.getProperty(PROPERTY_KEY_GRAPHVIZ));
        this.pic2plotDirectoryField.setText(properties.getProperty(PROPERTY_KEY_PIC2PLOT));
        this.outputFormatField.setSelectedIndex(Integer.parseInt(properties.getProperty(PROPERTY_KEY_OUTPUT_FORMAT)));
        this.graphvizDirectoryField.setEnabled(this.performStep.isSelected());
        this.pic2plotDirectoryField.setEnabled(this.performStep.isSelected());
        this.graphvizDirectoryChooseButton.setEnabled(this.performStep.isSelected());
        this.pic2plotDirectoryChooseButton.setEnabled(this.performStep.isSelected());
        this.outputFormatField.setEnabled(this.performStep.isSelected());
    }

    @Override
    public boolean isNextStepAllowed() {
        final boolean performThisStep = this.performStep.isSelected();
        if (performThisStep) {
            final boolean graphvizAvailable = this.checkGraphvizExecutable();
            if (!graphvizAvailable) {
                final int result = JOptionPane.showConfirmDialog(this, "The Graphviz executable could not be found. Continue?", "Graphviz Executable", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (JOptionPane.NO_OPTION == result) {
                    return false;
                }
            }
            final boolean pic2PlotAvailable = this.checkPic2PlotExecutable();
            if (!pic2PlotAvailable) {
                final int result = JOptionPane.showConfirmDialog(this, "The Pic2Plot executable could not be found. Continue?", "Pic2Plot Executable", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                return (JOptionPane.YES_OPTION == result);
            }
        }
        return true;
    }

    private boolean checkPic2PlotExecutable() {
        return this.checkExecutable(this.pic2plotDirectoryField.getText() + "/pic2plot", "--v");
    }

    private boolean checkGraphvizExecutable() {
        return this.checkExecutable(this.graphvizDirectoryField.getText() + "/dot", "-V");
    }

    private boolean checkExecutable(final String command, final String parameter) {
        final Process p;
        try {
            p = Runtime.getRuntime().exec(new String[] { command, parameter });
            return (0 == p.waitFor());
        } catch (final IOException | InterruptedException e) {
            return false;
        }
    }

    /**
     * @author Nils Christian Ehmke
     *
     * @since 1.10
     */
    private static class ChooseDirectoryActionListener implements ActionListener {

        private final JTextField textField;

        private final Component parent;

        public ChooseDirectoryActionListener(final JTextField textField, final Component parent) {
            this.textField = textField;
            this.parent = parent;
        }

        @Override
        public void actionPerformed(final ActionEvent event) {
            final JFileChooser fileChooser = new JFileChooser(this.textField.getText());
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.showOpenDialog(this.parent) == JFileChooser.APPROVE_OPTION) {
                this.textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
            }
        }
    }

    /**
     * @author Nils Christian Ehmke
     *
     * @since 1.10
     */
    private static class FileNameExtensionFilter implements FilenameFilter {

        private final String extension;

        public FileNameExtensionFilter(final String extension) {
            this.extension = extension;
        }

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith(this.extension);
        }
    }
}


try {
            p = Runtime.getRuntime().exec(new String[] { command, parameter });
            return (0 == p.waitFor());
        } catch (final IOException | InterruptedException e) {
            return false;
        }

package kieker.tools.trace.analysis.gui;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Locale;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Nils Christian Ehmke
 *
 * @since 1.10
 */
public class ConversionStep extends AbstractStep {

    private static final long serialVersionUID = 1L;

    private static final String PROPERTY_KEY_IDENTIFIER = ConversionStep.class.getSimpleName();

    private static final String PROPERTY_KEY_PERFORM_STEP = PROPERTY_KEY_IDENTIFIER + ".performStep";

    private static final String PROPERTY_KEY_GRAPHVIZ = PROPERTY_KEY_IDENTIFIER + ".graphvizDirectoryField";

    private static final String PROPERTY_KEY_PIC2PLOT = PROPERTY_KEY_IDENTIFIER + ".pic2plotDirectoryField";

    private static final String PROPERTY_KEY_OUTPUT_FORMAT = PROPERTY_KEY_IDENTIFIER + ".outputFormatField";

    private static final String GRAPHVIZ_DIR_TEXT_FIELD_TOOLTIP = "The graphviz directory contains the path to the graphviz binary. Required for conversion.";

    private static final String PIC2PLOT_DIR_TEXT_FIELD_TOOLTIP = "The pic2plot directory contains the path to the pic2plot binary. Required for conversion.";

    private static final Logger LOGGER = LoggerFactory.getLogger(ConversionStep.class);

    private final String currentPath = new File(".").getAbsolutePath();

    private final JLabel infoLabel = new JLabel("In this step you manage Graphviz and Pic2Plot in order to convert the results from the trace " + "analysis.

WARNING: If selected, this step will overwrite existing files in your output directory.");

    private final JPanel expandingPanel1 = new JPanel();

    private final JPanel expandingPanel2 = new JPanel();

    private final JCheckBox performStep = new JCheckBox("Perform File Conversion");

    private final JLabel graphvizDirectoryLabel = new JLabel("Graphviz Directory: ");

    private final JLabel pic2plotDirectoryLabel = new JLabel("Pic2Plot Directory: ");

    private final JTextField graphvizDirectoryField = new JTextField(this.currentPath);

    private final JTextField pic2plotDirectoryField = new JTextField(this.currentPath);

    private final JButton graphvizDirectoryChooseButton = new JButton("Choose");

    private final JButton pic2plotDirectoryChooseButton = new JButton("Choose");

    private final JLabel outputFormat = new JLabel("Output Format: ");

    private final JComboBox<String> outputFormatField = new JComboBox<>(new String[] { "PNG", "JPEG", "SVG", "PDF" });

    public ConversionStep() {
        this.addAndLayoutComponents();
        this.addLogicToComponents();
        this.addToolTipsToComponents();
    }

    private void addAndLayoutComponents() {
        this.setLayout(new GridBagLayout());
        final GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        this.add(this.infoLabel, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.insets.set(5, 5, 0, 0);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        this.add(this.performStep, gridBagConstraints);
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.weightx = 0.0;
        this.add(this.graphvizDirectoryLabel, gridBagConstraints);
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        this.add(this.graphvizDirectoryField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.weightx = 0.0;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.graphvizDirectoryChooseButton, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.pic2plotDirectoryLabel, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        this.add(this.pic2plotDirectoryField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        this.add(this.pic2plotDirectoryChooseButton, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        this.add(this.outputFormat, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.RELATIVE;
        gridBagConstraints.anchor = GridBagConstraints.EAST;
        gridBagConstraints.insets.set(5, 5, 5, 5);
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        this.add(this.outputFormatField, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        this.add(this.expandingPanel1, gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        this.add(this.expandingPanel2, gridBagConstraints);
    }

    private void addLogicToComponents() {
        this.graphvizDirectoryChooseButton.addActionListener(new ChooseDirectoryActionListener(this.graphvizDirectoryField, this));
        this.pic2plotDirectoryChooseButton.addActionListener(new ChooseDirectoryActionListener(this.pic2plotDirectoryField, this));
        this.performStep.addActionListener(new ActionListener() {

            @Override
            @SuppressWarnings("synthetic-access")
            public void actionPerformed(final ActionEvent e) {
                ConversionStep.this.graphvizDirectoryField.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.pic2plotDirectoryField.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.graphvizDirectoryChooseButton.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.pic2plotDirectoryChooseButton.setEnabled(ConversionStep.this.performStep.isSelected());
                ConversionStep.this.outputFormatField.setEnabled(ConversionStep.this.performStep.isSelected());
            }
        });
    }

    private void addToolTipsToComponents() {
        this.graphvizDirectoryField.setToolTipText(GRAPHVIZ_DIR_TEXT_FIELD_TOOLTIP);
        this.pic2plotDirectoryField.setToolTipText(PIC2PLOT_DIR_TEXT_FIELD_TOOLTIP);
    }

    @Override
    public void addSelectedTraceAnalysisParameters(final Collection<String> parameters) {
        // Nothing to add here
    }

    public void convert(final String outputDirectory) {
        if (this.performStep.isSelected()) {
            final File outputDir = new File(outputDirectory);
            final File[] dotFiles = outputDir.listFiles(new FileNameExtensionFilter(".dot"));
            if (dotFiles == null) {
                return;
            }
            for (final File dotFile : dotFiles) {
                try {
                    final Process p = Runtime.getRuntime().exec(new String[] { this.graphvizDirectoryField.getText() + "/dot", "-O", "-T" + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH), dotFile.getAbsolutePath() });
                    p.waitFor();
                } catch (final IOException | InterruptedException e) {
                    LOGGER.warn("An exception occurred", e);
                }
            }
            final File[] picFiles = outputDir.listFiles(new FileNameExtensionFilter(".pic"));
            if (picFiles == null) {
                return;
            }
            for (final File picFile : picFiles) {
                OutputStream writer = null;
                try {
                    final Process p = Runtime.getRuntime().exec(new String[] { this.pic2plotDirectoryField.getText() + "/pic2plot", "-T" + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH), picFile.getAbsolutePath() });
                    final InputStream s = p.getInputStream();
                    writer = new FileOutputStream(picFile.getAbsolutePath() + "." + this.outputFormatField.getSelectedItem().toString().toLowerCase(Locale.ENGLISH));
                    int r;
                    final byte[] buffer = new byte[10 * 1024];
                    while ((r = s.read(buffer)) != -1) {
                        // NOPMD
                        writer.write(buffer, 0, r);
                    }
                    writer.close();
                    s.close();
                    p.waitFor();
                } catch (final IOException | InterruptedException e) {
                    LOGGER.warn("An exception occurred", e);
                } finally {
                    if (null != writer) {
                        try {
                            writer.close();
                        } catch (final IOException e) {
                            LOGGER.warn("An exception occurred", e);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void loadDefaultConfiguration() {
        this.graphvizDirectoryField.setText(this.currentPath);
        this.pic2plotDirectoryField.setText(this.currentPath);
        this.outputFormatField.setSelectedIndex(0);
        this.graphvizDirectoryField.setEnabled(false);
        this.pic2plotDirectoryField.setEnabled(false);
        this.graphvizDirectoryChooseButton.setEnabled(false);
        this.pic2plotDirectoryChooseButton.setEnabled(false);
        this.outputFormatField.setEnabled(false);
    }

    @Override
    public void saveCurrentConfiguration(final Properties properties) {
        properties.setProperty(PROPERTY_KEY_PERFORM_STEP, Boolean.toString(this.performStep.isSelected()));
        properties.setProperty(PROPERTY_KEY_GRAPHVIZ, this.graphvizDirectoryField.getText());
        properties.setProperty(PROPERTY_KEY_PIC2PLOT, this.pic2plotDirectoryField.getText());
        properties.setProperty(PROPERTY_KEY_OUTPUT_FORMAT, Integer.toString(this.outputFormatField.getSelectedIndex()));
    }

    @Override
    public void loadCurrentConfiguration(final Properties properties) {
        this.performStep.setSelected(Boolean.parseBoolean(properties.getProperty(PROPERTY_KEY_PERFORM_STEP)));
        this.graphvizDirectoryField.setText(properties.getProperty(PROPERTY_KEY_GRAPHVIZ));
        this.pic2plotDirectoryField.setText(properties.getProperty(PROPERTY_KEY_PIC2PLOT));
        this.outputFormatField.setSelectedIndex(Integer.parseInt(properties.getProperty(PROPERTY_KEY_OUTPUT_FORMAT)));
        this.graphvizDirectoryField.setEnabled(this.performStep.isSelected());
        this.pic2plotDirectoryField.setEnabled(this.performStep.isSelected());
        this.graphvizDirectoryChooseButton.setEnabled(this.performStep.isSelected());
        this.pic2plotDirectoryChooseButton.setEnabled(this.performStep.isSelected());
        this.outputFormatField.setEnabled(this.performStep.isSelected());
    }

    @Override
    public boolean isNextStepAllowed() {
        final boolean performThisStep = this.performStep.isSelected();
        if (performThisStep) {
            final boolean graphvizAvailable = this.checkGraphvizExecutable();
            if (!graphvizAvailable) {
                final int result = JOptionPane.showConfirmDialog(this, "The Graphviz executable could not be found. Continue?", "Graphviz Executable", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (JOptionPane.NO_OPTION == result) {
                    return false;
                }
            }
            final boolean pic2PlotAvailable = this.checkPic2PlotExecutable();
            if (!pic2PlotAvailable) {
                final int result = JOptionPane.showConfirmDialog(this, "The Pic2Plot executable could not be found. Continue?", "Pic2Plot Executable", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                return (JOptionPane.YES_OPTION == result);
            }
        }
        return true;
    }

    private boolean checkPic2PlotExecutable() {
        return this.checkExecutable(this.pic2plotDirectoryField.getText() + "/pic2plot", "--v");
    }

    private boolean checkGraphvizExecutable() {
        return this.checkExecutable(this.graphvizDirectoryField.getText() + "/dot", "-V");
    }

    private boolean checkExecutable(final String command, final String parameter) {
        final Process p;

    }

    /**
     * @author Nils Christian Ehmke
     *
     * @since 1.10
     */
    private static class ChooseDirectoryActionListener implements ActionListener {

        private final JTextField textField;

        private final Component parent;

        public ChooseDirectoryActionListener(final JTextField textField, final Component parent) {
            this.textField = textField;
            this.parent = parent;
        }

        @Override
        public void actionPerformed(final ActionEvent event) {
            final JFileChooser fileChooser = new JFileChooser(this.textField.getText());
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.showOpenDialog(this.parent) == JFileChooser.APPROVE_OPTION) {
                this.textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
            }
        }
    }

    /**
     * @author Nils Christian Ehmke
     *
     * @since 1.10
     */
    private static class FileNameExtensionFilter implements FilenameFilter {

        private final String extension;

        public FileNameExtensionFilter(final String extension) {
            this.extension = extension;
        }

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith(this.extension);
        }
    }
}


for (index = 0; index < event.getPointerCount(); index++) {
                    pointerId = event.getPointerId(index);
                    if (pointerId < FINGERS) {
                        float x = event.getX(index);
                        float y = event.getY(index);
                        float pressure = event.getPressure(index);
                        redraw |= onTouchMove(pointerId, x, y, pressure);
                    }
                }

package com.levien.synthesizer.android.widgets.keyboard;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.levien.synthesizer.core.midi.MidiListener;

public class KeyboardView extends View {

    public KeyboardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        nKeys_ = 96;
        firstKey_ = 12;
        noteStatus_ = new byte[128];
        noteForFinger_ = new int[FINGERS];
        for (int i = 0; i < FINGERS; i++) {
            noteForFinger_[i] = -1;
        }
        drawingRect_ = new Rect();
        paint_ = new Paint();
        paint_.setAntiAlias(true);
        float density = getResources().getDisplayMetrics().density;
        textSize_ = 32.0f * density;
        paint_.setTextSize(textSize_);
        paint_.setTextAlign(Paint.Align.CENTER);
        strokeWidth_ = 1.0f * density;
        paint_.setStrokeWidth(strokeWidth_);
        offset_ = 0.0f;
        zoom_ = 1.0f;
        setKeyboardSpec(KeyboardSpec.make2Row());
        velSens_ = 0.5f;
        velAvg_ = 64;
    }

    public void setKeyboardSpec(KeyboardSpec keyboardSpec) {
        keyboardSpec_ = keyboardSpec;
        keyboardScale_ = zoom_ / keyboardSpec_.repeatWidth * keyboardSpec_.keys.length / nKeys_;
        invalidate();
    }

    public void setMidiListener(MidiListener listener) {
        midiListener_ = listener;
    }

    public void onNote(int note, int velocity) {
        if (note >= 0 && note < 128) {
            noteStatus_[note] = (byte) velocity;
            // could do smarter invalidation, whatev
            invalidate();
        }
    }

    public void setVelocitySensitivity(float velSens, float velAvg) {
        velSens_ = velSens;
        velAvg_ = velAvg;
    }

    public void setScrollZoom(float offset, float zoom) {
        offset_ = offset;
        zoom_ = zoom;
        keyboardScale_ = zoom_ / keyboardSpec_.repeatWidth * keyboardSpec_.keys.length / nKeys_;
        invalidate();
    }

    public float getMaxScroll() {
        float width = drawingRect_.width();
        return (zoom_ - 1) * width;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        getDrawingRect(drawingRect_);
        float xscale = (drawingRect_.width() - strokeWidth_) * keyboardScale_;
        float yscale = (drawingRect_.height() - strokeWidth_) / keyboardSpec_.height;
        float x0 = drawingRect_.left + strokeWidth_ * 0.5f + offset_;
        float y0 = drawingRect_.top + strokeWidth_ * 0.5f;
        for (int i = 0; i < nKeys_; i++) {
            KeySpec ks = keyboardSpec_.keys[i % keyboardSpec_.keys.length];
            float x = x0 + ((i / keyboardSpec_.keys.length) * keyboardSpec_.repeatWidth + ks.rect.left) * xscale;
            float y = y0 + ks.rect.top * yscale;
            float width = ks.rect.width() * xscale;
            float height = ks.rect.height() * yscale;
            int note = i + firstKey_;
            int vel = noteStatus_[note];
            if (vel == 0) {
                paint_.setColor(ks.color);
            } else {
                // green->yellow->red gradient, dependent on velocity
                int color;
                if (vel < 64) {
                    color = 0xff00ff00 + (vel << 18);
                } else {
                    color = 0xffffff00 - ((vel - 64) << 10);
                }
                paint_.setColor(color);
            }
            paint_.setStyle(Style.FILL);
            canvas.drawRect(x, y, x + width, y + height, paint_);
            if (ks.color != Color.BLACK) {
                paint_.setColor(Color.BLACK);
                paint_.setStyle(Style.STROKE);
                canvas.drawRect(x, y, x + width, y + height, paint_);
            } else {
                paint_.setColor(Color.WHITE);
            }
            // Draw note label
            if (note % 12 == 0) {
                float xs = x + width / 2;
                float ys = y + 0.5f * height + 0.35f * textSize_;
                paint_.setStyle(Style.FILL);
                if (note % 12 == 0) {
                    paint_.setTypeface(Typeface.DEFAULT_BOLD);
                } else {
                    paint_.setTypeface(Typeface.DEFAULT);
                }
                canvas.drawText(noteString(note), xs, ys, paint_);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int actionCode = event.getActionMasked();
        boolean redraw = false;
        switch(actionCode) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                int index = actionCode == MotionEvent.ACTION_POINTER_DOWN ? event.getActionIndex() : 0;
                int pointerId = event.getPointerId(index);
                if (pointerId < FINGERS && pointerId >= 0) {
                    float x = event.getX(index);
                    float y = event.getY(index);
                    float pressure = event.getPressure(index);
                    redraw |= onTouchDown(pointerId, x, y, pressure);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                index = actionCode == MotionEvent.ACTION_POINTER_UP ? event.getActionIndex() : 0;
                pointerId = event.getPointerId(index);
                if (pointerId < FINGERS && pointerId >= 0) {
                    float x = event.getX(index);
                    float y = event.getY(index);
                    float pressure = event.getPressure(index);
                    redraw |= onTouchUp(pointerId, x, y, pressure);
                }
                break;
            case MotionEvent.ACTION_MOVE:

                break;
        }
        if (redraw) {
            invalidate();
        }
        return true;
    }

    private int hitTest(float x, float y) {
        /* convert x and y to KeyboardSpec space */
        float xscale = (drawingRect_.width() - strokeWidth_) * keyboardScale_;
        float yscale = (drawingRect_.height() - strokeWidth_) / keyboardSpec_.height;
        float xk = (x - 0.5f * strokeWidth_ - offset_) / xscale;
        float yk = (y - 0.5f * strokeWidth_) / yscale;
        for (int i = 0; i < nKeys_; i++) {
            KeySpec ks = keyboardSpec_.keys[i % keyboardSpec_.keys.length];
            float kx0 = ks.rect.left + (i / keyboardSpec_.keys.length) * keyboardSpec_.repeatWidth;
            if (xk >= kx0 && xk < kx0 + ks.rect.width() && yk >= ks.rect.top && yk < ks.rect.bottom) {
                return i + firstKey_;
            }
        }
        return -1;
    }

    private int computeVelocity(float pressure) {
        int velocity = (int) (velSens_ * (pressure - 0.5f) * 127.0f + velAvg_ + 0.5f);
        if (velocity < 1) {
            velocity = 1;
        } else if (velocity > 127) {
            velocity = 127;
        }
        return velocity;
    }

    private boolean onTouchDown(int id, float x, float y, float pressure) {
        int note = hitTest(x, y);
        if (note >= 0 && noteStatus_[note] == 0) {
            int velocity = computeVelocity(pressure);
            noteForFinger_[id] = note;
            noteStatus_[note] = (byte) velocity;
            if (midiListener_ != null) {
                midiListener_.onNoteOn(0, note, velocity);
            }
            return true;
        }
        return false;
    }

    private boolean onTouchUp(int id, float x, float y, float pressure) {
        int note = noteForFinger_[id];
        if (note >= 0) {
            int velocity = noteStatus_[note];
            if (midiListener_ != null) {
                midiListener_.onNoteOff(0, note, velocity);
            }
            noteForFinger_[id] = -1;
            noteStatus_[note] = 0;
            return true;
        }
        return false;
    }

    private boolean onTouchMove(int id, float x, float y, float pressure) {
        int oldNote = noteForFinger_[id];
        int newNote = hitTest(x, y);
        if (newNote != -1 && newNote != oldNote && noteStatus_[newNote] == 0) {
            // keep consistent velocity; new is likely to be too high
            if (oldNote >= 0) {
                int velocity = noteStatus_[oldNote];
                if (midiListener_ != null) {
                    midiListener_.onNoteOff(0, oldNote, velocity);
                    midiListener_.onNoteOn(0, newNote, velocity);
                }
                noteForFinger_[id] = newNote;
                noteStatus_[oldNote] = 0;
                noteStatus_[newNote] = (byte) velocity;
            } else {
                // moving onto active note from dead zone
                int velocity = 64;
                if (midiListener_ != null) {
                    midiListener_.onNoteOn(0, newNote, velocity);
                }
                noteForFinger_[id] = newNote;
                noteStatus_[newNote] = (byte) velocity;
            }
            return true;
        }
        return false;
    }

    private static String noteString(int note) {
        int octave = note / 12 - 1;
        return NOTE_NAMES[note % 12] + Integer.toString(octave);
    }

    private float velSens_;

    private float velAvg_;

    private MidiListener midiListener_;

    private Rect drawingRect_;

    private Paint paint_;

    private float strokeWidth_;

    private float textSize_;

    private float keyboardScale_;

    private float offset_;

    private float zoom_;

    private KeyboardSpec keyboardSpec_;

    private int nKeys_;

    private int firstKey_;

    private byte[] noteStatus_;

    private static final int FINGERS = 10;

    private int[] noteForFinger_;

    static final String[] NOTE_NAMES = new String[] { "C", "C\u266f", "D", "D\u266f", "E", "F", "F\u266f", "G", "G\u266f", "A", "A\u266f", "B" };
}


protected void setLatLngVisible(boolean visible) {
        Style styleLat = m_latitudeLabel.getElement().getParentElement().getStyle();
        Style styleLng = m_longitudeLabel.getElement().getParentElement().getStyle();
        if (visible) {
            styleLat.clearDisplay();
            styleLng.clearDisplay();
        } else {
            styleLat.setDisplay(Display.NONE);
            styleLng.setDisplay(Display.NONE);
        }
    }

/*
 * This library is part of OpenCms -
 * the Open Source Content Management System
 *
 *
 */
package org.opencms.gwt.client.ui.input.location;

import org.opencms.gwt.client.Messages;
import org.opencms.gwt.client.ui.CmsPushButton;
import org.opencms.gwt.client.ui.I_CmsButton.ButtonColor;
import org.opencms.gwt.client.ui.I_CmsButton.ButtonStyle;
import org.opencms.gwt.client.ui.input.CmsSelectBox;
import org.opencms.gwt.client.ui.input.CmsSuggestBox;
import org.opencms.gwt.client.ui.input.CmsTextBox;
import java.util.Map;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SuggestOracle;

/**
 * The location picker map view.

 */
public class CmsLocationPopupContent extends Composite {

    /**
     * @see com.google.gwt.uibinder.client.UiBinder
     */
    protected interface I_CmsLocationPopupContentUiBinder extends UiBinder<HTMLPanel, CmsLocationPopupContent> {
        // GWT interface, nothing to do here
    }

    private static I_CmsLocationPopupContentUiBinder uiBinder = GWT.create(I_CmsLocationPopupContentUiBinder.class);

    /**
     * The address suggest box.
     */
    @UiField(provided = true)
    CmsSuggestBox m_addressField;

    /**
     * The address label.
     */
    @UiField
    Label m_addressLabel;

    /**
     * The cancel button.
     */
    @UiField
    CmsPushButton m_cancelButton;

    /**
     * The height field.
     */
    @UiField
    CmsTextBox m_heightField;

    /**
     * The label field.
     */
    @UiField
    CmsTextBox m_latitudeField;

    /**
     * The label label.
     */
    @UiField
    Label m_latitudeLabel;

    /**
     * The longitude field.
     */
    @UiField
    CmsTextBox m_longitudeField;

    /**
     * The longitude label.
     */
    @UiField
    Label m_longitudeLabel;

    /**
     * The map canvas element.
     */
    @UiField
    Element m_mapCanvas;

    /**
     * The mode field.
     */
    @UiField(provided = true)
    CmsSelectBox m_modeField;

    /**
     * The mode label.
     */
    @UiField
    Label m_modeLabel;

    /**
     * The OK button.
     */
    @UiField
    CmsPushButton m_okButton;

    /**
     * The map size label.
     */
    @UiField
    Label m_sizeLabel;

    /**
     * The map type field.
     */
    @UiField(provided = true)
    CmsSelectBox m_typeField;

    /**
     * The map type label.
     */
    @UiField
    Label m_typeLabel;

    /**
     * The width field.
     */
    @UiField
    CmsTextBox m_widthField;

    /**
     * The zoom field.
     */
    @UiField(provided = true)
    CmsSelectBox m_zoomField;

    /**
     * The zoom label.
     */
    @UiField
    Label m_zoomLabel;

    /**
     * The location picker.
     */
    private CmsLocationController m_controller;

    /**
     * Constructor.

     *
     * @param controller the location controller
     * @param addressOracle the address suggest oracle to use for the address suggest box
     * @param modeItems the available map modes
     * @param typeItems the available map types
     * @param zoomItems the available zoom levels
     */
    public CmsLocationPopupContent(CmsLocationController controller, SuggestOracle addressOracle, Map<String, String> modeItems, Map<String, String> typeItems, Map<String, String> zoomItems) {
        // create fields annotated as provided before running the ui-binder
        m_addressField = new CmsSuggestBox(addressOracle);
        m_modeField = new CmsSelectBox(modeItems);
        m_typeField = new CmsSelectBox(typeItems);
        m_zoomField = new CmsSelectBox(zoomItems);
        initWidget(uiBinder.createAndBindUi(this));
        m_controller = controller;
        m_mapCanvas.setId(HTMLPanel.createUniqueId());
        initLabels();
        initFields();
    }

    /**
     * Displays the location value fields.

     *
     * @param value the location value
     */
    protected void displayValues(CmsLocationValue value) {
        m_addressField.setTextValue(value.getAddress());
        m_latitudeField.setFormValueAsString(value.getLatitudeString());
        m_longitudeField.setFormValueAsString(value.getLongitudeString());
        m_heightField.setFormValueAsString("" + value.getHeight());
        m_widthField.setFormValueAsString("" + value.getWidth());
        m_zoomField.setFormValueAsString("" + value.getZoom());
        m_modeField.setFormValueAsString(value.getMode());
        m_typeField.setFormValueAsString(value.getType());
    }

    /**
     * Returns the map canvas element.

     *
     * @return the map canvas element
     */
    protected Element getMapCanvas() {
        return m_mapCanvas;
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setAddressVisible(boolean visible) {
        Style style = m_addressLabel.getElement().getParentElement().getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */

/**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setMapVisible(boolean visible) {
        Style style = m_mapCanvas.getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setModeVisible(boolean visible) {
        Style style = m_modeLabel.getElement().getParentElement().getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setSizeVisible(boolean visible) {
        Style style = m_sizeLabel.getElement().getParentElement().getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setTypeVisible(boolean visible) {
        Style style = m_typeLabel.getElement().getParentElement().getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * Sets the field visibility.

     *
     * @param visible true to show the field
     */
    protected void setZoomVisible(boolean visible) {
        Style style = m_zoomLabel.getElement().getParentElement().getStyle();
        if (visible) {
            style.clearDisplay();
        } else {
            style.setDisplay(Display.NONE);
        }
    }

    /**
     * On address field value change.

     *
     * @param event the change event
     */
    @UiHandler("m_addressField")
    void onAddressChange(ValueChangeEvent<String> event) {
        m_controller.onAddressChange(event.getValue());
    }

    /**
     * On address suggest selection.

     *
     * @param event the selection event
     */
    @UiHandler("m_addressField")
    void onAddressSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
        m_controller.onAddressChange(event.getSelectedItem());
    }

    /**
     * Handles the cancel click.

     *
     * @param event the mouse event
     */
    @UiHandler("m_cancelButton")
    void onCancel(ClickEvent event) {
        m_controller.onCancel();
    }

    /**
     * On height value change.

     *
     * @param event the change event
     */
    @UiHandler("m_heightField")
    void onHeightChange(ValueChangeEvent<String> event) {
        m_controller.onHeightChange(event.getValue());
    }

    /**
     * On latitude value change.

     *
     * @param event the change event
     */
    @UiHandler("m_latitudeField")
    void onLatitudeChange(ValueChangeEvent<String> event) {
        m_controller.onLatitudeChange(event.getValue());
    }

    /**
     * On longitude value change.

     *
     * @param event the change event
     */
    @UiHandler("m_longitudeField")
    void onLongitudeChange(ValueChangeEvent<String> event) {
        m_controller.onLongitudeChange(event.getValue());
    }

    /**
     * On mode value change.

     *
     * @param event the change event
     */
    @UiHandler("m_modeField")
    void onModeChange(ValueChangeEvent<String> event) {
        m_controller.onModeChange(event.getValue());
    }

    /**
     * Handles the OK click.

     *
     * @param event the mouse event
     */
    @UiHandler("m_okButton")
    void onOk(ClickEvent event) {
        m_controller.onOk();
    }

    /**
     * On type value change.

     *
     * @param event the change event
     */
    @UiHandler("m_typeField")
    void onTypeChange(ValueChangeEvent<String> event) {
        m_controller.onTypeChange(event.getValue());
    }

    /**
     * On width value change.

     *
     * @param event the change event
     */
    @UiHandler("m_widthField")
    void onWidthChange(ValueChangeEvent<String> event) {
        m_controller.onWidthChange(event.getValue());
    }

    /**
     * On zoom value change.

     *
     * @param event the change event
     */
    @UiHandler("m_zoomField")
    void onZoomChange(ValueChangeEvent<String> event) {
        m_controller.onZoomChange(event.getValue());
    }

    private void initFields() {
        m_latitudeField.setTriggerChangeOnKeyPress(true);
        m_longitudeField.setTriggerChangeOnKeyPress(true);
        m_heightField.setTriggerChangeOnKeyPress(true);
        m_widthField.setTriggerChangeOnKeyPress(true);
    }

    private void initLabels() {
        m_addressLabel.setText(Messages.get().key(Messages.GUI_LOCATION_ADDRESS_0));
        m_longitudeLabel.setText(Messages.get().key(Messages.GUI_LOCATION_LONGITUDE_0));
        m_latitudeLabel.setText(Messages.get().key(Messages.GUI_LOCATION_LATITUDE_0));
        m_sizeLabel.setText(Messages.get().key(Messages.GUI_LOCATION_SIZE_0));
        m_zoomLabel.setText(Messages.get().key(Messages.GUI_LOCATION_ZOOM_0));
        m_typeLabel.setText(Messages.get().key(Messages.GUI_LOCATION_TYPE_0));
        m_modeLabel.setText(Messages.get().key(Messages.GUI_LOCATION_MODE_0));
        m_okButton.setText(Messages.get().key(Messages.GUI_OK_0));
        m_okButton.setUseMinWidth(true);
        m_okButton.setButtonStyle(ButtonStyle.TEXT, ButtonColor.BLUE);
        m_cancelButton.setText(Messages.get().key(Messages.GUI_CANCEL_0));
        m_cancelButton.setUseMinWidth(true);
        m_cancelButton.setButtonStyle(ButtonStyle.TEXT, ButtonColor.BLUE);
    }
}


public String getStringValue() {
        if (this.value != null) {
            return value.toString();
        }
        return "";
    }

package com.dexcoder.commons.office;

/**
 * row中的一列数据
 *
 * Created by liyd on 7/28/14.
 */
public class ExcelCell {

    /**
     * 列值
     */
    private Object value;

    public ExcelCell() {
    }

    public ExcelCell(Object value) {
        this.value = value;
    }

    /**
     * 获取value值的字符串形式
     *
     * @return
     */

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        if (this.value != null) {
            return value.toString();
        }
        return "null";
    }
}