void addSubProject(ProjectView subProject) {
        subProjects.add(subProject);
    }

package org.gradle.foundation;

import org.gradle.util.GUtil;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a
 * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.
 */
public class ProjectView implements Comparable<ProjectView>, Serializable {

    private final String name;

    private final ProjectView parentProject;

    // It is null for the root project.
    private final List<ProjectView> subProjects = new ArrayList<ProjectView>();

    private final List<TaskView> tasks = new ArrayList<TaskView>();

    private final List<ProjectView> dependsOnProjects = new ArrayList<ProjectView>();

    private final File buildFile;

    private final String description;

    /**
     * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.
     */
    ProjectView(ProjectView parentProject, String name, File buildFile, String description) {
        this.parentProject = parentProject;
        this.name = name;
        this.buildFile = buildFile;
        this.description = GUtil.elvis(description, "");
        if (parentProject != null) {
            parentProject.addSubProject(this);
        }
    }

    public String getName() {
        return name;
    }

    public File getBuildFile() {
        return buildFile;
    }

    public String getDescription() {
        return description;
    }

    public String toString() {
        return name;
    }

    public ProjectView getParentProject() {
        return parentProject;
    }

    public int compareTo(ProjectView otherProject) {
        return name.compareTo(otherProject.name);
    }

    /**
     * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */
    void createTask(String name, String description, boolean isDefault) {
        TaskView taskView = new TaskView(this, name, description, isDefault);
        tasks.add(taskView);
    }

    /**
     * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */

    /**
     * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */
    void setDependsOnProjects(List<ProjectView> newDependsOnProjects) {
        if (newDependsOnProjects == null) {
            return;
        }
        this.dependsOnProjects.clear();
        this.dependsOnProjects.addAll(newDependsOnProjects);
    }

    public List<ProjectView> getDependsOnProjects() {
        return dependsOnProjects;
    }

    public List<TaskView> getTasks() {
        return Collections.unmodifiableList(tasks);
    }

    public List<ProjectView> getSubProjects() {
        return Collections.unmodifiableList(subProjects);
    }

    public void sortSubProjectsAndTasks() {
        Collections.sort(tasks);
        Collections.sort(subProjects);
    }

    public ProjectView getSubProject(String name) {
        Iterator<ProjectView> iterator = subProjects.iterator();
        while (iterator.hasNext()) {
            ProjectView subProject = iterator.next();
            if (name.equals(subProject.getName())) {
                return subProject;
            }
        }
        return null;
    }

    public TaskView getTask(String name) {
        Iterator<TaskView> iterator = tasks.iterator();
        while (iterator.hasNext()) {
            TaskView task = iterator.next();
            if (name.equals(task.getName())) {
                return task;
            }
        }
        return null;
    }

    public ProjectView getSubProjectFromFullPath(String fullProjectName) {
        if (fullProjectName == null) {
            return null;
        }
        PathParserPortion portion = new PathParserPortion(fullProjectName);
        ProjectView subProject = getSubProject(portion.getFirstPart());
        if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).
        !portion.hasRemainder()) {
            return subProject;
        }
        if (subProject == null) {
            return null;
        }
        // the path may be invalid
        return subProject.getSubProjectFromFullPath(portion.getRemainder());
    }

    /**
     * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.
     *
     * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).
     * @return the task or null if not found.
     */
    public TaskView getTaskFromFullPath(String fullTaskName) {
        if (fullTaskName == null) {
            return null;
        }
        PathParserPortion portion = new PathParserPortion(fullTaskName);
        if (// if we have no remainder, then this is for a task.
        !portion.hasRemainder()) {
            return getTask(portion.getFirstPart());
        }
        ProjectView subProject = getSubProject(portion.getFirstPart());
        if (subProject == null) {
            return null;
        }
        // let the sub project figure it out.
        return subProject.getTaskFromFullPath(portion.getRemainder());
    }

    /**
     * This generates this project's full name. This is a colon-separated string of this project and its parent projects.
     *
     * Example: root_project:sub_project:sub_sub_project.
     */
    public String getFullProjectName() {
        ProjectView ancestorProject = getParentProject();
        if (ancestorProject == null) {
            return "";
        }
        // if we're the root, our full project name is nothing.
        StringBuilder builder = new StringBuilder(name);
        while (// we don't want to include the 'root' project
        ancestorProject != null && ancestorProject.getParentProject() != null) {
            builder.insert(0, ancestorProject.getName() + ':');
            ancestorProject = ancestorProject.getParentProject();
        }
        return builder.toString();
    }

    /**
     * Builds a list of default tasks. These are defined by specifying
     *
     * defaultTasks 'task name'
     *
     * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.
     *
     * @return a list of default tasks or an empty list if none exist
     */
    public List<TaskView> getDefaultTasks() {
        List<TaskView> defaultTasks = new ArrayList<TaskView>();
        Iterator<TaskView> taskIterator = tasks.iterator();
        while (taskIterator.hasNext()) {
            TaskView taskView = taskIterator.next();
            if (taskView.isDefault()) {
                defaultTasks.add(taskView);
            }
        }
        return defaultTasks;
    }
}


while (iterator.hasNext()) {
            ProjectView subProject = iterator.next();
            if (name.equals(subProject.getName())) {
                return subProject;
            }
        }

package org.gradle.foundation;

import org.gradle.util.GUtil;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a
 * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.
 */
public class ProjectView implements Comparable<ProjectView>, Serializable {

    private final String name;

    private final ProjectView parentProject;

