try {
            writerWaitStats.accumulate(System.nanoTime() - waitStart);
            return doInTransaction(work);
        } finally {
            writeLock.unlock();
        }

package org.apache.aurora.scheduler.storage.durability;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import javax.inject.Inject;
import org.apache.aurora.common.inject.TimedInterceptor.Timed;
import org.apache.aurora.common.stats.SlidingStats;
import org.apache.aurora.gen.storage.Op;
import org.apache.aurora.scheduler.base.SchedulerException;
import org.apache.aurora.scheduler.events.EventSink;
import org.apache.aurora.scheduler.storage.AttributeStore;
import org.apache.aurora.scheduler.storage.CronJobStore;
import org.apache.aurora.scheduler.storage.HostMaintenanceStore;
import org.apache.aurora.scheduler.storage.JobUpdateStore;
import org.apache.aurora.scheduler.storage.QuotaStore;
import org.apache.aurora.scheduler.storage.SchedulerStore;
import org.apache.aurora.scheduler.storage.Storage;
import org.apache.aurora.scheduler.storage.Storage.MutateWork.NoResult;
import org.apache.aurora.scheduler.storage.Storage.NonVolatileStorage;
import org.apache.aurora.scheduler.storage.TaskStore;
import org.apache.aurora.scheduler.storage.durability.Persistence.PersistenceException;
import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;

/**
 * A storage implementation that ensures storage mutations are written to a persistence layer.
 *
 *
In the classic write-ahead log usage we'd perform mutations as follows:
 *

 *
record op

 *
perform op locally

 *
persist ops

 *

 *
 *
Writing the operation to persistences ensures we have a record of our mutation in case we
 * should need to recover state later after a crash or on a new host (assuming the scheduler is
 * distributed).  We then apply the mutation to a local (in-memory) data structure for serving fast
 * read requests.
 *
 *
This implementation leverages a local transaction to handle this:
 *

 *
start local transaction

 *
perform op locally (uncommitted!)

 *
write op to persistence

 *

 *
 *
If the op fails to apply to local storage we will never persist the op, and if the op
 * fails to persist, it'll throw and abort the local storage operation as well.
 */
public class DurableStorage implements NonVolatileStorage {

    /**
     * A maintainer for context about open transactions. Assumes that an external entity is
     * responsible for opening and closing transactions.
     */
    interface TransactionManager {

        /**
         * Checks whether there is an open transaction.
         *
         * @return {@code true} if there is an open transaction, {@code false} otherwise.
         */
        boolean hasActiveTransaction();

        /**
         * Adds an operation to the existing transaction.
         *
         * @param op Operation to include in the existing transaction.
         */
        void log(Op op);
    }

    private final Persistence persistence;

    private final Storage writeBehindStorage;

    private final ReentrantLock writeLock;

    private final ThriftBackfill thriftBackfill;

    private final WriteRecorder writeRecorder;

    private TransactionRecorder transaction = null;

    private final SlidingStats writerWaitStats = new SlidingStats("storage_write_lock_wait", "ns");

    @Inject
    DurableStorage(Persistence persistence, @Volatile Storage delegateStorage, @Volatile SchedulerStore.Mutable schedulerStore, @Volatile CronJobStore.Mutable jobStore, @Volatile TaskStore.Mutable taskStore, @Volatile QuotaStore.Mutable quotaStore, @Volatile AttributeStore.Mutable attributeStore, @Volatile JobUpdateStore.Mutable jobUpdateStore, @Volatile HostMaintenanceStore.Mutable hostMaintenanceStore, EventSink eventSink, ReentrantLock writeLock, ThriftBackfill thriftBackfill) {
        this.persistence = requireNonNull(persistence);
        // DurableStorage has two distinct operating modes: pre- and post-recovery.  When recovering,
        // we write directly to the writeBehind stores since we are replaying what's already persisted.
        // After that, all writes must succeed in Persistence before they may be considered successful.
        this.writeBehindStorage = requireNonNull(delegateStorage);
        this.writeLock = requireNonNull(writeLock);
        this.thriftBackfill = requireNonNull(thriftBackfill);
        TransactionManager transactionManager = new TransactionManager() {

            @Override
            public boolean hasActiveTransaction() {
                return transaction != null;
            }

            @Override
            public void log(Op op) {
                transaction.add(op);
            }
        };
        this.writeRecorder = new WriteRecorder(transactionManager, schedulerStore, jobStore, taskStore, quotaStore, attributeStore, jobUpdateStore, hostMaintenanceStore, LoggerFactory.getLogger(WriteRecorder.class), eventSink);
    }

    @Override
    @Timed("scheduler_storage_prepare")
    public synchronized void prepare() {
        writeBehindStorage.prepare();
        persistence.prepare();
    }

    @Override
    @Timed("scheduler_storage_start")
    public void start(final MutateWork.NoResult.Quiet initializationLogic) {
        writeLock.lock();
        try {
            // We recover directly into the forwarded system to avoid persisting replayed operations.
            writeBehindStorage.write((NoResult.Quiet) this::recover);
            // Now that we're recovered we should persist any mutations done in initializationLogic, so
            // run it in one of our transactions.
            write(initializationLogic);
        } finally {
            writeLock.unlock();
        }
    }

    @Override
    public void stop() {
    }

    @Timed("scheduler_storage_recover")
    void recover(MutableStoreProvider stores) throws RecoveryFailedException {
        try {
            Loader.load(stores, thriftBackfill, persistence.recover());
        } catch (PersistenceException e) {
            throw new RecoveryFailedException(e);
        }
    }

    private static final class RecoveryFailedException extends SchedulerException {

        RecoveryFailedException(Throwable cause) {
            super(cause);
        }
    }

    private <T, E extends Exception> T doInTransaction(final MutateWork<T, E> work) throws StorageException, E {
        // The transaction has already been set up so we just need to delegate with our store provider
        // so any mutations may be persisted.
        if (transaction != null) {
            return work.apply(writeRecorder);
        }
        transaction = new TransactionRecorder();
        try {
            return writeBehindStorage.write(unused -> {
                T result = work.apply(writeRecorder);
                List<Op> ops = transaction.getOps();
                if (!ops.isEmpty()) {
                    try {
                        persistence.persist(ops.stream());
                    } catch (PersistenceException e) {
                        throw new StorageException("Failed to persist storage changes", e);
                    }
                }
                return result;
            });
        } finally {
            transaction = null;
        }
    }

    @Override
    public <T, E extends Exception> T write(final MutateWork<T, E> work) throws StorageException, E {
        long waitStart = System.nanoTime();
        writeLock.lock();

    }

    @Override
    public <T, E extends Exception> T read(Work<T, E> work) throws StorageException, E {
        return writeBehindStorage.read(work);
    }
}


@Override
    public void collect() {
    }

package jrds.probe;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.rrd4j.core.jrrd.RRDatabase;
import org.slf4j.event.Level;
import jrds.GraphDesc;
import jrds.GraphNode;
import jrds.Probe;
import jrds.factories.ProbeBean;
import jrds.graphe.RRDToolGraphNode;
import jrds.store.RRDToolStoreFactory;
import jrds.store.StoreFactory;

/**
 * A class wrapper to use rrdtool's files
 *
 * @author Fabrice Bacchella
 */
@ProbeBean({ "rrdfile" })
public class RRDToolProbe extends Probe<String, Double> {

    private File rrdpath;