    // It is null for the root project.
    private final List<ProjectView> subProjects = new ArrayList<ProjectView>();

    private final List<TaskView> tasks = new ArrayList<TaskView>();

    private final List<ProjectView> dependsOnProjects = new ArrayList<ProjectView>();

    private final File buildFile;

    private final String description;

    /**
     * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.
     */
    ProjectView(ProjectView parentProject, String name, File buildFile, String description) {
        this.parentProject = parentProject;
        this.name = name;
        this.buildFile = buildFile;
        this.description = GUtil.elvis(description, "");
        if (parentProject != null) {
            parentProject.addSubProject(this);
        }
    }

    public String getName() {
        return name;
    }

    public File getBuildFile() {
        return buildFile;
    }

    public String getDescription() {
        return description;
    }

    public String toString() {
        return name;
    }

    public ProjectView getParentProject() {
        return parentProject;
    }

    public int compareTo(ProjectView otherProject) {
        return name.compareTo(otherProject.name);
    }

    /**
     * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */
    void createTask(String name, String description, boolean isDefault) {
        TaskView taskView = new TaskView(this, name, description, isDefault);
        tasks.add(taskView);
    }

    /**
     * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */
    void addSubProject(ProjectView subProject) {
        subProjects.add(subProject);
    }

    /**
     * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.
     */
    void setDependsOnProjects(List<ProjectView> newDependsOnProjects) {
        if (newDependsOnProjects == null) {
            return;
        }
        this.dependsOnProjects.clear();
        this.dependsOnProjects.addAll(newDependsOnProjects);
    }

    public List<ProjectView> getDependsOnProjects() {
        return dependsOnProjects;
    }

    public List<TaskView> getTasks() {
        return Collections.unmodifiableList(tasks);
    }

    public List<ProjectView> getSubProjects() {
        return Collections.unmodifiableList(subProjects);
    }

    public void sortSubProjectsAndTasks() {
        Collections.sort(tasks);
        Collections.sort(subProjects);
    }

    public ProjectView getSubProject(String name) {
        Iterator<ProjectView> iterator = subProjects.iterator();

        return null;
    }

    public TaskView getTask(String name) {
        Iterator<TaskView> iterator = tasks.iterator();
        while (iterator.hasNext()) {
            TaskView task = iterator.next();
            if (name.equals(task.getName())) {
                return task;
            }
        }
        return null;
    }

    public ProjectView getSubProjectFromFullPath(String fullProjectName) {
        if (fullProjectName == null) {
            return null;
        }
        PathParserPortion portion = new PathParserPortion(fullProjectName);
        ProjectView subProject = getSubProject(portion.getFirstPart());
        if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).
        !portion.hasRemainder()) {
            return subProject;
        }
        if (subProject == null) {
            return null;
        }
        // the path may be invalid
        return subProject.getSubProjectFromFullPath(portion.getRemainder());
    }

    /**
     * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.
     *
     * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).
     * @return the task or null if not found.
     */
    public TaskView getTaskFromFullPath(String fullTaskName) {
        if (fullTaskName == null) {
            return null;
        }
        PathParserPortion portion = new PathParserPortion(fullTaskName);
        if (// if we have no remainder, then this is for a task.
        !portion.hasRemainder()) {
            return getTask(portion.getFirstPart());
        }
        ProjectView subProject = getSubProject(portion.getFirstPart());
        if (subProject == null) {
            return null;
        }
        // let the sub project figure it out.
        return subProject.getTaskFromFullPath(portion.getRemainder());
    }

    /**
     * This generates this project's full name. This is a colon-separated string of this project and its parent projects.
     *
     * Example: root_project:sub_project:sub_sub_project.
     */
    public String getFullProjectName() {
        ProjectView ancestorProject = getParentProject();
        if (ancestorProject == null) {
            return "";
        }
        // if we're the root, our full project name is nothing.
        StringBuilder builder = new StringBuilder(name);
        while (// we don't want to include the 'root' project
        ancestorProject != null && ancestorProject.getParentProject() != null) {
            builder.insert(0, ancestorProject.getName() + ':');
            ancestorProject = ancestorProject.getParentProject();
        }
        return builder.toString();
    }

    /**
     * Builds a list of default tasks. These are defined by specifying
     *
     * defaultTasks 'task name'
     *
     * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.
     *
     * @return a list of default tasks or an empty list if none exist
     */
    public List<TaskView> getDefaultTasks() {
        List<TaskView> defaultTasks = new ArrayList<TaskView>();
        Iterator<TaskView> taskIterator = tasks.iterator();
        while (taskIterator.hasNext()) {
            TaskView taskView = taskIterator.next();
            if (taskView.isDefault()) {
                defaultTasks.add(taskView);
            }
        }
        return defaultTasks;
    }
}


public int getWidth(int imageIndex) throws IOException

package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;
        try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }
    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];
        for (int i = 0; i < nc; i++) {
            r[i] = data[i * 3];
            g[i] = data[i * 3 + 1];
            b[i] = data[i * 3 + 2];
        }
        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(input);
    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException {
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

{
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */
    public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


{
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;
        try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }
    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];
        for (int i = 0; i < nc; i++) {
            r[i] = data[i * 3];
            g[i] = data[i * 3 + 1];
            b[i] = data[i * 3 + 2];
        }
        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(input);
    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException

    public int getWidth(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */
    public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;
        try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }
    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];
        for (int i = 0; i < nc; i++) {
            r[i] = data[i * 3];
            g[i] = data[i * 3 + 1];
            b[i] = data[i * 3 + 2];
        }
        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(i

    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException {
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

    public int getWidth(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */
    public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;
        try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }
    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];
        for (int i = 0; i < nc; i++) {
            r[i] = data[i * 3];
            g[i] = data[i * 3 + 1];
            b[i] = data[i * 3 + 2];
        }
        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(input);
    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException {
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

    public int getWidth(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;
        try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }
    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];

        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(input);
    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException {
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

    public int getWidth(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */
    public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


try {
            if (input instanceof InputStream)
                file = new GIFFile((InputStream) input);
            else
                file = new GIFFile(new IIOInputStream((ImageInputStream) input));
        } catch (GIFFile.GIFException ge) {
            throw new IIOException(ge.getMessage());
        }

package gnu.javax.imageio.gif;

import gnu.javax.imageio.IIOInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.*;
import javax.imageio.spi.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageInputStream;
import java.util.Iterator;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class GIFImageReader extends ImageReader {

    private GIFFile file;

    protected GIFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
        file = null;
    }

    private void readImage() throws IOException {
        if (file != null)
            return;

    }

    /**
     * Returns the Global/Local palette as an IndexColorModel
     */
    private IndexColorModel getPalette(int index) {
        GIFFile f = file.getImage(index);
        byte[] data = f.getRawPalette();
        int nc = f.getNColors();
        byte[] r = new byte[nc];
        byte[] g = new byte[nc];
        byte[] b = new byte[nc];
        for (int i = 0; i < nc; i++) {
            r[i] = data[i * 3];
            g[i] = data[i * 3 + 1];
            b[i] = data[i * 3 + 2];
        }
        if (f.hasTransparency()) {
            byte[] a = new byte[nc];
            for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;
            a[f.getTransparentIndex()] = 0;
            return new IndexColorModel(8, nc, r, g, b, a);
        }
        return new IndexColorModel(8, nc, r, g, b);
    }

    private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {
        if (imageIndex < 0 || imageIndex >= getNumImages(false))
            throw new IndexOutOfBoundsException("Invalid image index.");
    }

    public void setInput(Object input) {
        super.setInput(input);
    }

    public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
    }

    public void setInput(Object input, boolean isStreamable) {
        super.setInput(input, isStreamable);
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalArgumentException("Input not an ImageInputStream.");
    }

    private void checkStream() throws IOException {
        if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))
            throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
        if (input == null)
            throw new IllegalStateException("No input stream.");
    }

    public int getWidth(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        validateIndex(imageIndex);
        return file.getImage(imageIndex).getHeight();
    }

    public Iterator getImageTypes(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    /**
     * Returns the number of images.
     */
    public int getNumImages(boolean allowSearch) {
        try // Image should be loaded here already. But just in case:
        {
            readImage();
        } catch (IOException ioe) {
            // Well, now we're in trouble. But return something anyway.
            return 0;
        }
        return file.nImages();
    }

    // FIXME: Support metadata
    public IIOMetadata getImageMetadata(int imageIndex) {
        validateIndex(imageIndex);
        return null;
    }

    // FIXME: Support metadata
    public IIOMetadata getStreamMetadata() {
        return null;
    }

    /**
     * Reads the image indexed by imageIndex and returns it as
     * a complete BufferedImage, using a supplied ImageReadParam.
     */
    public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {
        validateIndex(imageIndex);
        GIFFile f = file.getImage(imageIndex);
        int width = f.getWidth();
        int height = f.getHeight();
        SampleModel sm;
        switch(f.getNColors()) {
            case 16:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);
                break;
            case 4:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);
                break;
            case 2:
                sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);
                break;
            default:
                sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });
                break;
        }
        DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        return new BufferedImage(getPalette(imageIndex), raster, false, null);
    }
}


private static Supplier<IllegalStateException> missingPropertyISE(String propertyName)

/*
 * SonarQube
 * mailto:info AT sonarsource DOT com
 *
 */
package org.sonar.server.health;

import java.util.function.Supplier;
import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.process.NetworkUtils;
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
import org.sonar.process.cluster.health.NodeHealthProvider;
import static java.lang.String.format;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;
import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;

public class NodeHealthProviderImpl implements NodeHealthProvider {

    private final HealthChecker healthChecker;

    private final NodeHealth.Builder nodeHealthBuilder;

    private final NodeDetails nodeDetails;

    public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {
        this.healthChecker = healthChecker;
        this.nodeHealthBuilder = newNodeHealthBuilder();
        this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();
    }

    private static String computeName(Configuration configuration) {
        return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));
    }

    private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {
        return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);
    }

    private static int computePort(Configuration configuration) {
        return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));
    }

{
        return () -> new IllegalStateException(format("Property %s is not defined", propertyName));
    }

    @Override
    public NodeHealth get() {
        Health nodeHealth = healthChecker.checkNode();
        this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));
        nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);
        return this.nodeHealthBuilder.setDetails(nodeDetails).build();
    }
}


{
        return () -> new IllegalStateException(format("Property %s is not defined", propertyName));
    }

/*
 * SonarQube
 * mailto:info AT sonarsource DOT com
 *
 */
package org.sonar.server.health;

import java.util.function.Supplier;
import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.process.NetworkUtils;
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
import org.sonar.process.cluster.health.NodeHealthProvider;
import static java.lang.String.format;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;
import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;

public class NodeHealthProviderImpl implements NodeHealthProvider {

    private final HealthChecker healthChecker;