    public Boolean configure(File rrdpath) {
        this.rrdpath = rrdpath;
        try {
            log(Level.TRACE, "rrd is %s", rrdpath.getCanonicalPath());
        } catch (IOException e) {
        }
        Map<String, String> args = new HashMap<String, String>(1);
        try {
            args.put("rrdfile", rrdpath.getCanonicalPath());
            setMainStore(new RRDToolStoreFactory(), args);
            return rrdpath.canRead();
        } catch (IOException e) {
            log(Level.ERROR, e, "rrdtool file %s unreadable", rrdpath);
            return false;
        } catch (InvocationTargetException e) {
            log(Level.ERROR, e, "store configuration failed");
            return false;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#setMainStore(jrds.store.StoreFactory, java.util.Map)
     */
    @Override
    public void setMainStore(StoreFactory factory, Map<String, String> args) throws InvocationTargetException {
        if (factory.getClass() == RRDToolStoreFactory.class)
            super.setMainStore(factory, args);
    }

    public void setRrdfile(File rrdpath) {
        this.rrdpath = rrdpath;
    }

    public File getRrdfile() {
        return rrdpath;
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#addGraph(jrds.GraphNode)
     */
    @Override
    public void addGraph(GraphNode node) {
        super.addGraph(new RRDToolGraphNode(this, node.getGraphDesc(), rrdpath));
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#addGraph(jrds.GraphDesc)
     */
    @Override
    public void addGraph(GraphDesc gd) {
        super.addGraph(new RRDToolGraphNode(this, gd, rrdpath));
    }

    @Override
    public Map<String, Double> getNewSampleValues() {
        return Collections.emptyMap();
    }

    @Override
    public String getSourceType() {
        return "RRDToolFile";
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#collect()
     */

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#getLastUpdate()
     */
    @Override
    public Date getLastUpdate() {
        try (RRDatabase db = new RRDatabase(rrdpath)) {
            return db.getLastUpdate();
        } catch (IOException e) {
            log(Level.ERROR, "probe %s, read failed: %s", e);
        }
        return new Date(0);
    }
}


try {
            log(Level.TRACE, "rrd is %s", rrdpath.getCanonicalPath());
        } catch (IOException e) {
        }

package jrds.probe;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.rrd4j.core.jrrd.RRDatabase;
import org.slf4j.event.Level;
import jrds.GraphDesc;
import jrds.GraphNode;
import jrds.Probe;
import jrds.factories.ProbeBean;
import jrds.graphe.RRDToolGraphNode;
import jrds.store.RRDToolStoreFactory;
import jrds.store.StoreFactory;

/**
 * A class wrapper to use rrdtool's files
 *
 * @author Fabrice Bacchella
 */
@ProbeBean({ "rrdfile" })
public class RRDToolProbe extends Probe<String, Double> {

    private File rrdpath;

    public Boolean configure(File rrdpath) {
        this.rrdpath = rrdpath;

        Map<String, String> args = new HashMap<String, String>(1);
        try {
            args.put("rrdfile", rrdpath.getCanonicalPath());
            setMainStore(new RRDToolStoreFactory(), args);
            return rrdpath.canRead();
        } catch (IOException e) {
            log(Level.ERROR, e, "rrdtool file %s unreadable", rrdpath);
            return false;
        } catch (InvocationTargetException e) {
            log(Level.ERROR, e, "store configuration failed");
            return false;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#setMainStore(jrds.store.StoreFactory, java.util.Map)
     */
    @Override
    public void setMainStore(StoreFactory factory, Map<String, String> args) throws InvocationTargetException {
        if (factory.getClass() == RRDToolStoreFactory.class)
            super.setMainStore(factory, args);
    }

    public void setRrdfile(File rrdpath) {
        this.rrdpath = rrdpath;
    }

    public File getRrdfile() {
        return rrdpath;
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#addGraph(jrds.GraphNode)
     */
    @Override
    public void addGraph(GraphNode node) {
        super.addGraph(new RRDToolGraphNode(this, node.getGraphDesc(), rrdpath));
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#addGraph(jrds.GraphDesc)
     */
    @Override
    public void addGraph(GraphDesc gd) {
        super.addGraph(new RRDToolGraphNode(this, gd, rrdpath));
    }

    @Override
    public Map<String, Double> getNewSampleValues() {
        return Collections.emptyMap();
    }

    @Override
    public String getSourceType() {
        return "RRDToolFile";
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#collect()
     */
    @Override
    public void collect() {
    }

    /*
     * (non-Javadoc)
     *
     * @see jrds.Probe#getLastUpdate()
     */
    @Override
    public Date getLastUpdate() {
        try (RRDatabase db = new RRDatabase(rrdpath)) {
            return db.getLastUpdate();
        } catch (IOException e) {
            log(Level.ERROR, "probe %s, read failed: %s", e);
        }
        return new Date(0);
    }
}


public static ICategoryProviderFactory getInstance() {
        return instance;
    }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *   Actuate Corporation  - initial API and implementation
 * *****************************************************************************
 */
package org.eclipse.birt.report.designer.ui.cubebuilder.attributes;

import org.eclipse.birt.report.designer.ui.cubebuilder.attributes.page.CubePage;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.views.attributes.AttributesUtil;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.CategoryProviderFactory;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ICategoryProvider;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ICategoryProviderFactory;

public class CubeCategoryProviderFactory extends CategoryProviderFactory {

    private static ICategoryProviderFactory instance = new CubeCategoryProviderFactory();

    protected CubeCategoryProviderFactory() {
    }

    /**
     * @return The unique CategoryProviderFactory instance
     */

    public ICategoryProvider getCategoryProvider(Object input) {
        return AttributesUtil.createCategoryProvider(new String[] { null, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_ADVANCEPROPERTY }, new String[] { CATEGORY_KEY_GENERAL }, new String[] { Messages.getString("CubePageGenerator.List.General") }, new Class[] { CubePage.class });
    }
}


public void changeWasMade(final String sha, final int newDeclarationLine, final boolean wasRenamed) {
        final ChangeEvent ce = new ChangeEvent(sha, wasRenamed, newDeclarationLine);
        changeEvents.add(ce);
        if (wasRenamed) {
            changeEvents = ImmutableList.copyOf(changeEvents);
        }
    }

package renaming.history;

import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

/**
 * A single identifier name through the history of the repository. When a
 * renaming happens, this object is "locked".
 *
 * @author Miltos Allamanis <example@nnthink.com>
 */
public class NameThroughHistory {

    public static final class ChangeEvent {

        final boolean wasRenamed;

        final String changeSha;

        final int declarationLine;

        public ChangeEvent(final String changeSha, final boolean wasRenamed, final int declarationLine) {
            this.changeSha = changeSha;
            this.wasRenamed = wasRenamed;
            this.declarationLine = declarationLine;
        }
    }

    public final String name;

    private List<ChangeEvent> changeEvents = Lists.newArrayList();

    public NameThroughHistory(final String name, final String appearedSha, final int initialDeclarationLine) {
        this.name = name;
        final ChangeEvent ce = new ChangeEvent(appearedSha, false, initialDeclarationLine);
        changeEvents.add(ce);
    }

    /**
     * Add a line to the history of this name.
     *
     * @param sha
     * @param newDeclarationLine
     * @param wasRenamed
     */

    public List<ChangeEvent> getChangeEvents() {
        return changeEvents;
    }
}


public static List<LemonFieldError> getErrors(Set<ConstraintViolation<?>> constraintViolations) {
        return constraintViolations.stream().map(LemonFieldError::of).collect(Collectors.toList());
    }

package com.naturalprogrammer.spring.lemon.exceptions;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.support.WebExchangeBindException;
import javax.validation.ConstraintViolation;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Holds a field or form error
 */
@Getter
@AllArgsConstructor
@ToString
public class LemonFieldError implements Serializable {

    // Name of the field. Null in case of a form level error.
    private final String field;

    // Error code. Typically the I18n message-code.
    private final String code;

    // Error message
    private final String message;

    /**
     * Converts a set of ConstraintViolations
     * to a list of FieldErrors
     */

    /**
     * Converts a ConstraintViolation
     * to a FieldError
     */
    private static LemonFieldError of(ConstraintViolation<?> constraintViolation) {
        // Get the field name by removing the first part of the propertyPath.
        // (The first part would be the service method name)
        String field = StringUtils.substringAfter(constraintViolation.getPropertyPath().toString(), ".");
        return new LemonFieldError(field, constraintViolation.getMessageTemplate(), constraintViolation.getMessage());
    }

    public static List<LemonFieldError> getErrors(WebExchangeBindException ex) {
        List<LemonFieldError> errors = ex.getFieldErrors().stream().map(LemonFieldError::of).collect(Collectors.toList());
        errors.addAll(ex.getGlobalErrors().stream().map(LemonFieldError::of).collect(Collectors.toSet()));
        return errors;
    }

    private static LemonFieldError of(FieldError fieldError) {
        return new LemonFieldError(fieldError.getObjectName() + "." + fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage());
    }

    public static LemonFieldError of(ObjectError error) {
        return new LemonFieldError(error.getObjectName(), error.getCode(), error.getDefaultMessage());
    }
}


@objid("e7106362-faf7-4de6-8f2c-a192145b7b58")
    List<IRTModule> getStartedModules();

/*
 *
 * This file is part of Modelio.
 *
 *
 */
package org.modelio.platform.mda.infra.service;

import java.util.List;
import com.modeliosoft.modelio.javadesigner.annotations.objid;
import org.modelio.api.module.mda.IMdaExpert;

/**
 * Access to services provided by deployed modules.
 */
@objid("6f8ea657-4d53-473c-9049-d13dd320c297")
public interface IModuleService {

    /**
     * The MDA expert tool can answer questions about dependencies between stereotyped metaclass or elements.
     *
     * @return the MDA expert.
     */
    @objid("d28f6b20-c3c7-4ff4-9cd1-c13c26b869a6")
    IMdaExpert getMdaExpert();

    /**
     * Get the started modules.
     *
     * @return The started modules.
     */


public DefaultOfficeManagerConfiguration setWorkDir(File workDir) {
        checkArgumentNotNull("workDir", workDir);
        this.workDir = workDir;
        return this;
    }

// JODConverter - Java OpenDocument Converter
package org.artofsolving.jodconverter.office;

import java.io.File;
import org.artofsolving.jodconverter.process.ProcessManager;
import org.artofsolving.jodconverter.process.PureJavaProcessManager;
import org.artofsolving.jodconverter.process.LinuxProcessManager;
import org.artofsolving.jodconverter.process.SigarProcessManager;
import org.artofsolving.jodconverter.util.PlatformUtils;

public class DefaultOfficeManagerConfiguration {

    public static final long DEFAULT_RETRY_TIMEOUT = 120000L;

    private File officeHome = OfficeUtils.getDefaultOfficeHome();

    private OfficeConnectionProtocol connectionProtocol = OfficeConnectionProtocol.SOCKET;

    private int[] portNumbers = new int[] { 2002 };

    private String[] pipeNames = new String[] { "office" };

    private String[] runAsArgs = null;

    private File templateProfileDir = null;

    private File workDir = new File(System.getProperty("java.io.tmpdir"));

    private long taskQueueTimeout = 30000L;

    private long taskExecutionTimeout = 120000L;

    private int maxTasksPerProcess = 200;

    private long retryTimeout = DEFAULT_RETRY_TIMEOUT;

    // lazily initialised
    private ProcessManager processManager = null;

    public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        return setOfficeHome(new File(officeHome));
    }

    public DefaultOfficeManagerConfiguration setOfficeHome(File officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        checkArgument("officeHome", officeHome.isDirectory(), "must exist and be a directory");
        this.officeHome = officeHome;
        return this;
    }

    public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol connectionProtocol) throws NullPointerException {
        checkArgumentNotNull("connectionProtocol", connectionProtocol);
        this.connectionProtocol = connectionProtocol;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumber(int portNumber) {
        this.portNumbers = new int[] { portNumber };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumbers(int... portNumbers) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("portNumbers", portNumbers);
        checkArgument("portNumbers", portNumbers.length > 0, "must not be empty");
        this.portNumbers = portNumbers;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeName(String pipeName) throws NullPointerException {
        checkArgumentNotNull("pipeName", pipeName);
        this.pipeNames = new String[] { pipeName };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeNames(String... pipeNames) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("pipeNames", pipeNames);
        checkArgument("pipeNames", pipeNames.length > 0, "must not be empty");
        this.pipeNames = pipeNames;
        return this;
    }

    public DefaultOfficeManagerConfiguration setRunAsArgs(String... runAsArgs) {
        this.runAsArgs = runAsArgs;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir) throws IllegalArgumentException {
        if (templateProfileDir != null) {
            checkArgument("templateProfileDir", templateProfileDir.isDirectory(), "must exist and be a directory");
        }
        this.templateProfileDir = templateProfileDir;
        return this;
    }

    /**
     * Sets the directory where temporary office profiles will be created.
     *

     * Defaults to the system temporary directory as specified by the java.io.tmpdir system property.
     *
     * @param workDir
     * @return
     */

    public DefaultOfficeManagerConfiguration setTaskQueueTimeout(long taskQueueTimeout) {
        this.taskQueueTimeout = taskQueueTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTaskExecutionTimeout(long taskExecutionTimeout) {
        this.taskExecutionTimeout = taskExecutionTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setMaxTasksPerProcess(int maxTasksPerProcess) {
        this.maxTasksPerProcess = maxTasksPerProcess;
        return this;
    }

    /**
     * Provide a specific {@link ProcessManager} implementation
     * <p>
     * The default is to use {@link SigarProcessManager} if sigar.jar is
     * available in the classpath, otherwise {@link LinuxProcessManager}
     * on Linux and {@link PureJavaProcessManager} on other platforms.
     *
     * @param processManager
     * @return
     * @throws NullPointerException
     */
    public DefaultOfficeManagerConfiguration setProcessManager(ProcessManager processManager) throws NullPointerException {
        checkArgumentNotNull("processManager", processManager);
        this.processManager = processManager;
        return this;
    }

    /**
     * Retry timeout set in milliseconds. Used for retrying office process calls.
     * If not set, it defaults to 2 minutes
     *
     * @param retryTimeout in milliseconds
     * @return
     */
    public DefaultOfficeManagerConfiguration setRetryTimeout(long retryTimeout) {
        this.retryTimeout = retryTimeout;
        return this;
    }

    public OfficeManager buildOfficeManager() throws IllegalStateException {
        if (officeHome == null) {
            throw new IllegalStateException("officeHome not set and could not be auto-detected");
        } else if (!officeHome.isDirectory()) {
            throw new IllegalStateException("officeHome doesn't exist or is not a directory: " + officeHome);
        } else if (!OfficeUtils.getOfficeExecutable(officeHome).isFile()) {
            throw new IllegalStateException("invalid officeHome: it doesn't contain soffice.bin: " + officeHome);
        }
        if (templateProfileDir != null && !isValidProfileDir(templateProfileDir)) {
            throw new IllegalStateException("templateProfileDir doesn't appear to contain a user profile: " + templateProfileDir);
        }
        if (!workDir.isDirectory()) {
            throw new IllegalStateException("workDir doesn't exist or is not a directory: " + workDir);
        }
        if (processManager == null) {
            processManager = findBestProcessManager();
        }
        int numInstances = connectionProtocol == OfficeConnectionProtocol.PIPE ? pipeNames.length : portNumbers.length;
        UnoUrl[] unoUrls = new UnoUrl[numInstances];
        for (int i = 0; i < numInstances; i++) {
            unoUrls[i] = (connectionProtocol == OfficeConnectionProtocol.PIPE) ? UnoUrl.pipe(pipeNames[i]) : UnoUrl.socket(portNumbers[i]);
        }
        return new ProcessPoolOfficeManager(officeHome, unoUrls, runAsArgs, templateProfileDir, workDir, retryTimeout, taskQueueTimeout, taskExecutionTimeout, maxTasksPerProcess, processManager);
    }

    private ProcessManager findBestProcessManager() {
        if (isSigarAvailable()) {
            return new SigarProcessManager();
        } else if (PlatformUtils.isLinux()) {
            LinuxProcessManager processManager = new LinuxProcessManager();
            if (runAsArgs != null) {
                processManager.setRunAsArgs(runAsArgs);
            }
            return processManager;
        } else {
            // NOTE: UnixProcessManager can't be trusted to work on Solaris
            // because of the 80-char limit on ps output there
            return new PureJavaProcessManager();
        }
    }

    private boolean isSigarAvailable() {
        try {
            Class.forName("org.hyperic.sigar.Sigar", false, getClass().getClassLoader());
            return true;
        } catch (ClassNotFoundException classNotFoundException) {
            return false;
        }
    }

    private void checkArgumentNotNull(String argName, Object argValue) throws NullPointerException {
        if (argValue == null) {
            throw new NullPointerException(argName + " must not be null");
        }
    }

    private void checkArgument(String argName, boolean condition, String message) throws IllegalArgumentException {
        if (!condition) {
            throw new IllegalArgumentException(argName + " " + message);
        }
    }

    private boolean isValidProfileDir(File profileDir) {
        return new File(profileDir, "user").isDirectory();
    }
}


for (int i = 0; i < numInstances; i++) {
            unoUrls[i] = (connectionProtocol == OfficeConnectionProtocol.PIPE) ? UnoUrl.pipe(pipeNames[i]) : UnoUrl.socket(portNumbers[i]);
        }

// JODConverter - Java OpenDocument Converter
package org.artofsolving.jodconverter.office;

import java.io.File;
import org.artofsolving.jodconverter.process.ProcessManager;
import org.artofsolving.jodconverter.process.PureJavaProcessManager;
import org.artofsolving.jodconverter.process.LinuxProcessManager;
import org.artofsolving.jodconverter.process.SigarProcessManager;
import org.artofsolving.jodconverter.util.PlatformUtils;

public class DefaultOfficeManagerConfiguration {

    public static final long DEFAULT_RETRY_TIMEOUT = 120000L;

    private File officeHome = OfficeUtils.getDefaultOfficeHome();

    private OfficeConnectionProtocol connectionProtocol = OfficeConnectionProtocol.SOCKET;

    private int[] portNumbers = new int[] { 2002 };

    private String[] pipeNames = new String[] { "office" };

    private String[] runAsArgs = null;

    private File templateProfileDir = null;

    private File workDir = new File(System.getProperty("java.io.tmpdir"));

    private long taskQueueTimeout = 30000L;

    private long taskExecutionTimeout = 120000L;

    private int maxTasksPerProcess = 200;

    private long retryTimeout = DEFAULT_RETRY_TIMEOUT;

    // lazily initialised
    private ProcessManager processManager = null;

    public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        return setOfficeHome(new File(officeHome));
    }

    public DefaultOfficeManagerConfiguration setOfficeHome(File officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        checkArgument("officeHome", officeHome.isDirectory(), "must exist and be a directory");
        this.officeHome = officeHome;
        return this;
    }

    public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol connectionProtocol) throws NullPointerException {
        checkArgumentNotNull("connectionProtocol", connectionProtocol);
        this.connectionProtocol = connectionProtocol;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumber(int portNumber) {
        this.portNumbers = new int[] { portNumber };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumbers(int... portNumbers) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("portNumbers", portNumbers);
        checkArgument("portNumbers", portNumbers.length > 0, "must not be empty");
        this.portNumbers = portNumbers;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeName(String pipeName) throws NullPointerException {
        checkArgumentNotNull("pipeName", pipeName);
        this.pipeNames = new String[] { pipeName };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeNames(String... pipeNames) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("pipeNames", pipeNames);
        checkArgument("pipeNames", pipeNames.length > 0, "must not be empty");
        this.pipeNames = pipeNames;
        return this;
    }

    public DefaultOfficeManagerConfiguration setRunAsArgs(String... runAsArgs) {
        this.runAsArgs = runAsArgs;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir) throws IllegalArgumentException {
        if (templateProfileDir != null) {
            checkArgument("templateProfileDir", templateProfileDir.isDirectory(), "must exist and be a directory");
        }
        this.templateProfileDir = templateProfileDir;
        return this;
    }

    /**
     * Sets the directory where temporary office profiles will be created.
     *

     * Defaults to the system temporary directory as specified by the java.io.tmpdir system property.
     *
     * @param workDir
     * @return
     */
    public DefaultOfficeManagerConfiguration setWorkDir(File workDir) {
        checkArgumentNotNull("workDir", workDir);
        this.workDir = workDir;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTaskQueueTimeout(long taskQueueTimeout) {
        this.taskQueueTimeout = taskQueueTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTaskExecutionTimeout(long taskExecutionTimeout) {
        this.taskExecutionTimeout = taskExecutionTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setMaxTasksPerProcess(int maxTasksPerProcess) {
        this.maxTasksPerProcess = maxTasksPerProcess;
        return this;
    }

    /**
     * Provide a specific {@link ProcessManager} implementation
     *

     * The default is to use {@link SigarProcessManager} if sigar.jar is
     * available in the classpath, otherwise {@link LinuxProcessManager}
     * on Linux and {@link PureJavaProcessManager} on other platforms.
     *
     * @param processManager
     * @return
     * @throws NullPointerException
     */
    public DefaultOfficeManagerConfiguration setProcessManager(ProcessManager processManager) throws NullPointerException {
        checkArgumentNotNull("processManager", processManager);
        this.processManager = processManager;
        return this;
    }

    /**
     * Retry timeout set in milliseconds. Used for retrying office process calls.
     * If not set, it defaults to 2 minutes
     *
     * @param retryTimeout in milliseconds
     * @return
     */
    public DefaultOfficeManagerConfiguration setRetryTimeout(long retryTimeout) {
        this.retryTimeout = retryTimeout;
        return this;
    }

    public OfficeManager buildOfficeManager() throws IllegalStateException {
        if (officeHome == null) {
            throw new IllegalStateException("officeHome not set and could not be auto-detected");
        } else if (!officeHome.isDirectory()) {
            throw new IllegalStateException("officeHome doesn't exist or is not a directory: " + officeHome);
        } else if (!OfficeUtils.getOfficeExecutable(officeHome).isFile()) {
            throw new IllegalStateException("invalid officeHome: it doesn't contain soffice.bin: " + officeHome);
        }
        if (templateProfileDir != null && !isValidProfileDir(templateProfileDir)) {
            throw new IllegalStateException("templateProfileDir doesn't appear to contain a user profile: " + templateProfileDir);
        }
        if (!workDir.isDirectory()) {
            throw new IllegalStateException("workDir doesn't exist or is not a directory: " + workDir);
        }
        if (processManager == null) {
            processManager = findBestProcessManager();
        }
        int numInstances = connectionProtocol == OfficeConnectionProtocol.PIPE ? pipeNames.length : portNumbers.length;
        UnoUrl[] unoUrls = new UnoUrl[numInstances];

        return new ProcessPoolOfficeManager(officeHome, unoUrls, runAsArgs, templateProfileDir, workDir, retryTimeout, taskQueueTimeout, taskExecutionTimeout, maxTasksPerProcess, processManager);
    }

    private ProcessManager findBestProcessManager() {
        if (isSigarAvailable()) {
            return new SigarProcessManager();
        } else if (PlatformUtils.isLinux()) {
            LinuxProcessManager processManager = new LinuxProcessManager();
            if (runAsArgs != null) {
                processManager.setRunAsArgs(runAsArgs);
            }
            return processManager;
        } else {
            // NOTE: UnixProcessManager can't be trusted to work on Solaris
            // because of the 80-char limit on ps output there
            return new PureJavaProcessManager();
        }
    }

    private boolean isSigarAvailable() {
        try {
            Class.forName("org.hyperic.sigar.Sigar", false, getClass().getClassLoader());
            return true;
        } catch (ClassNotFoundException classNotFoundException) {
            return false;
        }
    }

    private void checkArgumentNotNull(String argName, Object argValue) throws NullPointerException {
        if (argValue == null) {
            throw new NullPointerException(argName + " must not be null");
        }
    }

    private void checkArgument(String argName, boolean condition, String message) throws IllegalArgumentException {
        if (!condition) {
            throw new IllegalArgumentException(argName + " " + message);
        }
    }

    private boolean isValidProfileDir(File profileDir) {
        return new File(profileDir, "user").isDirectory();
    }
}


try {
            Class.forName("org.hyperic.sigar.Sigar", false, getClass().getClassLoader());
            return true;
        } catch (ClassNotFoundException classNotFoundException) {
            return false;
        }

// JODConverter - Java OpenDocument Converter
package org.artofsolving.jodconverter.office;

import java.io.File;
import org.artofsolving.jodconverter.process.ProcessManager;
import org.artofsolving.jodconverter.process.PureJavaProcessManager;
import org.artofsolving.jodconverter.process.LinuxProcessManager;
import org.artofsolving.jodconverter.process.SigarProcessManager;
import org.artofsolving.jodconverter.util.PlatformUtils;

public class DefaultOfficeManagerConfiguration {

    public static final long DEFAULT_RETRY_TIMEOUT = 120000L;

    private File officeHome = OfficeUtils.getDefaultOfficeHome();

    private OfficeConnectionProtocol connectionProtocol = OfficeConnectionProtocol.SOCKET;

    private int[] portNumbers = new int[] { 2002 };

    private String[] pipeNames = new String[] { "office" };

    private String[] runAsArgs = null;

    private File templateProfileDir = null;

    private File workDir = new File(System.getProperty("java.io.tmpdir"));

    private long taskQueueTimeout = 30000L;

    private long taskExecutionTimeout = 120000L;

    private int maxTasksPerProcess = 200;

    private long retryTimeout = DEFAULT_RETRY_TIMEOUT;

    // lazily initialised
    private ProcessManager processManager = null;

    public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        return setOfficeHome(new File(officeHome));
    }

    public DefaultOfficeManagerConfiguration setOfficeHome(File officeHome) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("officeHome", officeHome);
        checkArgument("officeHome", officeHome.isDirectory(), "must exist and be a directory");
        this.officeHome = officeHome;
        return this;
    }

    public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol connectionProtocol) throws NullPointerException {
        checkArgumentNotNull("connectionProtocol", connectionProtocol);
        this.connectionProtocol = connectionProtocol;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumber(int portNumber) {
        this.portNumbers = new int[] { portNumber };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPortNumbers(int... portNumbers) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("portNumbers", portNumbers);
        checkArgument("portNumbers", portNumbers.length > 0, "must not be empty");
        this.portNumbers = portNumbers;
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeName(String pipeName) throws NullPointerException {
        checkArgumentNotNull("pipeName", pipeName);
        this.pipeNames = new String[] { pipeName };
        return this;
    }

    public DefaultOfficeManagerConfiguration setPipeNames(String... pipeNames) throws NullPointerException, IllegalArgumentException {
        checkArgumentNotNull("pipeNames", pipeNames);
        checkArgument("pipeNames", pipeNames.length > 0, "must not be empty");
        this.pipeNames = pipeNames;
        return this;
    }

    public DefaultOfficeManagerConfiguration setRunAsArgs(String... runAsArgs) {
        this.runAsArgs = runAsArgs;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir) throws IllegalArgumentException {
        if (templateProfileDir != null) {
            checkArgument("templateProfileDir", templateProfileDir.isDirectory(), "must exist and be a directory");
        }
        this.templateProfileDir = templateProfileDir;
        return this;
    }

    /**
     * Sets the directory where temporary office profiles will be created.
     *

     * Defaults to the system temporary directory as specified by the java.io.tmpdir system property.
     *
     * @param workDir
     * @return
     */
    public DefaultOfficeManagerConfiguration setWorkDir(File workDir) {
        checkArgumentNotNull("workDir", workDir);
        this.workDir = workDir;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTaskQueueTimeout(long taskQueueTimeout) {
        this.taskQueueTimeout = taskQueueTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setTaskExecutionTimeout(long taskExecutionTimeout) {
        this.taskExecutionTimeout = taskExecutionTimeout;
        return this;
    }

    public DefaultOfficeManagerConfiguration setMaxTasksPerProcess(int maxTasksPerProcess) {
        this.maxTasksPerProcess = maxTasksPerProcess;
        return this;
    }

    /**
     * Provide a specific {@link ProcessManager} implementation
     *

     * The default is to use {@link SigarProcessManager} if sigar.jar is
     * available in the classpath, otherwise {@link LinuxProcessManager}
     * on Linux and {@link PureJavaProcessManager} on other platforms.
     *
     * @param processManager
     * @return
     * @throws NullPointerException
     */
    public DefaultOfficeManagerConfiguration setProcessManager(ProcessManager processManager) throws NullPointerException {
        checkArgumentNotNull("processManager", processManager);
        this.processManager = processManager;
        return this;
    }

    /**
     * Retry timeout set in milliseconds. Used for retrying office process calls.
     * If not set, it defaults to 2 minutes
     *
     * @param retryTimeout in milliseconds
     * @return
     */
    public DefaultOfficeManagerConfiguration setRetryTimeout(long retryTimeout) {
        this.retryTimeout = retryTimeout;
        return this;
    }

    public OfficeManager buildOfficeManager() throws IllegalStateException {
        if (officeHome == null) {
            throw new IllegalStateException("officeHome not set and could not be auto-detected");
        } else if (!officeHome.isDirectory()) {
            throw new IllegalStateException("officeHome doesn't exist or is not a directory: " + officeHome);
        } else if (!OfficeUtils.getOfficeExecutable(officeHome).isFile()) {
            throw new IllegalStateException("invalid officeHome: it doesn't contain soffice.bin: " + officeHome);
        }
        if (templateProfileDir != null && !isValidProfileDir(templateProfileDir)) {
            throw new IllegalStateException("templateProfileDir doesn't appear to contain a user profile: " + templateProfileDir);
        }
        if (!workDir.isDirectory()) {
            throw new IllegalStateException("workDir doesn't exist or is not a directory: " + workDir);
        }
        if (processManager == null) {
            processManager = findBestProcessManager();
        }
        int numInstances = connectionProtocol == OfficeConnectionProtocol.PIPE ? pipeNames.length : portNumbers.length;
        UnoUrl[] unoUrls = new UnoUrl[numInstances];
        for (int i = 0; i < numInstances; i++) {
            unoUrls[i] = (connectionProtocol == OfficeConnectionProtocol.PIPE) ? UnoUrl.pipe(pipeNames[i]) : UnoUrl.socket(portNumbers[i]);
        }
        return new ProcessPoolOfficeManager(officeHome, unoUrls, runAsArgs, templateProfileDir, workDir, retryTimeout, taskQueueTimeout, taskExecutionTimeout, maxTasksPerProcess, processManager);
    }

    private ProcessManager findBestProcessManager() {
        if (isSigarAvailable()) {
            return new SigarProcessManager();
        } else if (PlatformUtils.isLinux()) {
            LinuxProcessManager processManager = new LinuxProcessManager();
            if (runAsArgs != null) {
                processManager.setRunAsArgs(runAsArgs);
            }
            return processManager;
        } else {
            // NOTE: UnixProcessManager can't be trusted to work on Solaris
            // because of the 80-char limit on ps output there
            return new PureJavaProcessManager();
        }
    }

    private boolean isSigarAvailable() {

    }

    private void checkArgumentNotNull(String argName, Object argValue) throws NullPointerException {
        if (argValue == null) {
            throw new NullPointerException(argName + " must not be null");
        }
    }

    private void checkArgument(String argName, boolean condition, String message) throws IllegalArgumentException {
        if (!condition) {
            throw new IllegalArgumentException(argName + " " + message);
        }
    }

    private boolean isValidProfileDir(File profileDir) {
        return new File(profileDir, "user").isDirectory();
    }
}


public static float getWorldTime(World world) {
        return getWorldTime(world, 0);
    }

package net.minecraftforge.client.model.animation;

import net.minecraft.world.World;
import java.lang.ref.WeakReference;

public enum Animation {

    INSTANCE;

    private float clientPartialTickTime;

    private static long epochTime;

    private static WeakReference<World> worldRef;

    /**
     * Get the global world time for the current tick, in seconds.
     */

    /**
     * Get the global world time for the current tick + partial tick progress, in seconds.
     */
    public static float getWorldTime(World world, float tickProgress) {
        if (worldRef == null || worldRef.get() != world) {
            epochTime = world.getGameTime();
            worldRef = new WeakReference<>(world);
        }
        return (world.getGameTime() - epochTime + tickProgress) / 20;
    }

    /**
     * Get current partialTickTime.
     */
    public static float getPartialTickTime() {
        return INSTANCE.clientPartialTickTime;
    }

    public static void setClientPartialTickTime(float clientPartialTickTime) {
        Animation.INSTANCE.clientPartialTickTime = clientPartialTickTime;
    }
}


public void buildWSDLResponse(HttpServletRequest request, HttpServletResponse response, Servlet templateReplayWSDLRenderer) throws IOException, ServletException, Exception;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.easysoa.proxy.core.api.template;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jguillemotte
 */
public interface WsdlDataStoreProvider {

    // TODO : inject velocity components to render store list or WSDL
    // TODO : ProxyFileStore as Reference, no proxyFileStore composite at this time
    // @Reference
    // void buildResponse(String requestedResource, VelocityEngine velocityEngine, VelocityContext velocityContext, HttpServletRequest request, HttpServletResponse response) throws IOException;
    /**
     * Build a response containing the HTML formated store list
     * @param request The http request
     * @param response The http response to build
     * @Param templateReplayWSDLHTMLListRenderer The template renderer
     * @throws IOException If a problem occurs
     */
    public void buildStoreListHTMLResponse(HttpServletRequest request, HttpServletResponse response, Servlet templateReplayWSDLHTMLListRenderer) throws IOException, ServletException;

    /**
     * Build a response containing a WSDL file. The WSDL file is generated from
     * a FLD file processed by a velocity template
     * @param request The http request
     * @param response The http response to build
     * @param templateReplayWSDLRenderer The template renderer
     * @throws IOException If a problem occurs
     */


for (int i = 0, length = projects.length; i < length; i++) {
            IJavaProject project = projects[i];
            if (project.equals(projectOfRoot))
                continue;
            updateProjectClasspath(rootPath, project, oldRoots);
        }

/**
 * ****************************************************************************
 *  Copyright (c) 2000, 2013 IBM Corporation and others.
 *
 *  This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License 2.0
 *  which accompanies this distribution, and is available at
 *  https://www.eclipse.org/legal/epl-2.0/
 *
 *  SPDX-License-Identifier: EPL-2.0
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.core;

import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.*;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class DeletePackageFragmentRootOperation extends JavaModelOperation {

    int updateResourceFlags;

    int updateModelFlags;

    public DeletePackageFragmentRootOperation(IPackageFragmentRoot root, int updateResourceFlags, int updateModelFlags) {
        super(root);
        this.updateResourceFlags = updateResourceFlags;
        this.updateModelFlags = updateModelFlags;
    }

    @Override
    protected void executeOperation() throws JavaModelException {
        IPackageFragmentRoot root = (IPackageFragmentRoot) getElementToProcess();
        IClasspathEntry rootEntry = root.getRawClasspathEntry();
        // remember olds roots
        DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().getDeltaProcessor();
        if (deltaProcessor.oldRoots == null)
            deltaProcessor.oldRoots = new HashMap();
        // update classpath if needed
        if ((this.updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH) != 0) {
            updateProjectClasspath(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
        }
        if ((this.updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_CLASSPATH) != 0) {
            updateReferringProjectClasspaths(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
        }
        // delete resource
        if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
            deleteResource(root, rootEntry);
        }
    }

    protected void deleteResource(IPackageFragmentRoot root, IClasspathEntry rootEntry) throws JavaModelException {
        final char[][] exclusionPatterns = ((ClasspathEntry) rootEntry).fullExclusionPatternChars();
        IResource rootResource = ((JavaElement) root).resource();
        if (rootEntry.getEntryKind() != IClasspathEntry.CPE_SOURCE || exclusionPatterns == null) {
            try {
                rootResource.delete(this.updateResourceFlags, this.progressMonitor);
            } catch (CoreException e) {
                throw new JavaModelException(e);
            }
        } else {
            final IPath[] nestedFolders = getNestedFolders(root);
            IResourceProxyVisitor visitor = new IResourceProxyVisitor() {

                @Override
                public boolean visit(IResourceProxy proxy) throws CoreException {
                    if (proxy.getType() == IResource.FOLDER) {
                        IPath path = proxy.requestFullPath();
                        if (prefixesOneOf(path, nestedFolders)) {
                            // equals if nested source folder
                            return !equalsOneOf(path, nestedFolders);
                        } else {
                            // subtree doesn't contain any nested source folders
                            proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
                            return false;
                        }
                    } else {
                        proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
                        return false;
                    }
                }
            };
            try {
                rootResource.accept(visitor, IResource.NONE);
            } catch (CoreException e) {
                throw new JavaModelException(e);
            }
        }
        setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
    }

    /*
	 * Deletes the classpath entries equals to the given rootPath from all Java projects.
	 */
    protected void updateReferringProjectClasspaths(IPath rootPath, IJavaProject projectOfRoot, Map oldRoots) throws JavaModelException {
        IJavaModel model = getJavaModel();
        IJavaProject[] projects = model.getJavaProjects();

    }

    /*
	 * Deletes the classpath entries equals to the given rootPath from the given project.
	 */
    protected void updateProjectClasspath(IPath rootPath, IJavaProject project, Map oldRoots) throws JavaModelException {
        // remember old roots
        oldRoots.put(project, project.getPackageFragmentRoots());
        IClasspathEntry[] classpath = project.getRawClasspath();
        IClasspathEntry[] newClasspath = null;
        int cpLength = classpath.length;
        int newCPIndex = -1;
        for (int j = 0; j < cpLength; j++) {
            IClasspathEntry entry = classpath[j];
            if (rootPath.equals(entry.getPath())) {
                if (newClasspath == null) {
                    newClasspath = new IClasspathEntry[cpLength - 1];
                    System.arraycopy(classpath, 0, newClasspath, 0, j);
                    newCPIndex = j;
                }
            } else if (newClasspath != null) {
                newClasspath[newCPIndex++] = entry;
            }
        }
        if (newClasspath != null) {
            if (newCPIndex < newClasspath.length) {
                System.arraycopy(newClasspath, 0, newClasspath = new IClasspathEntry[newCPIndex], 0, newCPIndex);
            }
            project.setRawClasspath(newClasspath, this.progressMonitor);
        }
    }

    @Override
    protected IJavaModelStatus verify() {
        IJavaModelStatus status = super.verify();
        if (!status.isOK()) {
            return status;
        }
        IJavaElement root = getElementToProcess();
        if (root == null || !root.exists()) {
            return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, root);
        }
        IResource resource = ((JavaElement) root).resource();
        if (resource instanceof IFolder) {
            if (resource.isLinked()) {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE, root);
            }
        }
        return JavaModelStatus.VERIFIED_OK;
    }
}


try {
                rootResource.accept(visitor, IResource.NONE);
            } catch (CoreException e) {
                throw new JavaModelException(e);
            }

/**
 * ****************************************************************************
 *  Copyright (c) 2000, 2013 IBM Corporation and others.
 *
 *  This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License 2.0
 *  which accompanies this distribution, and is available at
 *  https://www.eclipse.org/legal/epl-2.0/
 *
 *  SPDX-License-Identifier: EPL-2.0
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.core;

import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.*;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class DeletePackageFragmentRootOperation extends JavaModelOperation {

    int updateResourceFlags;

    int updateModelFlags;

    public DeletePackageFragmentRootOperation(IPackageFragmentRoot root, int updateResourceFlags, int updateModelFlags) {
        super(root);
        this.updateResourceFlags = updateResourceFlags;
        this.updateModelFlags = updateModelFlags;
    }

    @Override
    protected void executeOperation() throws JavaModelException {
        IPackageFragmentRoot root = (IPackageFragmentRoot) getElementToProcess();
        IClasspathEntry rootEntry = root.getRawClasspathEntry();
        // remember olds roots
        DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().getDeltaProcessor();
        if (deltaProcessor.oldRoots == null)
            deltaProcessor.oldRoots = new HashMap();
        // update classpath if needed
        if ((this.updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH) != 0) {
            updateProjectClasspath(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
        }
        if ((this.updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_CLASSPATH) != 0) {
            updateReferringProjectClasspaths(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
        }
        // delete resource
        if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
            deleteResource(root, rootEntry);
        }
    }

    protected void deleteResource(IPackageFragmentRoot root, IClasspathEntry rootEntry) throws JavaModelException {
        final char[][] exclusionPatterns = ((ClasspathEntry) rootEntry).fullExclusionPatternChars();
        IResource rootResource = ((JavaElement) root).resource();
        if (rootEntry.getEntryKind() != IClasspathEntry.CPE_SOURCE || exclusionPatterns == null) {
            try {
                rootResource.delete(this.updateResourceFlags, this.progressMonitor);
            } catch (CoreException e) {
                throw new JavaModelException(e);
            }
        } else {
            final IPath[] nestedFolders = getNestedFolders(root);
            IResourceProxyVisitor visitor = new IResourceProxyVisitor() {

                @Override
                public boolean visit(IResourceProxy proxy) throws CoreException {
                    if (proxy.getType() == IResource.FOLDER) {
                        IPath path = proxy.requestFullPath();
                        if (prefixesOneOf(path, nestedFolders)) {
                            // equals if nested source folder
                            return !equalsOneOf(path, nestedFolders);
                        } else {
                            // subtree doesn't contain any nested source folders
                            proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
                            return false;
                        }
                    } else {
                        proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
                        return false;
                    }
                }
            };

        }
        setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
    }

    /*
	 * Deletes the classpath entries equals to the given rootPath from all Java projects.
	 */
    protected void updateReferringProjectClasspaths(IPath rootPath, IJavaProject projectOfRoot, Map oldRoots) throws JavaModelException {
        IJavaModel model = getJavaModel();
        IJavaProject[] projects = model.getJavaProjects();
        for (int i = 0, length = projects.length; i < length; i++) {
            IJavaProject project = projects[i];
            if (project.equals(projectOfRoot))
                continue;
            updateProjectClasspath(rootPath, project, oldRoots);
        }
    }

    /*
	 * Deletes the classpath entries equals to the given rootPath from the given project.
	 */
    protected void updateProjectClasspath(IPath rootPath, IJavaProject project, Map oldRoots) throws JavaModelException {
        // remember old roots
        oldRoots.put(project, project.getPackageFragmentRoots());
        IClasspathEntry[] classpath = project.getRawClasspath();
        IClasspathEntry[] newClasspath = null;
        int cpLength = classpath.length;
        int newCPIndex = -1;
        for (int j = 0; j < cpLength; j++) {
            IClasspathEntry entry = classpath[j];
            if (rootPath.equals(entry.getPath())) {
                if (newClasspath == null) {
                    newClasspath = new IClasspathEntry[cpLength - 1];
                    System.arraycopy(classpath, 0, newClasspath, 0, j);
                    newCPIndex = j;
                }
            } else if (newClasspath != null) {
                newClasspath[newCPIndex++] = entry;
            }
        }
        if (newClasspath != null) {
            if (newCPIndex < newClasspath.length) {
                System.arraycopy(newClasspath, 0, newClasspath = new IClasspathEntry[newCPIndex], 0, newCPIndex);
            }
            project.setRawClasspath(newClasspath, this.progressMonitor);
        }
    }

    @Override
    protected IJavaModelStatus verify() {
        IJavaModelStatus status = super.verify();
        if (!status.isOK()) {
            return status;
        }
        IJavaElement root = getElementToProcess();
        if (root == null || !root.exists()) {
            return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, root);
        }
        IResource resource = ((JavaElement) root).resource();
        if (resource instanceof IFolder) {
            if (resource.isLinked()) {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE, root);
            }
        }
        return JavaModelStatus.VERIFIED_OK;
    }
}


void nodeChanged(FileSystemBrowserTreeNode paramBrowserTreeNode, TreeEventType paramTreeEventType);

package com.fangyuzhong.intelliJ.hadoop.fsbrowser.model;

import com.fangyuzhong.intelliJ.hadoop.core.ui.tree.TreeEventType;
import com.intellij.util.messages.Topic;
import java.util.EventListener;

/**
 * Created by fangyuzhong on 17-7-16.
 */
public interface BrowserTreeEventListener extends EventListener {

    final Topic<BrowserTreeEventListener> TOPIC = Topic.create("Browser tree event", BrowserTreeEventListener.class);

    /**
     * 树节点Node改变事件触发的方法
     * @param paramBrowserTreeNode Node接口
     * @param paramTreeEventType 事件类型枚举
     */

    /**
     * 树节点Node选中改变事件触发的方法
     */
    void selectionChanged();
}


while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            if (org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)) {
                continue;
            }
            java.util.Enumeration<String> values = request.getHeaders(name);
            if (values != null && values.hasMoreElements()) {
                param = name;
                break;
            }
        }

/**
 * OWASP Benchmark Project v1.2
 *
 *
This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
 * details, please see http://example.com.
 *
 * @author Dave Wichers
 * @created 2015
 */
package org.owasp.benchmark.testcode;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/hash-01/BenchmarkTest01125")
public class BenchmarkTest01125 extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String param = "";
        java.util.Enumeration<String> names = request.getHeaderNames();

        // Note: We don't URL decode header names because people don't normally do that
        String bar = new Test().doSomething(request, param);
        try {
            java.util.Properties benchmarkprops = new java.util.Properties();
            benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
            String algorithm = benchmarkprops.getProperty("hashAlg2", "SHA5");
            java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
            byte[] input = { (byte) '?' };
            Object inputParam = bar;
            if (inputParam instanceof String)
                input = ((String) inputParam).getBytes();
            if (inputParam instanceof java.io.InputStream) {
                byte[] strInput = new byte[1000];
                int i = ((java.io.InputStream) inputParam).read(strInput);
                if (i == -1) {
                    response.getWriter().println("This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
                    return;
                }
                input = java.util.Arrays.copyOf(strInput, i);
            }
            md.update(input);
            byte[] result = md.digest();
            java.io.File fileTarget = new java.io.File(new java.io.File(org.owasp.benchmark.helpers.Utils.TESTFILES_DIR), "passwordFile.txt");
            java.io.FileWriter fw = // the true will append the new data
            new java.io.FileWriter(fileTarget, true);
            fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
            fw.close();
            response.getWriter().println("Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' hashed and stored<br/>");
        } catch (java.security.NoSuchAlgorithmException e) {
            System.out.println("Problem executing hash - TestCase");
            throw new ServletException(e);
        }
        response.getWriter().println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
    }

    // end doPost
    private class Test {

        public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
            org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
            String bar = thing.doSomething(param);
            return bar;
        }
    }
    // end innerclass Test
}
// end DataflowThruInnerClass


public double getMaxValue() {
        return _fbmic.getClipMax();
    }

package edu.mines.jtk.awt;

import java.awt.image.IndexColorModel;
import static java.lang.Math.floor;
import edu.mines.jtk.util.Check;
import edu.mines.jtk.util.FloatByteMap;

/**
 * Maps arrays of floats to colors.
 *

 * This mapping consists of two parts. Floats are first mapped to bytes,
 * and then those bytes are mapped to colors.
 *

 * The first mapping from floats to bytes is linear between minimum and
 * maximum clip values. Values below and above these min and max values
 * are clipped. Clips may be computed from percentiles or may be specified
 * explicitly. By default, the clip min and max values are the minimum
 * and maximum values in specified arrays of floats.
 *

 * The second mapping depends on the number of arrays of floats specified.
 * When only one array is specified, each byte from the float-to-byte
 * mapping is used as an index for an index color model with 256 colors.
 *

 * When three arrays are specified, a float value from each of the three
 * arrays is first mapped independently (using different float-to-byte
 * maps, possibly with different clips) to obtain three bytes. These
 * three bytes are then interpreted directly as color components in
 * either (red,green,blue) or (hue,saturation,brightness) color models.
 * Because each color component can have 256 values, millions of colors
 * are possible.
 *

 * When four arrays are specified, the mapping is the same as for three
 * arrays, except that the fourth array corresponds to an alpha (opacity)
 * component.
 *

 * An index color model may be useful even when three or four arrays are
 * specified, by specifying one of the arrays to serve as a source of
 * of byte indices. This capability enables a single float value to be
 * mapped to a color, even when three or four arrays of floats are
 * specified. For example, if the index color model contained fully
 * saturated and bright colors with different hues, then one might
 * specify the array corresponding to the hue component as the source
 * of byte indices. The indexed colors might then be displayed in a color
 * bar.
 *

 * By default, direct color components with indices 0, 1, and 2 are red,
 * green, and blue, respectively. If HSB components are enabled, then
 * these same indices instead correspond to components hue, saturation,
 * and brightness. Enabling HSB adds an extra conversion step to the
 * mapping from floats to colors. After three bytes are computed from
 * three floats, these HSB byte values are then mapped to the nearest
 * RGB byte values. The hues corresponding to min/max byte values 0
 * and 255 are red (0.00) and blue (0.67), but these hues may be
 * specified explicitly. This extra conversion step is never performed
 * for indexed color mappings of single float values.
 *
 * @author Dave Hale, Colorado School of Mines
 * @version 2007.08.08
 */
public class FloatColorMap extends ColorMap {

    /**
     * Constructs a color map with only indexed colors.
     * @param f an array of floats.
     * @param icm the index color model.
     */
    public FloatColorMap(float[][] f, IndexColorModel icm) {
        this(new float[][][] { f }, 0, icm);
    }

    /**
     * Constructs a color map with more than one color components.
     * @param f arrays of floats, one array for each color component.
     * @param ic array index of the component for the index color model.
     * @param icm the index color model corresponding to one component.
     */
    public FloatColorMap(float[][][] f, int ic, IndexColorModel icm) {
        super(icm);
        Check.argument(f.length == 1 || f.length == 3 || f.length == 4, "number of arrays (color components) equals 1, 3, or 4");
        int nc = f.length;
        FloatByteMap[] fbm = new FloatByteMap[nc];
        for (int jc = 0; jc < nc; ++jc) fbm[jc] = new FloatByteMap(f[jc]);
        _fbmi0 = fbm[0];
        _fbmi1 = (nc > 1) ? fbm[1] : fbm[0];
        _fbmi2 = (nc > 1) ? fbm[2] : fbm[0];
        _fbmi3 = (nc > 3) ? fbm[3] : null;
        _fbmic = fbm[ic];
    }

    /**
     * Enables or disables HSB components. By default, color components
     * 0, 1, and 2 (if specified) correspond to red, green, and blue. If HSB
     * components are enabled, these indices correspond to hue, saturation,
     * and brightness. Then, as floats are mapped to colors, bytes for HSB
     * are converted to RGB.
     * @param hsb true, to enable HSB components; false, for RGB components.
     */
    public void setHSB(boolean hsb) {
        _hsb = hsb;
    }

    /**
     * Sets hue values corresponding to byte values 0 and 255.
     * These hues are used only when HSB components are enabled.
     * @param hue000 hue corresponding to byte value 0; default is 0.00 (red).
     * @param hue255 hue corresponding to byte value 255; default is 0.67 (blue).
     */
    public void setHues(double hue000, double hue255) {
        _hue000 = (float) hue000;
        _hue255 = (float) hue255;
    }

    /**
     * Gets the color index corresponding to the specified value.
     * @param f the value to be mapped to index.
     * @return the index in the range [0,255].
     */
    public int getIndex(float f) {
        return _fbmic.getByte(f);
    }

    /**
     * Gets the 32-bit color in 0xAARRGGBB format for the specified value.
     * This method uses the index color model.
     * @param f the value to be mapped to a color.
     * @return the pixel.
     */
    public int getARGB(float f) {
        return getColorModel().getRGB(getIndex(f));
    }

    /**
     * Gets the 32-bit color in 0xffRRGGBB format for specified values.
     * This method does not use the index color model.
     * @param f0 the value for color component 0.
     * @param f1 the value for color component 1.
     * @param f2 the value for color component 2.
     * @return the color.
     */
    public int getRGB(float f0, float f1, float f2) {
        int i0 = _fbmi0.getByte(f0);
        int i1 = _fbmi1.getByte(f1);
        int i2 = _fbmi2.getByte(f2);
        return (_hsb) ? rgbFromHsb(i0, i1, i2) : rgbFromRgb(i0, i1, i2);
    }

    /**
     * Gets the 32-bit color in 0xAARRGGBB format for specified values.
     * This method does not use the index color model.
     * @param f0 the value for color component 0.
     * @param f1 the value for color component 1.
     * @param f2 the value for color component 2.
     * @param f3 the value for color component 3.
     * @return the color.
     */
    public int getARGB(float f0, float f1, float f2, float f3) {
        int i0 = _fbmi0.getByte(f0);
        int i1 = _fbmi1.getByte(f1);
        int i2 = _fbmi2.getByte(f2);
        int i3 = (_fbmi3 != null) ? _fbmi3.getByte(f3) : 0xff;
        return (_hsb) ? argbFromHsba(i0, i1, i2, i3) : argbFromRgba(i0, i1, i2, i3);
    }

    // Override
    /**
     * Gets the color index corresponding to the specified value.
     * @param v the value to be mapped to index.
     * @return the index in the range [0,255].
     */
    public int getIndex(double v) {
        return getIndex((float) v);
    }

    /**
     * Gets the minimum value in the range of mapped values.
     * @return the minimum value.
     */
    public double getMinValue() {
        return _fbmic.getClipMin();
    }

    /**
     * Gets the maximum value in the range of mapped values.
     * @return the maximum value.
     */

    /**
     * Sets the min-max range of values mapped to colors. Values outside this
     * range are clipped. The default range is the min and max clips in the
     * mapping from floats to bytes.
     * @param vmin the minimum value.
     * @param vmax the maximum value.
     */
    public void setValueRange(double vmin, double vmax) {
        if ((float) vmin != getMinValue() || (float) vmax != getMaxValue()) {
            _fbmic.setClips((float) vmin, (float) vmax);
            super.setValueRange(vmin, vmax);
        }
    }

    // private int nc; // number of color components: 1, 3, or 4.
    // private int _ic; // array index of component for index color model
    // the float-byte map for index color model
    private FloatByteMap _fbmic;

    private FloatByteMap _fbmi0;

    private FloatByteMap _fbmi1;

    private FloatByteMap _fbmi2;

    private FloatByteMap _fbmi3;

    // true if components are hue, sat, brightness
    private boolean _hsb;

    // corresponds to byte value 000
    private float _hue000;

    // corresponds to byte value 255
    private float _hue255;

    private int argbFromRgba(int r, int g, int b, int a) {
        return (a << 24) | (r << 16) | (g << 8) | b;
    }

    private int rgbFromRgb(int r, int g, int b) {
        return 0xff000000 | (r << 16) | (g << 8) | b;
    }

    private int argbFromHsba(int hu, int sa, int br, int al) {
        return (al << 24) | rgbFromHsb(hu, sa, br);
    }

    private int rgbFromHsb(int hu, int sa, int br) {
        float scale = 1.0f / 255.0f;
        if (hu < 0)
            hu += 256;
        if (sa < 0)
            sa += 256;
        if (br < 0)
            br += 256;
        float hue = _hue000 + (_hue255 - _hue000) * hu * scale;
        float sat = (float) sa * scale;
        float bri = (float) br * scale;
        int r = 0, g = 0, b = 0;
        if (sat == 0.0f) {
            r = g = b = (int) (bri * 255.0f + 0.5f);
        } else {
            float h = (hue - (float) floor(hue)) * 6.0f;
            float f = h - (float) floor(h);
            float p = bri * (1.0f - sat);
            float q = bri * (1.0f - sat * f);
            float t = bri * (1.0f - sat * (1.0f - f));
            switch((int) h) {
                case 0:
                    r = (int) (bri * 255.0f + 0.5f);
                    g = (int) (t * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 1:
                    r = (int) (q * 255.0f + 0.5f);
                    g = (int) (bri * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 2:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (bri * 255.0f + 0.5f);
                    b = (int) (t * 255.0f + 0.5f);
                    break;
                case 3:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (q * 255.0f + 0.5f);
                    b = (int) (bri * 255.0f + 0.5f);
                    break;
                case 4:
                    r = (int) (t * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (bri * 255.0f + 0.5f);
                    break;
                case 5:
                    r = (int) (bri * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (q * 255.0f + 0.5f);
                    break;
            }
        }
        return rgbFromRgb(r, g, b);
    }
}


for (int jc = 0; jc < nc; ++jc) fbm[jc] = new FloatByteMap(f[jc]);

package edu.mines.jtk.awt;

import java.awt.image.IndexColorModel;
import static java.lang.Math.floor;
import edu.mines.jtk.util.Check;
import edu.mines.jtk.util.FloatByteMap;

/**
 * Maps arrays of floats to colors.
 *

 * This mapping consists of two parts. Floats are first mapped to bytes,
 * and then those bytes are mapped to colors.
 *

 * The first mapping from floats to bytes is linear between minimum and
 * maximum clip values. Values below and above these min and max values
 * are clipped. Clips may be computed from percentiles or may be specified
 * explicitly. By default, the clip min and max values are the minimum
 * and maximum values in specified arrays of floats.
 *

 * The second mapping depends on the number of arrays of floats specified.
 * When only one array is specified, each byte from the float-to-byte
 * mapping is used as an index for an index color model with 256 colors.
 *

 * When three arrays are specified, a float value from each of the three
 * arrays is first mapped independently (using different float-to-byte
 * maps, possibly with different clips) to obtain three bytes. These
 * three bytes are then interpreted directly as color components in
 * either (red,green,blue) or (hue,saturation,brightness) color models.
 * Because each color component can have 256 values, millions of colors
 * are possible.
 *

 * When four arrays are specified, the mapping is the same as for three
 * arrays, except that the fourth array corresponds to an alpha (opacity)
 * component.
 *

 * An index color model may be useful even when three or four arrays are
 * specified, by specifying one of the arrays to serve as a source of
 * of byte indices. This capability enables a single float value to be
 * mapped to a color, even when three or four arrays of floats are
 * specified. For example, if the index color model contained fully
 * saturated and bright colors with different hues, then one might
 * specify the array corresponding to the hue component as the source
 * of byte indices. The indexed colors might then be displayed in a color
 * bar.
 *

 * By default, direct color components with indices 0, 1, and 2 are red,
 * green, and blue, respectively. If HSB components are enabled, then
 * these same indices instead correspond to components hue, saturation,
 * and brightness. Enabling HSB adds an extra conversion step to the
 * mapping from floats to colors. After three bytes are computed from
 * three floats, these HSB byte values are then mapped to the nearest
 * RGB byte values. The hues corresponding to min/max byte values 0
 * and 255 are red (0.00) and blue (0.67), but these hues may be
 * specified explicitly. This extra conversion step is never performed
 * for indexed color mappings of single float values.
 *
 * @author Dave Hale, Colorado School of Mines
 * @version 2007.08.08
 */
public class FloatColorMap extends ColorMap {

    /**
     * Constructs a color map with only indexed colors.
     * @param f an array of floats.
     * @param icm the index color model.
     */
    public FloatColorMap(float[][] f, IndexColorModel icm) {
        this(new float[][][] { f }, 0, icm);
    }

    /**
     * Constructs a color map with more than one color components.
     * @param f arrays of floats, one array for each color component.
     * @param ic array index of the component for the index color model.
     * @param icm the index color model corresponding to one component.
     */
    public FloatColorMap(float[][][] f, int ic, IndexColorModel icm) {
        super(icm);
        Check.argument(f.length == 1 || f.length == 3 || f.length == 4, "number of arrays (color components) equals 1, 3, or 4");
        int nc = f.length;
        FloatByteMap[] fbm = new FloatByteMap[nc];

        _fbmi0 = fbm[0];
        _fbmi1 = (nc > 1) ? fbm[1] : fbm[0];
        _fbmi2 = (nc > 1) ? fbm[2] : fbm[0];
        _fbmi3 = (nc > 3) ? fbm[3] : null;
        _fbmic = fbm[ic];
    }

    /**
     * Enables or disables HSB components. By default, color components
     * 0, 1, and 2 (if specified) correspond to red, green, and blue. If HSB
     * components are enabled, these indices correspond to hue, saturation,
     * and brightness. Then, as floats are mapped to colors, bytes for HSB
     * are converted to RGB.
     * @param hsb true, to enable HSB components; false, for RGB components.
     */
    public void setHSB(boolean hsb) {
        _hsb = hsb;
    }

    /**
     * Sets hue values corresponding to byte values 0 and 255.
     * These hues are used only when HSB components are enabled.
     * @param hue000 hue corresponding to byte value 0; default is 0.00 (red).
     * @param hue255 hue corresponding to byte value 255; default is 0.67 (blue).
     */
    public void setHues(double hue000, double hue255) {
        _hue000 = (float) hue000;
        _hue255 = (float) hue255;
    }

    /**
     * Gets the color index corresponding to the specified value.
     * @param f the value to be mapped to index.
     * @return the index in the range [0,255].
     */
    public int getIndex(float f) {
        return _fbmic.getByte(f);
    }

    /**
     * Gets the 32-bit color in 0xAARRGGBB format for the specified value.
     * This method uses the index color model.
     * @param f the value to be mapped to a color.
     * @return the pixel.
     */
    public int getARGB(float f) {
        return getColorModel().getRGB(getIndex(f));
    }

    /**
     * Gets the 32-bit color in 0xffRRGGBB format for specified values.
     * This method does not use the index color model.
     * @param f0 the value for color component 0.
     * @param f1 the value for color component 1.
     * @param f2 the value for color component 2.
     * @return the color.
     */
    public int getRGB(float f0, float f1, float f2) {
        int i0 = _fbmi0.getByte(f0);
        int i1 = _fbmi1.getByte(f1);
        int i2 = _fbmi2.getByte(f2);
        return (_hsb) ? rgbFromHsb(i0, i1, i2) : rgbFromRgb(i0, i1, i2);
    }

    /**
     * Gets the 32-bit color in 0xAARRGGBB format for specified values.
     * This method does not use the index color model.
     * @param f0 the value for color component 0.
     * @param f1 the value for color component 1.
     * @param f2 the value for color component 2.
     * @param f3 the value for color component 3.
     * @return the color.
     */
    public int getARGB(float f0, float f1, float f2, float f3) {
        int i0 = _fbmi0.getByte(f0);
        int i1 = _fbmi1.getByte(f1);
        int i2 = _fbmi2.getByte(f2);
        int i3 = (_fbmi3 != null) ? _fbmi3.getByte(f3) : 0xff;
        return (_hsb) ? argbFromHsba(i0, i1, i2, i3) : argbFromRgba(i0, i1, i2, i3);
    }

    // Override
    /**
     * Gets the color index corresponding to the specified value.
     * @param v the value to be mapped to index.
     * @return the index in the range [0,255].
     */
    public int getIndex(double v) {
        return getIndex((float) v);
    }

    /**
     * Gets the minimum value in the range of mapped values.
     * @return the minimum value.
     */
    public double getMinValue() {
        return _fbmic.getClipMin();
    }

    /**
     * Gets the maximum value in the range of mapped values.
     * @return the maximum value.
     */
    public double getMaxValue() {
        return _fbmic.getClipMax();
    }

    /**
     * Sets the min-max range of values mapped to colors. Values outside this
     * range are clipped. The default range is the min and max clips in the
     * mapping from floats to bytes.
     * @param vmin the minimum value.
     * @param vmax the maximum value.
     */
    public void setValueRange(double vmin, double vmax) {
        if ((float) vmin != getMinValue() || (float) vmax != getMaxValue()) {
            _fbmic.setClips((float) vmin, (float) vmax);
            super.setValueRange(vmin, vmax);
        }
    }

    // private int nc; // number of color components: 1, 3, or 4.
    // private int _ic; // array index of component for index color model
    // the float-byte map for index color model
    private FloatByteMap _fbmic;

    private FloatByteMap _fbmi0;

    private FloatByteMap _fbmi1;

    private FloatByteMap _fbmi2;

    private FloatByteMap _fbmi3;

    // true if components are hue, sat, brightness
    private boolean _hsb;

    // corresponds to byte value 000
    private float _hue000;

    // corresponds to byte value 255
    private float _hue255;

    private int argbFromRgba(int r, int g, int b, int a) {
        return (a << 24) | (r << 16) | (g << 8) | b;
    }

    private int rgbFromRgb(int r, int g, int b) {
        return 0xff000000 | (r << 16) | (g << 8) | b;
    }

    private int argbFromHsba(int hu, int sa, int br, int al) {
        return (al << 24) | rgbFromHsb(hu, sa, br);
    }

    private int rgbFromHsb(int hu, int sa, int br) {
        float scale = 1.0f / 255.0f;
        if (hu < 0)
            hu += 256;
        if (sa < 0)
            sa += 256;
        if (br < 0)
            br += 256;
        float hue = _hue000 + (_hue255 - _hue000) * hu * scale;
        float sat = (float) sa * scale;
        float bri = (float) br * scale;
        int r = 0, g = 0, b = 0;
        if (sat == 0.0f) {
            r = g = b = (int) (bri * 255.0f + 0.5f);
        } else {
            float h = (hue - (float) floor(hue)) * 6.0f;
            float f = h - (float) floor(h);
            float p = bri * (1.0f - sat);
            float q = bri * (1.0f - sat * f);
            float t = bri * (1.0f - sat * (1.0f - f));
            switch((int) h) {
                case 0:
                    r = (int) (bri * 255.0f + 0.5f);
                    g = (int) (t * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 1:
                    r = (int) (q * 255.0f + 0.5f);
                    g = (int) (bri * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 2:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (bri * 255.0f + 0.5f);
                    b = (int) (t * 255.0f + 0.5f);
                    break;
                case 3:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (q * 255.0f + 0.5f);
                    b = (int) (bri * 255.0f + 0.5f);
                    break;
                case 4:
                    r = (int) (t * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (bri * 255.0f + 0.5f);
                    break;
                case 5:
                    r = (int) (bri * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (q * 255.0f + 0.5f);
                    break;
            }
        }
        return rgbFromRgb(r, g, b);
    }
}