    private final NodeHealth.Builder nodeHealthBuilder;

    private final NodeDetails nodeDetails;

    public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {
        this.healthChecker = healthChecker;
        this.nodeHealthBuilder = newNodeHealthBuilder();
        this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();
    }

    private static String computeName(Configuration configuration) {
        return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));
    }

    private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {
        return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);
    }

    private static int computePort(Configuration configuration) {
        return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));
    }

    private static Supplier<IllegalStateException> missingPropertyISE(String propertyName)

    @Override
    public NodeHealth get() {
        Health nodeHealth = healthChecker.checkNode();
        this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));
        nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);
        return this.nodeHealthBuilder.setDetails(nodeDetails).build();
    }
}


/*
 * SonarQube
 * mailto:info AT sonarsource DOT com
 *
 */
package org.sonar.server.health;

import java.util.function.Supplier;
import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.process.NetworkUtils;
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
import org.sonar.process.cluster.health.NodeHealthProvider;
import static java.lang.String.format;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;
import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;

public class NodeHealthProviderImpl implements NodeHealthProvider {

    private final HealthChecker healthChecker;

    private final NodeHealth.Builder nodeHealthBuilder;

    private final NodeDetails nodeDetails;

    public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {
        this.healthChecker = healthChecker;
        this.nodeHealthBuilder = newNodeHealthBuilder();
        this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();
    }

    private static String computeName(Configuration configuration) {
        return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));
    }

    private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {
        return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);
    }

    private static int computePort(Configuration configuration) {
        return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));
    }

    private static Supplier<IllegalStateException> missingPropertyISE(String propertyName) {
        return () -> new IllegalStateException(format("Property %s is not defined", propertyName));
    }

    @Override
    public NodeHealth get() {
        Health

        this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));
        nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);
        return this.nodeHealthBuilder.setDetails(nodeDetails).build();
    }
}


public String predict(Annotation annotation, int sentId, int startToken, int endToken)

package edu.washington.cs.figer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.StringUtils;
import edu.washington.cs.figer.analysis.MapType;
import edu.washington.cs.figer.analysis.Preprocessing;
import edu.washington.cs.figer.analysis.feature.NERFeature;
import edu.washington.cs.figer.data.EntityProtos.Mention;
import edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;
import edu.washington.cs.figer.data.Feature;
import edu.washington.cs.figer.data.FeatureFactory;
import edu.washington.cs.figer.data.Instance;
import edu.washington.cs.figer.ml.Model;
import edu.washington.cs.figer.ml.MultiLabelLogisticRegression;
import edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;
import edu.washington.cs.figer.ml.NERClassifier;
import edu.washington.cs.figer.util.FileUtil;
import edu.washington.cs.figer.util.StanfordDependencyResolver;
import edu.washington.cs.figer.util.Timer;
import edu.washington.cs.figer.util.X;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;

public class FigerSystem {

    private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);

    private static FigerSystem instance = null;

    public static String configFile = "config/figer.conf";

    // useful variables
    public Model model = new MultiLabelLogisticRegression();

    public NERClassifier classifier = null;

    public NERFeature nerFeature = null;

    // debug variables
    public static HashSet<String> mentions = new HashSet<String>();

    public synchronized static FigerSystem instance() {
        if (instance == null) {
            instance = new FigerSystem();
        }
        return instance;
    }

    private FigerSystem() {
        X.parseArgs(configFile);
        Timer timer = new Timer();
        model.debug = X.getBoolean("debugModel");
        // read all tags
        MapType.typeFile = X.tagset;
        MapType.init();
        for (String newType : MapType.mapping.values()) {
            model.labelFactory.getLabel(newType);
        }
        logger.info("labels:\t" + model.labelFactory.allLabels);
        // read the model
        if (X.methodS == X.PERCEPTRON) {
            timer.task = "reading the model " + X.modelFile;
            timer.start();
            model.readModel(X.modelFile);
            model.featureFactory.isTrain = false;
            model.labelFactory.isTrain = false;
            timer.endPrint();
            // init NER Features
            nerFeature = new NERFeature(model);
            nerFeature.init();
            MultiLabelLogisticRegression.prob_threshold = X.getDouble("prob_threshold");
            classifier = new MultiLabelPerceptronNERClassifier(model.infer);
        }
    }

{
        Mention m = buildMention(annotation, sentId, startToken, endToken);
        // features
        ArrayList<String> features = new ArrayList<String>();
        nerFeature.extract(m, features);
        return predict(features);
    }

    public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {
        CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);
        List<CoreLabel> tokens = sentAnn.get(TokensAnnotation.class);
        // create a Mention object
        Mention.Builder m = Mention.newBuilder();
        m.setStart(startToken);
        m.setEnd(endToken);
        for (int i = 0; i < tokens.size(); i++) {
            m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));
            m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));
        }
        m.setEntityName("");
        m.setFileid("on-the-fly");
        m.setSentid(sentId);
        // dependency
        String depStr = StanfordDependencyResolver.getString(sentAnn);
        if (depStr != null) {
            for (String d : depStr.split("\t")) {
                Matcher match = Preprocessing.depPattern.matcher(d);
                if (match.find()) {
                    m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());
                } else {
                }
            }
        }
        return m.build();
    }

    public String predict(List<String> features) {
        try {
            Instance inst = (Instance) X.instanceClass.newInstance();
            for (String fea : features) {
                Feature f = model.featureFactory.getFeature(fea);
                FeatureFactory.setValue(inst, f, fea);
            }
            Hashtable<TIntList, String> pool = new Hashtable<TIntList, String>();
            TIntList entity = new TIntArrayList();
            classifier.predict(inst, pool, entity, model);
            String plabels = pool.get(entity);
            return plabels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // only use the following tag set to find named entities
    private static final Set<String> validTags = new HashSet<String>(Arrays.asList(new String[] { "PERSON", "ORGANIZATION", "LOCATION", "MISC", "O" }));

    public static List<Pair<Integer, Integer>> getNamedEntityMentions(CoreMap sentence) {
        List<Pair<Integer, Integer>> offsets = new ArrayList<Pair<Integer, Integer>>();
        String prevTag = "O";
        int tid = 0;
        int start = -1;
        for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
            String tag = token.get(NamedEntityTagAnnotation.class);
            if (!validTags.contains(tag)) {
                tag = "O";
            }
            if (tag.equals(prevTag)) {
            } else {
                if (tag.equals("O")) {
                    offsets.add(Pair.makePair(start, tid));
                    start = -1;
                } else {
                    if (prevTag.equals("O")) {
                        start = tid;
                    } else {
                        offsets.add(Pair.makePair(start, tid));
                        start = tid;
                    }
                }
            }
            prevTag = tag;
            tid++;
        }
        if (!prevTag.equals("O")) {
            offsets.add(Pair.makePair(start, tid));
        }
        return offsets;
    }

    private static void usage() {
        System.out.println("sbt \"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\"");
        System.out.println("    [config_file] is optional with a default value \"config/figer.conf\"");
    }

    public static void main(String[] args) {
        String textFile = null;
        if (args.length == 1) {
            textFile = args[0];
        } else if (args.length == 2) {
            configFile = args[0];
            textFile = args[1];
        } else {
            usage();
            System.exit(0);
        }
        // initialize the system
        FigerSystem sys = instance();
        Preprocessing.initPipeline();
        // preprocess the text
        List<String> list = FileUtil.getLinesFromFile(textFile);
        for (int i = 0; i < list.size(); i++) {
            Annotation annotation = new Annotation(list.get(i));
            Preprocessing.pipeline.annotate(annotation);
            // for each sentence
            int sentId = 0;
            for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {
                System.out.println("[l" + i + "][s" + sentId + "]tokenized sentence=" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));
                List<Pair<Integer, Integer>> entityMentionOffsets = getNamedEntityMentions(sentence);
                for (Pair<Integer, Integer> offset : entityMentionOffsets) {
                    String label = sys.predict(annotation, sentId, offset.first, offset.second);
                    String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));
                    System.out.println("[l" + i + "][s" + sentId + "]mention" + mention + "(" + offset.first + "," + offset.second + ") = " + mention + ", pred = " + label);
                }
                sentId++;
            }
        }
    }
}


{
        if (instance == null) {
            instance = new FigerSystem();
        }
        return instance;
    }

package edu.washington.cs.figer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.StringUtils;
import edu.washington.cs.figer.analysis.MapType;
import edu.washington.cs.figer.analysis.Preprocessing;
import edu.washington.cs.figer.analysis.feature.NERFeature;
import edu.washington.cs.figer.data.EntityProtos.Mention;
import edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;
import edu.washington.cs.figer.data.Feature;
import edu.washington.cs.figer.data.FeatureFactory;
import edu.washington.cs.figer.data.Instance;
import edu.washington.cs.figer.ml.Model;
import edu.washington.cs.figer.ml.MultiLabelLogisticRegression;
import edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;
import edu.washington.cs.figer.ml.NERClassifier;
import edu.washington.cs.figer.util.FileUtil;
import edu.washington.cs.figer.util.StanfordDependencyResolver;
import edu.washington.cs.figer.util.Timer;
import edu.washington.cs.figer.util.X;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;

public class FigerSystem {

    private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);

    private static FigerSystem instance = null;

    public static String configFile = "config/figer.conf";

    // useful variables
    public Model model = new MultiLabelLogisticRegression();

    public NERClassifier classifier = null;

    public NERFeature nerFeature = null;

    // debug variables
    public static HashSet<String> mentions = new HashSet<String>();

    public synchronized static FigerSystem instance()

    private FigerSystem() {
        X.parseArgs(configFile);
        Timer timer = new Timer();
        model.debug = X.getBoolean("debugModel");
        // read all tags
        MapType.typeFile = X.tagset;
        MapType.init();
        for (String newType : MapType.mapping.values()) {
            model.labelFactory.getLabel(newType);
        }
        logger.info("labels:\t" + model.labelFactory.allLabels);
        // read the model
        if (X.methodS == X.PERCEPTRON) {
            timer.task = "reading the model " + X.modelFile;
            timer.start();
            model.readModel(X.modelFile);
            model.featureFactory.isTrain = false;
            model.labelFactory.isTrain = false;
            timer.endPrint();
            // init NER Features
            nerFeature = new NERFeature(model);
            nerFeature.init();
            MultiLabelLogisticRegression.prob_threshold = X.getDouble("prob_threshold");
            classifier = new MultiLabelPerceptronNERClassifier(model.infer);
        }
    }

    public String predict(Annotation annotation, int sentId, int startToken, int endToken) {
        Mention m = buildMention(annotation, sentId, startToken, endToken);
        // features
        ArrayList<String> features = new ArrayList<String>();
        nerFeature.extract(m, features);
        return predict(features);
    }

    public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {
        CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);
        List<CoreLabel> tokens = sentAnn.get(TokensAnnotation.class);
        // create a Mention object
        Mention.Builder m = Mention.newBuilder();
        m.setStart(startToken);
        m.setEnd(endToken);
        for (int i = 0; i < tokens.size(); i++) {
            m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));
            m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));
        }
        m.setEntityName("");
        m.setFileid("on-the-fly");
        m.setSentid(sentId);
        // dependency
        String depStr = StanfordDependencyResolver.getString(sentAnn);
        if (depStr != null) {
            for (String d : depStr.split("\t")) {
                Matcher match = Preprocessing.depPattern.matcher(d);
                if (match.find()) {
                    m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());
                } else {
                }
            }
        }
        return m.build();
    }

    public String predict(List<String> features) {
        try {
            Instance inst = (Instance) X.instanceClass.newInstance();
            for (String fea : features) {
                Feature f = model.featureFactory.getFeature(fea);
                FeatureFactory.setValue(inst, f, fea);
            }
            Hashtable<TIntList, String> pool = new Hashtable<TIntList, String>();
            TIntList entity = new TIntArrayList();
            classifier.predict(inst, pool, entity, model);
            String plabels = pool.get(entity);
            return plabels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // only use the following tag set to find named entities
    private static final Set<String> validTags = new HashSet<String>(Arrays.asList(new String[] { "PERSON", "ORGANIZATION", "LOCATION", "MISC", "O" }));

    public static List<Pair<Integer, Integer>> getNamedEntityMentions(CoreMap sentence) {
        List<Pair<Integer, Integer>> offsets = new ArrayList<Pair<Integer, Integer>>();
        String prevTag = "O";
        int tid = 0;
        int start = -1;
        for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
            String tag = token.get(NamedEntityTagAnnotation.class);
            if (!validTags.contains(tag)) {
                tag = "O";
            }
            if (tag.equals(prevTag)) {
            } else {
                if (tag.equals("O")) {
                    offsets.add(Pair.makePair(start, tid));
                    start = -1;
                } else {
                    if (prevTag.equals("O")) {
                        start = tid;
                    } else {
                        offsets.add(Pair.makePair(start, tid));
                        start = tid;
                    }
                }
            }
            prevTag = tag;
            tid++;
        }
        if (!prevTag.equals("O")) {
            offsets.add(Pair.makePair(start, tid));
        }
        return offsets;
    }

    private static void usage() {
        System.out.println("sbt \"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\"");
        System.out.println("    [config_file] is optional with a default value \"config/figer.conf\"");
    }

    public static void main(String[] args) {
        String textFile = null;
        if (args.length == 1) {
            textFile = args[0];
        } else if (args.length == 2) {
            configFile = args[0];
            textFile = args[1];
        } else {
            usage();
            System.exit(0);
        }
        // initialize the system
        FigerSystem sys = instance();
        Preprocessing.initPipeline();
        // preprocess the text
        List<String> list = FileUtil.getLinesFromFile(textFile);
        for (int i = 0; i < list.size(); i++) {
            Annotation annotation = new Annotation(list.get(i));
            Preprocessing.pipeline.annotate(annotation);
            // for each sentence
            int sentId = 0;
            for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {
                System.out.println("[l" + i + "][s" + sentId + "]tokenized sentence=" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));
                List<Pair<Integer, Integer>> entityMentionOffsets = getNamedEntityMentions(sentence);
                for (Pair<Integer, Integer> offset : entityMentionOffsets) {
                    String label = sys.predict(annotation, sentId, offset.first, offset.second);
                    String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));
                    System.out.println("[l" + i + "][s" + sentId + "]mention" + mention + "(" + offset.first + "," + offset.second + ") = " + mention + ", pred = " + label);
                }
                sentId++;
            }
        }
    }
}


package edu.washington.cs.figer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.StringUtils;
import edu.washington.cs.figer.analysis.MapType;
import edu.washington.cs.figer.analysis.Preprocessing;
import edu.washington.cs.figer.analysis.feature.NERFeature;
import edu.washington.cs.figer.data.EntityProtos.Mention;
import edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;
import edu.washington.cs.figer.data.Feature;
import edu.washington.cs.figer.data.FeatureFactory;
import edu.washington.cs.figer.data.Instance;
import edu.washington.cs.figer.ml.Model;
import edu.washington.cs.figer.ml.MultiLabelLogisticRegression;
import edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;
import edu.washington.cs.figer.ml.NERClassifier;
import edu.washington.cs.figer.util.FileUtil;
import edu.washington.cs.figer.util.StanfordDependencyResolver;
import edu.washington.cs.figer.util.Timer;
import edu.washington.cs.figer.util.X;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;

public class FigerSystem {

    private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);

    private static FigerSystem instance = null;

    public static String configFile = "config/figer.conf";

    // useful variables
    public Model model = new MultiLabelLogisticRegression();

    public NERClassifier classifier = null;

    public NERFeature nerFeature = null;

    // debug variables
    public static HashSet<String> mentions = new HashSet<String>();

    public synchronized static FigerSystem instance() {
        if (instance == null) {
            instance = new FigerSystem();
        }
        return instance;
    }

    private FigerSystem() {
        X.parseArgs(configFile);
        Timer timer = new Timer();
        model.debug = X.getBoolean("debugModel");
        // read all tags
        MapType.typeFile = X.tagset;
        MapType.init();
        for (String newType : MapType.mapping.values()) {
            model.labelFactory.getLabel(newType);
        }
        logger.info("labels:\t" + model.labelFactory.allLabels);
        // read the model
        if (X.methodS == X.PERCEPTRON) {
            timer.task = "reading the model " + X.modelFile;
            timer.start();
            model.readModel(X.modelFile);
            model.featureFactory.isTrain = false;
            model.labelFactory.isTrain = false;
            timer.endPrint();
            // init NER Features
            nerFeature = new NERFeature(model);
            nerFeature.init();
            MultiLabelLogisticRegression.prob_threshold = X.getDouble("prob_threshold");
            classifier = new MultiLabelPerceptronNERClassifier(model.infer);
        }
    }

    public String predict(Annotation annotation, int sentId, int startToken, int endToken) {
        Mention m = buildMention(annotation, sentId, startToken, en

        // features
        ArrayList<String> features = new ArrayList<String>();
        nerFeature.extract(m, features);
        return predict(features);
    }

    public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {
        CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);
        List<CoreLabel> tokens = sentAnn.get(TokensAnnotation.class);
        // create a Mention object
        Mention.Builder m = Mention.newBuilder();
        m.setStart(startToken);
        m.setEnd(endToken);
        for (int i = 0; i < tokens.size(); i++) {
            m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));
            m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));
        }
        m.setEntityName("");
        m.setFileid("on-the-fly");
        m.setSentid(sentId);
        // dependency
        String depStr = StanfordDependencyResolver.getString(sentAnn);
        if (depStr != null) {
            for (String d : depStr.split("\t")) {
                Matcher match = Preprocessing.depPattern.matcher(d);
                if (match.find()) {
                    m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());
                } else {
                }
            }
        }
        return m.build();
    }

    public String predict(List<String> features) {
        try {
            Instance inst = (Instance) X.instanceClass.newInstance();
            for (String fea : features) {
                Feature f = model.featureFactory.getFeature(fea);
                FeatureFactory.setValue(inst, f, fea);
            }
            Hashtable<TIntList, String> pool = new Hashtable<TIntList, String>();
            TIntList entity = new TIntArrayList();
            classifier.predict(inst, pool, entity, model);
            String plabels = pool.get(entity);
            return plabels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // only use the following tag set to find named entities
    private static final Set<String> validTags = new HashSet<String>(Arrays.asList(new String[] { "PERSON", "ORGANIZATION", "LOCATION", "MISC", "O" }));

    public static List<Pair<Integer, Integer>> getNamedEntityMentions(CoreMap sentence) {
        List<Pair<Integer, Integer>> offsets = new ArrayList<Pair<Integer, Integer>>();
        String prevTag = "O";
        int tid = 0;
        int start = -1;
        for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
            String tag = token.get(NamedEntityTagAnnotation.class);
            if (!validTags.contains(tag)) {
                tag = "O";
            }
            if (tag.equals(prevTag)) {
            } else {
                if (tag.equals("O")) {
                    offsets.add(Pair.makePair(start, tid));
                    start = -1;
                } else {
                    if (prevTag.equals("O")) {
                        start = tid;
                    } else {
                        offsets.add(Pair.makePair(start, tid));
                        start = tid;
                    }
                }
            }
            prevTag = tag;
            tid++;
        }
        if (!prevTag.equals("O")) {
            offsets.add(Pair.makePair(start, tid));
        }
        return offsets;
    }

    private static void usage() {
        System.out.println("sbt \"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\"");
        System.out.println("    [config_file] is optional with a default value \"config/figer.conf\"");
    }

    public static void main(String[] args) {
        String textFile = null;
        if (args.length == 1) {
            textFile = args[0];
        } else if (args.length == 2) {
            configFile = args[0];
            textFile = args[1];
        } else {
            usage();
            System.exit(0);
        }
        // initialize the system
        FigerSystem sys = instance();
        Preprocessing.initPipeline();
        // preprocess the text
        List<String> list = FileUtil.getLinesFromFile(textFile);
        for (int i = 0; i < list.size(); i++) {
            Annotation annotation = new Annotation(list.get(i));
            Preprocessing.pipeline.annotate(annotation);
            // for each sentence
            int sentId = 0;
            for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {
                System.out.println("[l" + i + "][s" + sentId + "]tokenized sentence=" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));
                List<Pair<Integer, Integer>> entityMentionOffsets = getNamedEntityMentions(sentence);
                for (Pair<Integer, Integer> offset : entityMentionOffsets) {
                    String label = sys.predict(annotation, sentId, offset.first, offset.second);
                    String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));
                    System.out.println("[l" + i + "][s" + sentId + "]mention" + mention + "(" + offset.first + "," + offset.second + ") = " + mention + ", pred = " + label);
                }
                sentId++;
            }
        }
    }
}


for (int i = 0; i < tokens.size(); i++) {
            m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));
            m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));
        }

package edu.washington.cs.figer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.StringUtils;
import edu.washington.cs.figer.analysis.MapType;
import edu.washington.cs.figer.analysis.Preprocessing;
import edu.washington.cs.figer.analysis.feature.NERFeature;
import edu.washington.cs.figer.data.EntityProtos.Mention;
import edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;
import edu.washington.cs.figer.data.Feature;
import edu.washington.cs.figer.data.FeatureFactory;
import edu.washington.cs.figer.data.Instance;
import edu.washington.cs.figer.ml.Model;
import edu.washington.cs.figer.ml.MultiLabelLogisticRegression;
import edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;
import edu.washington.cs.figer.ml.NERClassifier;
import edu.washington.cs.figer.util.FileUtil;
import edu.washington.cs.figer.util.StanfordDependencyResolver;
import edu.washington.cs.figer.util.Timer;
import edu.washington.cs.figer.util.X;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;

public class FigerSystem {

    private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);

    private static FigerSystem instance = null;

    public static String configFile = "config/figer.conf";

    // useful variables
    public Model model = new MultiLabelLogisticRegression();

    public NERClassifier classifier = null;

    public NERFeature nerFeature = null;

    // debug variables
    public static HashSet<String> mentions = new HashSet<String>();

    public synchronized static FigerSystem instance() {
        if (instance == null) {
            instance = new FigerSystem();
        }
        return instance;
    }

    private FigerSystem() {
        X.parseArgs(configFile);
        Timer timer = new Timer();
        model.debug = X.getBoolean("debugModel");
        // read all tags
        MapType.typeFile = X.tagset;
        MapType.init();
        for (String newType : MapType.mapping.values()) {
            model.labelFactory.getLabel(newType);
        }
        logger.info("labels:\t" + model.labelFactory.allLabels);
        // read the model
        if (X.methodS == X.PERCEPTRON) {
            timer.task = "reading the model " + X.modelFile;
            timer.start();
            model.readModel(X.modelFile);
            model.featureFactory.isTrain = false;
            model.labelFactory.isTrain = false;
            timer.endPrint();
            // init NER Features
            nerFeature = new NERFeature(model);
            nerFeature.init();
            MultiLabelLogisticRegression.prob_threshold = X.getDouble("prob_threshold");
            classifier = new MultiLabelPerceptronNERClassifier(model.infer);
        }
    }

    public String predict(Annotation annotation, int sentId, int startToken, int endToken) {
        Mention m = buildMention(annotation, sentId, startToken, endToken);
        // features
        ArrayList<String> features = new ArrayList<String>();
        nerFeature.extract(m, features);
        return predict(features);
    }

    public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {
        CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);
        List<CoreLabel> tokens = sentAnn.get(TokensAnnotation.class);
        // create a Mention object
        Mention.Builder m = Mention.newBuilder();
        m.setStart(startToken);
        m.setEnd(endToken);

        m.setEntityName("");
        m.setFileid("on-the-fly");
        m.setSentid(sentId);
        // dependency
        String depStr = StanfordDependencyResolver.getString(sentAnn);
        if (depStr != null) {
            for (String d : depStr.split("\t")) {
                Matcher match = Preprocessing.depPattern.matcher(d);
                if (match.find()) {
                    m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());
                } else {
                }
            }
        }
        return m.build();
    }

    public String predict(List<String> features) {
        try {
            Instance inst = (Instance) X.instanceClass.newInstance();
            for (String fea : features) {
                Feature f = model.featureFactory.getFeature(fea);
                FeatureFactory.setValue(inst, f, fea);
            }
            Hashtable<TIntList, String> pool = new Hashtable<TIntList, String>();
            TIntList entity = new TIntArrayList();
            classifier.predict(inst, pool, entity, model);
            String plabels = pool.get(entity);
            return plabels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // only use the following tag set to find named entities
    private static final Set<String> validTags = new HashSet<String>(Arrays.asList(new String[] { "PERSON", "ORGANIZATION", "LOCATION", "MISC", "O" }));

    public static List<Pair<Integer, Integer>> getNamedEntityMentions(CoreMap sentence) {
        List<Pair<Integer, Integer>> offsets = new ArrayList<Pair<Integer, Integer>>();
        String prevTag = "O";
        int tid = 0;
        int start = -1;
        for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
            String tag = token.get(NamedEntityTagAnnotation.class);
            if (!validTags.contains(tag)) {
                tag = "O";
            }
            if (tag.equals(prevTag)) {
            } else {
                if (tag.equals("O")) {
                    offsets.add(Pair.makePair(start, tid));
                    start = -1;
                } else {
                    if (prevTag.equals("O")) {
                        start = tid;
                    } else {
                        offsets.add(Pair.makePair(start, tid));
                        start = tid;
                    }
                }
            }
            prevTag = tag;
            tid++;
        }
        if (!prevTag.equals("O")) {
            offsets.add(Pair.makePair(start, tid));
        }
        return offsets;
    }

    private static void usage() {
        System.out.println("sbt \"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\"");
        System.out.println("    [config_file] is optional with a default value \"config/figer.conf\"");
    }

    public static void main(String[] args) {
        String textFile = null;
        if (args.length == 1) {
            textFile = args[0];
        } else if (args.length == 2) {
            configFile = args[0];
            textFile = args[1];
        } else {
            usage();
            System.exit(0);
        }
        // initialize the system
        FigerSystem sys = instance();
        Preprocessing.initPipeline();
        // preprocess the text
        List<String> list = FileUtil.getLinesFromFile(textFile);
        for (int i = 0; i < list.size(); i++) {
            Annotation annotation = new Annotation(list.get(i));
            Preprocessing.pipeline.annotate(annotation);
            // for each sentence
            int sentId = 0;
            for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {
                System.out.println("[l" + i + "][s" + sentId + "]tokenized sentence=" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));
                List<Pair<Integer, Integer>> entityMentionOffsets = getNamedEntityMentions(sentence);
                for (Pair<Integer, Integer> offset : entityMentionOffsets) {
                    String label = sys.predict(annotation, sentId, offset.first, offset.second);
                    String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));
                    System.out.println("[l" + i + "][s" + sentId + "]mention" + mention + "(" + offset.first + "," + offset.second + ") = " + mention + ", pred = " + label);
                }
                sentId++;
            }
        }
    }
}