text:
**Warning:** Pipelines should be optimized to an image test-set before running a whole data-set.
See Pipeline Tutorial [here](vis_tutorial.md) or [here](vis_nir_tutorial.md).
Our image download tool, which talks to a LemnaTec database system can be found [here](https://github.com/danforthcenter/pheno-data-service).
Our download tool has a specific file structure, which may be different than yours unless you are using our tool, but we also have instructions
to run PlantCV over a flat file directory (just keep this in mind).

### Running PlantCV over PhenoFront image data-set structure

We normally execute pipelines in a shell script or in in a condor job file (or dagman workflow if running multiple pipelines into one sqlite database)

* First call the plantcv-pipeline.py script that does the parallelization
* -d is the --directory of images
* -p is the --pipeline that you are going to run over the images see [VIS tutorial here](vis_tutorial.md) and [PSII tutorial here](psII_tutorial.md)
* -i is the --outdir your desired location for the output images
* -a is the --adaptor to indicate structure to grab the metadata from, either 'filename' or the default, which is 'phenofront' (lemnatec structured output)
* -t is the --type extension 'png' is the default or 'jpg'
* -l is the --deliminator for the filename, default is "_"
* -C is the --coprocess Coprocess the specified imgtype with the imgtype specified in --match (e.g. coprocess NIR images with VIS).
* -f is the --meta (data) format map for example the default is "imgtype_camera_frame_zoom_id"
* -M is the --match metadata option, for example to select a certain zoom or angle. For example: 'imgtype:VIS,camera:SV,zoom:z500'
* -D is the --dates" option, to select a certain date range of data. YYYY-MM-DD-hh-mm-ss_YYYY-MM-DD-hh-mm-ss. If the second date is excluded then the current date is assumed.
* -s is the --db, sqlite database name
* -m is the --mask any image mask that you would like to provide
* -T is the --threads (cpus) you would like to use.
* -w is the --writeimg option, if True will write output images. default= False
* -c is the --create option to overwrite an sqlite database if it exists, if you are creating a new database or appending to database, do NOT add the -c flag
* -o is the --other_args option, used to pass non-standard options to the pipeline script. Must take the form `--other_args="--option1 value1 --option2 value2"`

####If running as a command in a shell script

```bash
#!/bin/bash

#Here we are running a VIS top-view pipeline

time \
/home/nfahlgren/programs/plantcv/plantcv-pipeline.py \
-d /home/nfahlgren/projects/lemnatec/burnin2/images3 \
-p /home/nfahlgren/programs/plantcv/scripts/image_analysis/vis_tv/vis_tv_z300_L1.py \
-t png \
-s burnin2.sqlite3 \
-i /home/nfahlgren/projects/lemnatec/burnin2/plantcv3/images \
-m /home/nfahlgren/programs/plantcv/masks/vis_tv/mask_brass_tv_z300_L1.png \
-f imgtype_camera_frame_zoom_id \
-M imgtype:VIS,camera:TV,zoom:z300 \
-C NIR \
-T 10 \
-w

#Here we are running a second VIS top-view pipeline at a second zoom level

time \
/home/nfahlgren/programs/plantcv/plantcv-pipeline.py \
-d /home/nfahlgren/projects/lemnatec/burnin2/images3 \
-p /home/nfahlgren/programs/plantcv/scripts/image_analysis/vis_tv/vis_tv_z1000_L1.py \
-t png \
-s burnin2.sqlite3 \
-i /home/nfahlgren/projects/lemnatec/burnin2/plantcv3/images \
-m /home/nfahlgren/programs/plantcv/masks/vis_tv/mask_brass_tv_z1000_L1.png \
-f imgtype_camera_frame_zoom_id \
-M imgtype:VIS,camera:TV,zoom:z1000 \
-C NIR \
-T 10 \
-w
```

### Example Condor Jobfile

```
####################
# HTCondor job description file
####################

universe         = vanilla
executable       = /home/mgehan/plantcv/plantcv-pipeline.py
arguments        = -d /shares/tmockler_share/mgehan/LemnaTec/bnapus_phenotyping_katie/images-full -p /home/mgehan/kt-greenham-lemnatec/scripts/vis_nir_tv_z500_h2_e10000_brassica.py -s ktbrassica.sqlite3 -i /home/mgehan/kt-greenham-lemnatec/output/output500 -f imgtype_camera_zoom_lifter_gain_exposure_id -M imgtype:VIS,camera:TV,zoom:z500 -T 16 -C NIR -w
log              = $(Cluster).$(Process).log
output           = $(Cluster).$(Process).out
error            = $(Cluster).$(Process).error
request_cpus     = 16
notification     = always
nice_user        =False
accounting_group = $ENV(CONDOR_GROUP)
getenv           = true
####################

queue
```

### Running PlantCV pipelines over a flat directory of images

**Note:** We will try and update PlantCV so that it can run over flat directories in a more flexible manner.
But for now please follow the instructions on Running PlantCV over a flat directory carefully.

In order for PlantCV to scrape all of the necessary metadata from the image files, image files need to be named in a particular way.

**Image name might include:**

1. Plant ID
2. Timestamp
3. Measurement/Experiment Label
4. Camera Label

**Example Name :**

AABA002948-2014-03-14 03_29_45-Pilot_031014-VIS_TV_z3500.png

1. Plant ID = AABA002948
2. Timestamp = 2014-03-14 03_29_45
3. Measurement Label = Pilot_031014
4. Camera Label = VIS_TV_z3500

**Next, run images over a flat directory with images named as described above:**

We normally execute pipelines as a shell script or as a condor jobfile (or dagman workflow)

```bash
#!/bin/bash

#Here we are running a VIS top-view pipeline over a flat directory of images

#Image names for this example look like this: cam1-16-08-06_16:45_el1100s1_p19.jpg

/home/mgehan/plantcv/plantcv-pipeline.py \
-d /shares/mgehan_share/raw_data/raw_image/2016-08_pat-edger/data/split-round1/split-cam1 \
-a filename \
-p /home/mgehan/pat-edger/round1-python-pipelines/2016-08_pat-edger_brassica-cam1-splitimg.py \
-s edger-round1-brassica.sqlite3 \
-i /shares/mgehan_share/raw_data/raw_image/2016-08_pat-edger/data/split-round1/split-cam1/output \
-f camera_timestamp_id_other \
-t jpg \
-T 16 \
-w

```


text:
echo "Starting provisioning..."
echo "Setting up user, and its rights"
mkdir -p ~/.klei/DoNotStarveTogether/
echo "End setting up user"

redpajama_set_name: RedPajamaGithub


text:
package com.hazelcast.config;

import com.hazelcast.internal.config.ConfigDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.spi.impl.executionservice.ExecutionService;
import com.hazelcast.topic.ITopic;
import com.hazelcast.topic.TopicOverloadPolicy;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;

import static com.hazelcast.internal.serialization.impl.SerializationUtil.readNullableList;
import static com.hazelcast.internal.serialization.impl.SerializationUtil.writeNullableList;
import static com.hazelcast.internal.util.Preconditions.checkHasText;
import static com.hazelcast.internal.util.Preconditions.checkNotNull;
import static com.hazelcast.internal.util.Preconditions.checkPositive;
import static com.hazelcast.topic.TopicOverloadPolicy.BLOCK;

/**
 * Configuration for a reliable {@link ITopic}.
 *

 * The reliable topic makes use of a {@link com.hazelcast.ringbuffer.Ringbuffer}
 * to store the actual messages.
 *

 * To configure the ringbuffer for a reliable topic, define a ringbuffer in
 * the config with exactly the same name. It is very unlikely that you want
 * to run with the default settings.
 *

 * When a ReliableTopic starts, it will always start from the {@code tail+1}
 * item from the RingBuffer. It will not chew its way through all available
 * events but it will wait for the next item being published.
 *

 * In the reliable topic, global order is always maintained, so all listeners
 * will observe exactly the same order of sequence of messages.
 */
public class ReliableTopicConfig implements IdentifiedDataSerializable, NamedConfig {

    /**
     * The default read batch size.
     */
    public static final int DEFAULT_READ_BATCH_SIZE = 10;

    /**
     * The default slow consumer policy.
     */
    public static final TopicOverloadPolicy DEFAULT_TOPIC_OVERLOAD_POLICY = BLOCK;

    /**
     * Default value for statistics enabled.
     */
    public static final boolean DEFAULT_STATISTICS_ENABLED = true;

    private Executor executor;
    private int readBatchSize = DEFAULT_READ_BATCH_SIZE;
    private String name;
    private boolean statisticsEnabled = DEFAULT_STATISTICS_ENABLED;
    private List<ListenerConfig> listenerConfigs = new LinkedList<ListenerConfig>();
    private TopicOverloadPolicy topicOverloadPolicy = DEFAULT_TOPIC_OVERLOAD_POLICY;

    public ReliableTopicConfig() {
    }

    /**
     * Creates a new ReliableTopicConfig with default settings.
     */
    public ReliableTopicConfig(String name) {
        this.name = checkNotNull(name, "name");
    }

    /**
     * Creates a new ReliableTopicConfig by cloning an existing one.
     *
     * @param config the ReliableTopicConfig to clone
     */
    public ReliableTopicConfig(ReliableTopicConfig config) {
        this.name = config.name;
        this.statisticsEnabled = config.statisticsEnabled;
        this.readBatchSize = config.readBatchSize;
        this.executor = config.executor;
        this.topicOverloadPolicy = config.topicOverloadPolicy;
        this.listenerConfigs = config.listenerConfigs;
    }

    ReliableTopicConfig(ReliableTopicConfig config, String name) {
        this(config);
        this.name = name;
    }

    /**
     * Sets the name of  the reliable topic.
     *
     * @param name the name of the reliable topic
     * @return the updated ReliableTopicConfig
     * @throws IllegalArgumentException if name is {@code null} or an empty string
     */
    public ReliableTopicConfig setName(String name) {
        this.name = checkHasText(name, "name must contain text");
        return this;
    }

    /**
     * Gets the name of the reliable topic.
     *
     * @return the name of the reliable topic
     */
    public String getName() {
        return name;
    }

    /**
     * Gets the TopicOverloadPolicy for this reliable topic.
     *
     * @return the TopicOverloadPolicy
     */
    public TopicOverloadPolicy getTopicOverloadPolicy() {
        return topicOverloadPolicy;
    }

    /**
     * Sets the TopicOverloadPolicy for this reliable topic. Check the
     * {@link TopicOverloadPolicy} for more details about this setting.
     *
     * @param topicOverloadPolicy the new TopicOverloadPolicy
     * @return the updated reliable topic config
     * @throws IllegalArgumentException if topicOverloadPolicy is {@code null}
     */
    public ReliableTopicConfig setTopicOverloadPolicy(TopicOverloadPolicy topicOverloadPolicy) {
        this.topicOverloadPolicy = checkNotNull(topicOverloadPolicy, "topicOverloadPolicy can't be null");
        return this;
    }

    /**
     * Gets the Executor that is going to process the events.
     *

     * If no Executor is selected, then the
     * {@link ExecutionService#ASYNC_EXECUTOR} is used.
     *
     * @return the Executor used to process events
     * @see #setExecutor(java.util.concurrent.Executor)
     */
    public Executor getExecutor() {
        return executor;
    }

    /**
     * Sets the executor that is going to process the event.
     *

     * In some cases it is desirable to set a specific executor. For example,
     * you may want to isolate a certain topic from other topics because it
     * contains long running messages or very high priority messages.
     *

     * A single executor can be shared between multiple Reliable topics, although
     * it could take more time to process a message.
     * If a single executor is not shared with other reliable topics, then the
     * executor only needs to have a single thread.
     *
     * @param executor the executor. if the executor is null, the
     *                 {@link ExecutionService#ASYNC_EXECUTOR} will be used
     *                 to process the event
     * @return the updated config
     */
    public ReliableTopicConfig setExecutor(Executor executor) {
        this.executor = executor;
        return this;
    }

    /**
     * Gets the maximum number of items to read in a batch. Returned value will
     * always be equal or larger than 1.
     *
     * @return the read batch size
     */
    public int getReadBatchSize() {
        return readBatchSize;
    }

    /**
     * Sets the read batch size.
     *

     * The ReliableTopic tries to read a batch of messages from the ringbuffer.
     * It will get at least one, but if there are more available, then it will
     * try to get more to increase throughput. The maximum read batch size can
     * be influenced using the read batch size.
     *

     * Apart from influencing the number of messages to retrieve, the
     * {@code readBatchSize} also determines how many messages will be processed
     * by the thread running the {@code MessageListener} before it returns back
     * to the pool to look for other {@code MessageListener}s that need to be
     * processed. The problem with returning to the pool and looking for new work
     * is that interacting with an executor is quite expensive due to contention
     * on the work-queue. The more work that can be done without retuning to the
     * pool, the smaller the overhead.
     *

     * If the {@code readBatchSize} is 10 and there are 50 messages available,
     * 10 items are retrieved and processed consecutively before the thread goes
     * back to the pool and helps out with the processing of other messages.
     *

     * If the {@code readBatchSize} is 10 and there are 2 items available,
     * 2 items are retrieved and processed consecutively.
     *

     * If the {@code readBatchSize} is an issue because a thread will be busy
     * too long with processing a single {@code MessageListener} and it can't
     * help out other {@code MessageListener}s, increase the size of the
     * threadpool so the other {@code MessageListener}s don't need to wait for
     * a thread, but can be processed in parallel.
     *
     * @param readBatchSize the maximum number of items to read in a batch
     * @return the updated reliable topic config
     * @throws IllegalArgumentException if the {@code readBatchSize} is smaller than 1
     */
    public ReliableTopicConfig setReadBatchSize(int readBatchSize) {
        this.readBatchSize = checkPositive("readBatchSize", readBatchSize);
        return this;
    }

    /**
     * Checks if statistics are enabled for this reliable topic.
     *
     * @return {@code true} if enabled, {@code false} otherwise
     */
    public boolean isStatisticsEnabled() {
        return statisticsEnabled;
    }

    /**
     * Enables or disables statistics for this reliable topic.
     * Collects the creation time, total number of published and received
     * messages for each member locally.
     *
     * @param statisticsEnabled {@code true} to enable statistics, {@code false} to disable
     * @return the updated reliable topic config
     */
    public ReliableTopicConfig setStatisticsEnabled(boolean statisticsEnabled) {
        this.statisticsEnabled = statisticsEnabled;
        return this;
    }

    /**
     * Sets the list of message listeners (listens for when messages are added
     * or removed) for this topic.
     *
     * @param listenerConfigs the list of message listeners for this topic
     * @return this updated topic configuration
     */
    public ReliableTopicConfig setMessageListenerConfigs(List<ListenerConfig> listenerConfigs) {
        this.listenerConfigs = listenerConfigs != null ? listenerConfigs : new LinkedList<ListenerConfig>();
        return this;
    }

    /**
     * Gets the list of message listeners (listens for when messages are added
     * or removed) for this reliable topic.
     *
     * @return list of MessageListener configurations
     */
    public List<ListenerConfig> getMessageListenerConfigs() {
        return listenerConfigs;
    }

    /**
     * Adds a message listener (listens for when messages are added or removed)
     * to this reliable topic.
     *
     * @param listenerConfig the ListenerConfig to add
     * @return the updated config
     * @throws NullPointerException if listenerConfig is {@code null}
     */
    public ReliableTopicConfig addMessageListenerConfig(ListenerConfig listenerConfig) {
        checkNotNull(listenerConfig, "listenerConfig can't be null");
        listenerConfigs.add(listenerConfig);
        return this;
    }

    @Override
    public String toString() {
        return "ReliableTopicConfig{"
                + "name='" + name + '\''
                + ", topicOverloadPolicy=" + topicOverloadPolicy
                + ", executor=" + executor
                + ", readBatchSize=" + readBatchSize
                + ", statisticsEnabled=" + statisticsEnabled
                + ", listenerConfigs=" + listenerConfigs
                + '}';
    }

    @Override
    public int getFactoryId() {
        return ConfigDataSerializerHook.F_ID;
    }

    @Override
    public int getClassId() {
        return ConfigDataSerializerHook.RELIABLE_TOPIC_CONFIG;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeObject(executor);
        out.writeInt(readBatchSize);
        out.writeString(name);
        out.writeBoolean(statisticsEnabled);
        writeNullableList(listenerConfigs, out);
        out.writeString(topicOverloadPolicy.name());
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        executor = in.readObject();
        readBatchSize = in.readInt();
        name = in.readString();
        statisticsEnabled = in.readBoolean();
        listenerConfigs = readNullableList(in);
        topicOverloadPolicy = TopicOverloadPolicy.valueOf(in.readString());
    }

    @Override
    @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
    public final boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ReliableTopicConfig)) {
            return false;
        }

        ReliableTopicConfig that = (ReliableTopicConfig) o;

        if (readBatchSize != that.readBatchSize) {
            return false;
        }
        if (statisticsEnabled != that.statisticsEnabled) {
            return false;
        }
        if (executor != null ? !executor.equals(that.executor) : that.executor != null) {
            return false;
        }
        if (!name.equals(that.name)) {
            return false;
        }
        if (listenerConfigs != null ? !listenerConfigs.equals(that.listenerConfigs) : that.listenerConfigs != null) {
            return false;
        }
        return topicOverloadPolicy == that.topicOverloadPolicy;
    }

    @Override
    public final int hashCode() {
        int result = executor != null ? executor.hashCode() : 0;
        result = 31 * result + readBatchSize;
        result = 31 * result + name.hashCode();
        result = 31 * result + (statisticsEnabled ? 1 : 0);
        result = 31 * result + (listenerConfigs != null ? listenerConfigs.hashCode() : 0);
        result = 31 * result + (topicOverloadPolicy != null ? topicOverloadPolicy.hashCode() : 0);
        return result;
    }
}


text:
class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :Workout, class_name: "Comment"
  belongs_to :Workout

  field :username,          type: String
  field :text,              type: String
end


text:
"""
Django settings for humanadm project.

Generated by 'django-admin startproject' using Django 1.8.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
SETTINGS_DIR = os.path.dirname(__file__) #setting the location of settings path of the project
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x#@&(vn66lc_=k^u(854t#7ocd9$xe&+k=8e&pf0aotr6kp0x3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'register',
    'wkhtmltopdf',
)
REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = True
WEBODT_CONVERTER = 'webodt.converters.abiword.AbiwordODFConverter'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/accounts/login/'
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'humanadm.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(PROJECT_PATH,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'humanadm.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
MEDIA_URL = '/media/'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = ''
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
	STATIC_PATH,
)

TEMPLATE_PATH = os.path.join(PROJECT_PATH,'templates')
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
	TEMPLATE_PATH,
)


text:
package hu.deik.boozepal.service.impl.test;

import java.util.Arrays;
import java.util.List;

import javax.ejb.EJB;

import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.container.ClassContainer;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import hu.deik.boozepal.arquillian.container.ArquillianContainer;
import hu.deik.boozepal.common.vo.PriceCategoryVO;
import hu.deik.boozepal.common.vo.PriceCategroy;
import hu.deik.boozepal.core.repo.UserRepository;
import hu.deik.boozepal.service.statistics.PriceCategoryStatisticsService;
import hu.deik.boozepal.service.statistics.impl.PriceCategoryStatisticsServiceImpl;

@RunWith(Arquillian.class)
public class PriceCategoryServiceIT extends ArquillianContainer {

    private static Class<?>[] testClasses = { UserRepository.class, PriceCategoryVO.class, PriceCategroy.class,
            PriceCategoryStatisticsServiceImpl.class, PriceCategoryStatisticsService.class };

    @Deployment
    public static Archive<WebArchive> createDeployment() {
        Archive<WebArchive> deployment = ArquillianContainer.createDeployment();
        ((ClassContainer<WebArchive>) deployment).addClasses(testClasses);
        return deployment;
    }

    @EJB
    private PriceCategoryStatisticsService service;

    @Test
    public void testgetPriceCategoryStatistics() {
        List<PriceCategoryVO> priceCategoryStatistics = service.getPriceCategoryStatistics();
        PriceCategoryVO low = PriceCategoryVO.builder().category(PriceCategroy.LOWEST).total(1).build();
        PriceCategoryVO lowmed = PriceCategoryVO.builder().category(PriceCategroy.LOWMEDIUM).total(0).build();
        PriceCategoryVO medium = PriceCategoryVO.builder().category(PriceCategroy.MEDIUM).total(1).build();
        PriceCategoryVO medhigh = PriceCategoryVO.builder().category(PriceCategroy.MEDHIGH).total(0).build();
        PriceCategoryVO highest = PriceCategoryVO.builder().category(PriceCategroy.HIGHER).total(0).build();

        List<PriceCategoryVO> list = Arrays.asList(low, lowmed, medium, medhigh, highest);
        Assert.assertThat(list, Matchers.containsInAnyOrder(priceCategoryStatistics.toArray()));
    }

    @Test
    public void testGetTheBiggestCategoryTotal() {
        Integer theBiggestCategoryTotal = service.getTheBiggestCategoryTotal();
        Assert.assertEquals(Integer.valueOf(1), theBiggestCategoryTotal);
    }

}


text:
A python CLI around the PNC REST API

Installation:
 * pip install pnc-cli

Usage:
 * Configure the REST endpoint for PNC in USER_HOME/.config/pnc-cli/pnc-cli.conf
 * pnc -h for a list of valid operations.

Currently outputs the raw JSON. More refined output is definitely in the works :)


text:
package jade.imtp.leap.nio;

//#J2ME_EXCLUDE_FILE
import jade.core.FrontEnd;
import jade.core.BackEnd;
import jade.core.BackEndContainer;
import jade.core.BEConnectionManager;
import jade.core.Profile;
import jade.core.ProfileException;
import jade.core.IMTPException;
import jade.imtp.leap.BackEndSkel;
import jade.imtp.leap.FrontEndStub;
import jade.imtp.leap.Dispatcher;
import jade.imtp.leap.ICPDispatchException;
import jade.imtp.leap.ICPException;
import jade.imtp.leap.JICP.JICPProtocol;
import jade.imtp.leap.JICP.JICPMediatorManager;
import jade.imtp.leap.JICP.JICPPacket;
import jade.imtp.leap.JICP.Connection;
import jade.util.leap.Properties;
import jade.util.Logger;

import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Level;

/**
This class implements the BIFEDispatcher related BackEnd dispatcher
managable by an asynchronous JICPMediatorManager
@author Giovanni Caire - Telecom Italia LAB S.p.A.
 */
public class NIOBEDispatcher implements NIOMediator, BEConnectionManager, Dispatcher {

    private static final long RESPONSE_TIMEOUT = 60000;
    private long keepAliveTime;
    private boolean enableServerKeepAlive;
    private long lastReceivedTime;
    private boolean active = true;
    private boolean peerActive = true;
    private boolean connectionDropped = false;
    private JICPMediatorManager myMediatorManager;
    private String myID;
    private Properties myProperties;
    private BackEndContainer myContainer = null;
    protected InputManager inpManager;
    protected OutputManager outManager;
    private Logger myLogger = Logger.getMyLogger(getClass().getName());

    /**
    Retrieve the ID of this mediator. Returns null if this mediator
    is not active
     */
    public String getID() {
        return (active ? myID : null);
    }

    /**
    Retrieve the startup Properties for this NIOBEDispatcher.
     */
    public Properties getProperties() {
        return myProperties;
    }

    /**
    Initialize this JICPMediator
     */
    public void init(JICPMediatorManager mgr, String id, Properties props) throws ICPException {
        myMediatorManager = mgr;
        myID = id;
        myProperties = props;

        // Max disconnection time
        long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
        try {
            maxDisconnectionTime = Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
        } catch (Exception e) {
            // Keep default
        }

        // Keep-alive time
        keepAliveTime = JICPProtocol.DEFAULT_KEEP_ALIVE_TIME;
        try {
            keepAliveTime = Long.parseLong(props.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY));
        } catch (Exception e) {
            // Keep default
        }

        // Server-keep-alive time
        enableServerKeepAlive = false;
        try {
            enableServerKeepAlive = Boolean.valueOf(props.getProperty("enable-server-keep-alive")).booleanValue();
        } catch (Exception e) {
            // Keep default
        }

        // inpCnt
        int inpCnt = 0;
        try {
            inpCnt = (Integer.parseInt(props.getProperty("lastsid")) + 1) & 0x0f;
        } catch (Exception e) {
            // Keep default
        }
        System.out.println("Next command for FE will have sessionID " + inpCnt);

        /* lastSid
        int lastSid = 0x0f;
        try {
            lastSid = (byte) (Integer.parseInt(props.getProperty("outcnt")) - 1);
            if (lastSid < 0) {
                lastSid = 0x0f;
            }
        } catch (Exception e) {
            // Keep default
        }*/

        FrontEndStub st = new FrontEndStub(this);
        inpManager = new InputManager(inpCnt, st);

        BackEndSkel sk = startBackEndContainer(props);
        outManager = new OutputManager(0x0f, sk, maxDisconnectionTime);
    }

    protected final BackEndSkel startBackEndContainer(Properties props) throws ICPException {
        try {
            String nodeName = myID.replace(':', '_');
            props.setProperty(Profile.CONTAINER_NAME, nodeName);

            myContainer = new BackEndContainer(props, this);
            if (!myContainer.connect()) {
                throw new ICPException("BackEnd container failed to join the platform");
            }
            // Possibly the node name was re-assigned by the main
            myID = myContainer.here().getName();
            if (myLogger.isLoggable(Logger.CONFIG)) {
                myLogger.log(Logger.CONFIG, "BackEndContainer " + myID + " successfully joined the platform");
            }
            return new BackEndSkel(myContainer);
        } catch (ProfileException pe) {
            // should never happen
            pe.printStackTrace();
            throw new ICPException("Error creating profile");
        }
    }
    // Local variable only used in the kill() method
    private Object shutdownLock = new Object();

    /**
    Kill the above container.
    This may be called by the JICPMediatorManager or when
    a peer termination notification is received.
     */
    public void kill() {
        // Avoid killing the above container two times
        synchronized (shutdownLock) {
            if (active) {
                active = false;
                myContainer.shutDown();
            }
        }
    }

    /**
     * Passes to this JICPMediator the connection opened by the mediated
     * entity.
     * This is called by the JICPMediatorManager this Mediator is attached to
     * as soon as the mediated entity (re)connects.
     * @param c the connection to the mediated entity
     * @param pkt the packet that was sent by the mediated entity when
     * opening this connection
     * @param addr the address of the mediated entity
     * @param port the local port used by the mediated entity
     * @return an indication to the JICPMediatorManager to keep the
     * connection open.
     */
    public boolean handleIncomingConnection(Connection c, JICPPacket pkt, InetAddress addr, int port) {
        checkTerminatedInfo(pkt);

        if (peerActive) {
            if (connectionDropped) {
                droppedToDisconnected();
            }

            // Update keep-alive info
            lastReceivedTime = System.currentTimeMillis();

            boolean inp = false;
            byte[] data = pkt.getData();
            if (data.length == 1) {
                inp = (data[0] == 1);
            }
            if (inp) {
                inpManager.setConnection((NIOJICPConnection) c);
                if (myLogger.isLoggable(Logger.CONFIG)) {
                    myLogger.log(Logger.CONFIG, myID + ": New INP Connection establishd");
                }
            } else {
                outManager.setConnection(c);
                if (myLogger.isLoggable(Logger.CONFIG)) {
                    myLogger.log(Logger.CONFIG, myID + ": New OUT Connection establishd");
                }
            }

            return true;
        } else {
            // The remote FrontEnd has terminated spontaneously -->
            // Kill the above container (this will also kill this NIOBEDispatcher).
            kill();
            return false;
        }
    }

    /**
    Notify this NIOMediator that an error occurred on one of the
    Connections it was using. This information is important since,
    unlike normal mediators, a NIOMediator typically does not read
    packets from
    connections on its own (the JICPMediatorManager does that in general).
     */
    public void handleConnectionError(Connection c, Exception e) {
        myLogger.log(Logger.WARNING, "connection error", e);
        if (active && peerActive) {
            // Try assuming it is the input connection
            try {
                inpManager.checkConnection(c);
                myLogger.log(Logger.WARNING, myID + ": IC Disconnection detected");
                inpManager.resetConnection();
            } catch (ICPException icpe) {
                // Then try assuming it is the output connection
                try {
                    outManager.checkConnection(c);
                    myLogger.log(Logger.WARNING, myID + ": OC Disconnection detected");
                    outManager.resetConnection();
                } catch (ICPException icpe2) {
                    // Ignore it
                }
            }
        }
    }

    /**
    Passes to this mediator a JICPPacket received by the
    JICPMediatorManager this mediator is attached to.
    In a NIOMediator this should never be called.
     */
    public JICPPacket handleJICPPacket(JICPPacket p, InetAddress addr, int port) throws ICPException {
        throw new ICPException("Unexpected call");
    }

    /**
    Overloaded version of the handleJICPPacket() method including
    the Connection the incoming JICPPacket was received
    from. This information is important since, unlike normal mediators,
    a NIOMediator may not read packets from connections on its own (the
    JICPMediatorManager does that in general).
     */
    public JICPPacket handleJICPPacket(Connection c, JICPPacket pkt, InetAddress addr, int port) throws ICPException {
        if (pkt.getType() == JICPProtocol.DROP_DOWN_TYPE) {
            // Note that the return packet is written inside the handleDropDown()
            // method since the connection must be closed after the response has
            // been sent back.
            handleDropDown(c, pkt, addr, port);
            return null;
        }

        checkTerminatedInfo(pkt);

        // Update keep-alive info
        lastReceivedTime = System.currentTimeMillis();

        byte type = pkt.getType();
        if (type == JICPProtocol.COMMAND_TYPE) {
            if (peerActive) {
                return outManager.handleCommand(c, pkt);
            } else {
                // The remote FrontEnd has terminated spontaneously -->
                // Kill the above container (this will also kill this NIOBEDispatcher).
                kill();
                return null;
            }
        } else if (type == JICPProtocol.KEEP_ALIVE_TYPE) {
            if (enableServerKeepAlive) {
                inpManager.sendServerKeepAlive();
            }
            return outManager.handleKeepAlive(c, pkt);
        } /* Asynch-reply
        else if (type == JICPProtocol.RESPONSE_TYPE || type == JICPProtocol.ERROR_TYPE) {
        inpManager.handleResponse(c, pkt);
        return null;
        }*/ else {
            throw new ICPException("Unexpected packet type " + type);
        }
    }

    /**
    This is periodically called by the JICPMediatorManager and is
    used by this NIOMediator to evaluate the elapsed time without
    the need of a dedicated thread or timer.
     */
    public final void tick(long currentTime) {
        if (active && !connectionDropped) {
            // 1) If there is a blocking read operation in place check the
            // response timeout
            inpManager.checkResponseTime(currentTime);

            // 2) Evaluate the keep alive
            if (keepAliveTime > 0) {
                if ((currentTime - lastReceivedTime) > (keepAliveTime + RESPONSE_TIMEOUT)) {
                    // Missing keep-alive.
                    // The OUT connection is no longer valid
                    if (outManager.isConnected()) {
                        myLogger.log(Logger.WARNING, myID + ": Missing keep-alive");
                        outManager.resetConnection();
                    }
                    // Check the INP connection. Since this method must return
                    // asap, does it in a separated Thread
                    if (inpManager.isConnected()) {
                        Thread t = new Thread() {

                            public void run() {
                                try {
                                    //JICPPacket pkt = new JICPPacket(JICPProtocol.KEEP_ALIVE_TYPE, JICPProtocol.DEFAULT_INFO, null);
                                    //inpManager.dispatch(pkt, false);
                                    inpManager.sendServerKeepAlive();
                                    if (myLogger.isLoggable(Logger.CONFIG)) {
                                        myLogger.log(Logger.CONFIG, myID + ": IC valid");
                                    }
                                } catch (Exception e) {
                                    // Just do nothing: the INP connection has been reset
                                }
                            }
                        };
                        t.start();
                    }
                }
            }

            // 3) Evaluate the max disconnection time
            if (outManager.checkMaxDisconnectionTime(currentTime)) {
                myLogger.log(Logger.SEVERE, myID + ": Max disconnection time expired.");
                // Consider as if the FrontEnd has terminated spontaneously -->
                // Kill the above container (this will also kill this NIOBEDispatcher).
                kill();
            }
        }
    }

    ////////////////////////////////////////////////
    // BEConnectionManager interface implementation
    ////////////////////////////////////////////////
    /**
    Return a stub of the remote FrontEnd that is connected to the
    local BackEnd.
    @param be The local BackEnd
    @param props Additional (implementation dependent) connection
    configuration properties.
    @return A stub of the remote FrontEnd.
     */
    public FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException {
        return inpManager.getStub();
    }

    /**
    Make this NIOBEDispatcher terminate.
     */
    public void shutdown() {
        active = false;
        if (myLogger.isLoggable(Logger.INFO)) {
            myLogger.log(Logger.INFO, myID + ": shutting down");
        }

        // Deregister from the JICPServer
        if (myID != null) {
            myMediatorManager.deregisterMediator(myID);
        }

        inpManager.shutdown();
        outManager.shutdown();
    }

    //////////////////////////////////////////
    // Dispatcher interface implementation
    //////////////////////////////////////////
    public byte[] dispatch(byte[] payload, boolean flush, int oldSessionId) throws ICPException {
        if (connectionDropped) {
            // Move from DROPPED state to DISCONNECTED state and wait
            // for the FE to reconnect
            droppedToDisconnected();
            requestRefresh();
            throw new ICPException("Connection dropped");
        } else {
            // Normal dispatch
            JICPPacket pkt = new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.DEFAULT_INFO, payload);
            pkt = inpManager.dispatch(pkt, flush, oldSessionId);
            return pkt.getData();
        }
    }

    //////////////////////////////////////////////////////
    // Methods related to connection drop-down management
    //////////////////////////////////////////////////////
    /**
    Handle a connection DROP_DOWN request from the FE.
     */
    protected void handleDropDown(Connection c, JICPPacket pkt, InetAddress addr, int port) {
        if (myLogger.isLoggable(Logger.INFO)) {
            myLogger.log(Logger.INFO, myID + ": DROP_DOWN request received.");
        }

        try {
            // If the INP connection is down or we have some postponed command
            // to flush, refuse dropping the connection
            if (inpManager.isConnected() && inpManager.isEmpty()) {
                JICPPacket rsp = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null);
                c.writePacket(rsp);

                inpManager.resetConnection();
                outManager.resetConnection();
                connectionDropped = true;
            } else {
                myLogger.log(Logger.WARNING, myID + ": DROP_DOWN request refused.");
                JICPPacket rsp = new JICPPacket(JICPProtocol.ERROR_TYPE, getReconnectInfo(), null);
                c.writePacket(rsp);
            }
        } catch (Exception e) {
            myLogger.log(Logger.WARNING, myID + ": Error writing DROP_DOWN response. " + e);
        }
    }

    /**
    Move from the connectionDropped state to the Disconnected state.
    This may happen when
    - a packet must be dispatched to the FE.
    - an incoming connection is detected
     */
    private void droppedToDisconnected() {
        connectionDropped = false;
        outManager.setExpirationDeadline();
    }

    /**
    Request the FE to refresh the connection.
     */
    protected void requestRefresh() {
    }

    public boolean isConnected() {
        return inpManager.isConnected() && outManager.isConnected();
    }

    private void updateConnectedState() {
        myProperties.put(BEManagementHelper.CONNECTED, (isConnected() ? "true" : "false"));
    }

    /**
    Inner class InputManager.
    This class manages the delivery of commands to the FrontEnd
     */
    protected class InputManager {

        private NIOJICPConnection myConnection;
        private boolean dispatching = false;
        private boolean connectionRefreshed;
        private boolean waitingForFlush;
        private long readStartTime = -1;
        private JICPPacket currentReply;
        private Object dispatchLock = new Object();
        private int inpCnt;
        private FrontEndStub myStub;

        InputManager(int c, FrontEndStub s) {
            inpCnt = c;
            myStub = s;
        }

        FrontEndStub getStub() {
            return myStub;
        }

        synchronized void setConnection(NIOJICPConnection c) {
            // Reset the old connection
            resetConnection();

            // Set the new connection
            myConnection = c;
            connectionRefreshed = true;
            waitingForFlush = myStub.flush();
            //myContainer.notifyInputConnectionReady();
            updateConnectedState();
        }

        synchronized void resetConnection() {
            // Close the connection if it was in place
            if (myConnection != null) {
                close(myConnection);
                myConnection = null;
            }
            // Asynch-reply
            // If there was someone waiting for a response on the
            // connection notify it.
            //notifyAll();
            updateConnectedState();
        }

        final void checkConnection(Connection c) throws ICPException {
            if (c != myConnection) {
                throw new ICPException("Wrong connection");
            }
        }

        final boolean isConnected() {
            return myConnection != null;
        }

        final boolean isEmpty() {
            // We are empty if we are not dispatching a JICPPacket and our stub
            // has no postponed commands waiting to be delivered.
            return (!dispatching) && myStub.isEmpty();
        }

        void shutdown() {
            resetConnection();
        }

        /**
        Dispatch a JICP command to the FE and get back a reply.
        This method must NOT be executed in mutual exclusion with
        setConnection() and resetConnection() since it performs a
        blocking read operation --> It can't just be declared synchronized.
         */
        final JICPPacket dispatch(JICPPacket pkt, boolean flush, int oldSessionId) throws ICPException {
            synchronized (dispatchLock) {
                dispatching = true;
                try {
                    synchronized (this) {
                        if ((!active) || (myConnection == null) || (waitingForFlush && (!flush))) {
                            // If we are waiting for flushed packets and the current packet
                            // is a normal (i.e. non-flushed) one, then throw an exception -->
                            // The packet will be put in the queue of packets to be flushed
                            throw new ICPException("Unreachable");
                        }

                        waitingForFlush = false;
                        connectionRefreshed = false;
                    }

                    try {
            			if (flush && oldSessionId != -1) {
            				// This is a postponed command whose previous dispatch failed --> Use the
            				// old sessionId, so that if the server already received it (previous dispatch
            				// failed due to a response delivering error) the command will be recognized
            				// as duplicated and properly managed
            				inpCnt = oldSessionId;
            			}
                        pkt.setSessionID((byte) inpCnt);
                        if (myLogger.isLoggable(Logger.FINE)) {
                            myLogger.log(Logger.FINE, myID + ": Sending command " + inpCnt + " to FE");
                        }

                        long start = System.currentTimeMillis();
                        myConnection.writePacket(pkt);
                        // Asynch-reply: JICPPacket reply = waitForReply(RESPONSE_TIMEOUT);
                        readStartTime = System.currentTimeMillis();
                        JICPPacket reply = myConnection.readPacket();
                        readStartTime = -1;
                        checkTerminatedInfo(reply);
                        lastReceivedTime = System.currentTimeMillis();
                        long end = lastReceivedTime;
                        System.out.println("INP Session " + inpCnt + ". Dispatching time = " + (end - start));

                        if (myLogger.isLoggable(Logger.FINER)) {
                            myLogger.log(Logger.FINER, myID + ": Received response " + inpCnt + " from FE");
                        }
                        if (reply.getType() == JICPProtocol.ERROR_TYPE) {
                            // Communication OK, but there was a JICP error on the peer
                            throw new ICPException(new String(pkt.getData()));
                        }
                        if (!peerActive) {
                            // This is the response to an exit command --> Suicide, without
                            // killing the above container since it is already dying.
                            NIOBEDispatcher.this.shutdown();
                        }
                        return reply;
                    } catch (NullPointerException npe) {
                        // This can happen if a resetConnection() occurs just before
                        // myConnection.writePacket()/readPacket() is called.
                        throw new ICPException("Connection reset.");
                    } catch (IOException ioe) {
                        synchronized (this) {
                            if (myConnection != null && !connectionRefreshed) {
                                // There was an IO exception writing data to the connection
                                // --> reset the connection.
                                myLogger.log(Logger.WARNING, myID + ": IOException IC. " + ioe);
                                resetConnection();
                            }
                        }
                        readStartTime = -1;
                        throw new ICPDispatchException("Dispatching error.", ioe, inpCnt);
                    }
                    finally {
                        inpCnt = (inpCnt + 1) & 0x0f;
                    }
                } finally {
                    dispatching = false;
                }
            }
        }

        public final void checkResponseTime(long currentTime) {
            if (readStartTime > 0 && (currentTime - readStartTime) > RESPONSE_TIMEOUT) {
                myLogger.log(Logger.WARNING, myID + ": Response timeout expired.");
                resetConnection();
            }
        }

        public void sendServerKeepAlive() throws ICPException {
            JICPPacket pkt = new JICPPacket(JICPProtocol.KEEP_ALIVE_TYPE, JICPProtocol.DEFAULT_INFO, null);
            dispatch(pkt, false, -1);
        }
        /* Asynch-reply
        final synchronized void handleResponse(Connection c, JICPPacket reply) throws ICPException {
        checkConnection(c);
        currentReply = reply;
        notifyAll();
        }

        private synchronized JICPPacket waitForReply(long timeout) throws ICPException, IOException {
        try {
        if (currentReply == null) {
        wait(timeout);
        if (currentReply == null) {
        if (isConnected()) {
        if (connectionRefreshed) {
        throw new ICPException("Connection refreshed");
        }
        else {
        throw new IOException("Response timeout expired");
        }
        }
        else {
        throw new ICPException("Connection reset");
        }
        }
        }
        JICPPacket tmp = currentReply;
        currentReply = null;
        return tmp;
        }
        catch (InterruptedException ie) {
        throw new ICPException("Interrupted");
        }
        }*/
    } // END of inner class InputManager

    /**
    Inner class OutputManager
    This class manages the reception of commands and keep-alive
    packets from the FrontEnd.
    This class also manages the maxDisconnectionTime, i.e. the remote
    FrontEnd is considered dead if it cannot re-establish the
    OUT connection within the maxDisconnectionTime.
     */
    protected class OutputManager {

        private Connection myConnection;
        private JICPPacket lastResponse;
        private int lastSid;
        private BackEndSkel mySkel;
        private long maxDisconnectionTime, expirationDeadline;

        OutputManager(int n, BackEndSkel s, long t) {
            lastSid = n;
            mySkel = s;
            maxDisconnectionTime = t;
        }

        synchronized void setConnection(Connection c) {
            // Close the old connection if any
            if (myConnection != null) {
                close(myConnection);
            }
            // Set the new connection
            myConnection = c;
            updateConnectedState();
        }

        synchronized void resetConnection() {
            if (myConnection != null) {
                setExpirationDeadline();
                close(myConnection);
            }
            myConnection = null;
            updateConnectedState();
        }

        synchronized void setExpirationDeadline() {
            expirationDeadline = System.currentTimeMillis() + maxDisconnectionTime;
        }

        final void checkConnection(Connection c) throws ICPException {
            if (c != myConnection) {
                throw new ICPException("Wrong connection");
            }
        }

        final boolean isConnected() {
            return (myConnection != null);
        }

        void shutdown() {
            resetConnection();
        }

        final synchronized JICPPacket handleCommand(Connection c, JICPPacket cmd) throws ICPException {
            checkConnection(c);
            JICPPacket reply = null;
            byte sid = cmd.getSessionID();
            if (sid == lastSid && lastResponse != null) {
                myLogger.log(Logger.WARNING, myID + ": Duplicated command from FE " + sid);
                reply = lastResponse;
            } else {
                if (myLogger.isLoggable(Logger.FINE)) {
                    myLogger.log(Logger.FINE, myID + ": Received command " + sid + " from FE");
                }

                byte[] rspData = mySkel.handleCommand(cmd.getData());
                if (myLogger.isLoggable(Logger.FINER)) {
                    myLogger.log(Logger.FINER, myID + ": Command " + sid + " from FE served ");
                }

                reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, getReconnectInfo(), rspData);
                reply.setSessionID(sid);
                lastSid = sid;
                lastResponse = reply;
            }
            return reply;
        }

        synchronized JICPPacket handleKeepAlive(Connection c, JICPPacket command) throws ICPException {
            checkConnection(c);
            if (myLogger.isLoggable(Logger.FINEST)) {
                myLogger.log(Logger.FINEST, myID + ": Keep-alive received");
            }
            return new JICPPacket(JICPProtocol.RESPONSE_TYPE, getReconnectInfo(), null);
        }

        final synchronized boolean checkMaxDisconnectionTime(long currentTime) {
            return (!isConnected()) && (currentTime > expirationDeadline);
        }
    } // END of inner class OutputManager

    private final byte getReconnectInfo() {
        byte info = JICPProtocol.DEFAULT_INFO;
        // If the inpConnection is null request the FrontEnd to reconnect
        if (!inpManager.isConnected()) {
            info |= JICPProtocol.RECONNECT_INFO;
        }
        return info;
    }

    private final void checkTerminatedInfo(JICPPacket pkt) {
        if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
            peerActive = false;
            if (myLogger.isLoggable(Logger.INFO)) {
                myLogger.log(Logger.INFO, myID + ": Peer termination notification received");
            }
        }
    }

    private void close(Connection c) {
        try {
            c.close();
        } catch (IOException ioe) {
        }
    }
}


text:
import {
  createModel,
  createSchema,
  currentDate,
  DocumentTypeFromSchema,
  FieldsOfDocument,
  ItemTypeFromTypeSchemaFunction,
  ModelFromSchema,
  ModelTypeFromTypeSchemaFunction,
  MongooseDocument,
  MongooseModule,
  ReplaceModelReturnType,
} from "../helpers";

import * as uuid from "uuid";
import * as mongooseLeanVirtuals from "mongoose-lean-virtuals";
import { IncidentEventSchema } from "./incident-event";

export function CADIncidentSchema(mongoose: MongooseModule) {
  const { Schema, Types } = mongoose;
  const IncidentEvent = IncidentEventSchema(mongoose);

  const toJSONOpts = {
    versionKey: false,
    transform(doc: DocumentTypeFromSchema<typeof modelSchema>, ret: FieldsOfDocument<DocumentTypeFromSchema<typeof modelSchema>>) {
      strictSchema(doc.schema, ret);
    },
  };

  const CADComment = createSchema(Schema, {
    Comment: {
      type: String,
    },
    CommentSource: {
      type: String,
    },
    CommentDateTime: {
      type: String,
    },
    CommentConfidential: {
      type: Boolean,
      default: false
    }
  }, {
    _id: false,
    id: false,
  });

  CADComment.set("toJSON", toJSONOpts);

  const CADPerson = createSchema(Schema, {
    PersonnelID: {
      type: String,
    },
    PersonnelName: {
      type: String,
    },
    PersonnelRank: {
      type: String,
    },
    PersonnelWorkCode: {
      type: String,
    },
    PersonnelNote: {
      type: String,
    },
  }, {
    _id: false,
    id: false,
  });
  CADPerson.set("toJSON", toJSONOpts);

  const CADUnit = createSchema(Schema, {
    UnitID: {
      type: String,
      required: true,
    },
    UnitDispatchNumber: {
      type: String,
      required: true,
    },
    AlarmAtDispatch: {
      type: String,
    },
    TimeDispatched: {
      type: String,
    },
    TimeEnroute: {
      type: String,
    },
    TimeArrived: {
      type: String,
    },
    TimeStaged: {
      type: String,
    },
    TimeCleared: {
      type: String,
    },
    TimeAtHospital: {
      type: String,
    },
    TimePatient: {
      type: String,
    },
    TimeTransport: {
      type: String,
    },
    TimeTransporting: {
      type: String,
    },

    PersonnelCount: {
      type: Number,
    },
    Personnel: [CADPerson],
  }, {
    _id: false,
    id: false,
  });
  CADUnit.set("toJSON", toJSONOpts);

  const APNNotificationType = createSchema(Schema, {
    name: {
      type: String,
    },
    value: {
      type: String,
    },
  }, {
    _id: false,
    id: false,
  });
  APNNotificationType.set("toJSON", toJSONOpts);

  const CADPriorIncident = createSchema(Schema, {
    Address: {
      type: String,
    },
    Comment: {
      type: [CADComment],
    },
    IncidentDateTime: {
      type: String,
    },
    IncidentNumber: {
      type: String,
    },
    Jurisdiction: {
      type: String,
    },
    Problem: {
      type: String,
    },
    Suite: {
      type: String,
    },
  }, {
    _id: false,
    id: false,
  });
  CADPriorIncident.set("toJSON", toJSONOpts);

  const modelSchema = createSchema(Schema, {
    _id: {
      type: Types.ObjectId,
      auto: true,
    },
    uuid: {
      type: String,
      default: uuid.v4,
    },
    departmentId: {
      type: String,
      default: "",
      required: true,
      index: true,
    },
    AgencyID: {
      type: String,
      required: true,
    },
    IncidentNumber: {
      type: String,
      required: true,
    },
    TransactionID: {
      type: String,
      required: true,
    },

    // Incident Specific
    AgencyIncidentCallTypeDescription: {
      type: String,
    },
    AgencyIncidentCallType: {
      type: String,
    },
    AgencyIncidentCallSubTypeDescription: {
      type: String,
    },
    AgencyIncidentCallSubType: {
      type: String,
    },
    AgencyIncidentPriorityDescription: {
      type: String,
    },
    PulsePointIncidentCallType: {
      type: String,
    },
    PulsePointDeterminantCode: {
      type: String,
    },
    AlarmLevel: {
      type: String,
    },
    CommandName: {
      type: String,
    },
    FireMap: {
      type: String,
    },
    TBMap: {
      type: String,
    },
    MapPages: {
      type: String,
    },
    TacticalChannel: {
      type: String,
    },
    TacticalAltChannel: {
      type: String,
    },
    CommandChannel: {
      type: String,
    },

    // Dates
    EntryDateTime: {
      type: String,
    },
    ClosedDateTime: {
      type: String,
    },
    CallReceivedDateTime: {
      type: String,
    },
    DispatchDateTime: {
      type: String,
    },
    IncidentLastUpdate: {
      type: String,
    },
    EnrouteDateTime: {
      type: String,
    },
    OnSceneDateTime: {
      type: String,
    },

    modified_date: {
      type: String,
    },
    modified_unix_date: {
      type: Number,
    },
    modified: {
      type: Date,
      default: currentDate,
    },
    start_unix_date: {
      type: Number,
    },
    closed_unix_date: {
      type: Number,
    },
    queued_at: {
      type: Number,
    },
    scheduled_at: {
      type: Number,
    },
    blacklisted: {
      type: Boolean,
      default: false,
    },

    // Address fields
    StreetName: {
      type: String,
    },
    StreetSuffix: {
      type: String,
    },
    Predirectional: {
      type: String,
    },
    Postdirectional: {
      type: String,
    },
    CityOrLocality: {
      type: String,
    },
    StateOrProvince: {
      type: String,
    },
    // Legacy
    StateOfProvince: {
      type: String,
    },
    CommonPlaceName: {
      type: String,
    },
    CrossStreet1: {
      type: String,
    },
    CrossStreet2: {
      type: String,
    },
    StreetNumber: {
      type: String,
    },
    Building: {
      type: String,
    },
    Floor: {
      type: String,
    },
    Suite: {
      type: String,
    },
    City: {
      type: String,
    },
    County: {
      type: String,
    },
    PostalCode: {
      type: String,
    },
    CrossStreetName: {
      type: String,
    },
    LocationComment: {
      type: String,
    },
    // TC Address
    full_address: {
      type: String,
    },
    address: {
      type: String,
    },
    cross_streets: {
      type: String,
    },

    // Prior History
    PriorIncidentChanged: {
      type: Boolean,
    },
    PriorIncident: {
      type: [CADPriorIncident],
      default: [],
    },

    // Caller
    CallerNumber: {
      type: String,
      default: "",
    },

    tag: {
      type: String,
      default: "",
    },

    // Coordinate
    Latitude: {
      type: String,
    },
    Longitude: {
      type: String,
    },

    Comment: {
      type: [CADComment],
      default: [],
    },

    units: {
      type: [CADUnit],
      default: [],
    },

    events: {
      type: [IncidentEvent], // setting types as object, because it does not work with importing IncidentEvent
      default: [],
    },

    // Tablet Command Internal fields
    preference_location: {
      type: String,
    },

    // Training
    simulation: {
      type: Boolean,
      default: false,
    },
    notify: {
      type: Boolean,
      default: true,
    },
    rts: {
      type: Boolean,
      default: true,
    },

    // Leaked
    CADSimulator: {
      type: String,
    },

    notificationType: {
      type: [APNNotificationType],
      default: [],
    },
    notifiedUnits: {
      type: [String],
      default: [],
    },
  }, {
    collection: "massive_incident_cad",
    strict: false, // Because we accept all kind of data in
  });
  modelSchema.set("autoIndex", false);

  modelSchema.set("toJSON", {
    virtuals: true,
    versionKey: false,
    transform(doc: ModelFromSchema<typeof modelSchema>, ret: DocumentTypeFromSchema<typeof modelSchema>) {
      // Remove fields that should not be here
      delete (ret as unknown as { apikey: unknown }).apikey;

      strictSchema(doc.schema as typeof modelSchema, ret);

      ret.id = ret._id;
    },
  });

  modelSchema.virtual("id").get(function(this: MongooseDocument) {
    // tslint:disable-next-line: no-unsafe-any
    return this._id.toString();
  });

  const ignoreFields: ReadonlyArray<string> = ["station", "callerNumber"];

  function strictSchema(schema: typeof modelSchema, ret: Record<string, unknown>) {
    Object.keys(ret).forEach(function(element) {
      // Don't complain about the virtuals
      if (element === "id") {
        return;
      }

      if (ignoreFields.indexOf(element) !== -1) {
        delete ret[element];
        return;
      }
      const pathSchema = schema as unknown as { paths: Record<string, string> };
      if (pathSchema.paths[element] === undefined) {
        // console.log("backend-models.cad-incident: undefined schema.paths[element]:", element, pathSchema.paths[element]);
        delete ret[element];
      }
    });
  }
  modelSchema.plugin(mongooseLeanVirtuals);
  return modelSchema;
}

export async function CADIncidentModule(mongoose: MongooseModule) {
  const modelSchema = CADIncidentSchema(mongoose);
  return createModel(mongoose, "CADIncident", modelSchema);
}

export interface CADIncident extends ItemTypeFromTypeSchemaFunction<typeof CADIncidentModule> { }
export interface CADIncidentModel extends ModelTypeFromTypeSchemaFunction<CADIncident> { }
export default CADIncidentModule as ReplaceModelReturnType<typeof CADIncidentModule, CADIncidentModel>;


text:
package java.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.Permission;
import java.security.PermissionCollection;

/**
 * Regulates the access to network operations available through sockets through
 * permissions. A permission consists of a target (a host), and an associated
 * action list. The target should identify the host by either indicating the
 * (possibly wildcarded (eg. {@code .company.com})) DNS style name of the host
 * or its IP address in standard {@code nn.nn.nn.nn} ("dot") notation. The
 * action list can be made up of one or more of the following actions separated
 * by a comma:
 *

 *
connect

 *
requests permission to connect to the host

 *
listen

 *
requests permission to listen for connections from the host

 *
accept

 *
requests permission to accept connections from the host

 *
resolve

 *
requests permission to resolve the hostname

 *

 * Note that {@code resolve} is implied when any (or none) of the others are
 * present.
 *

 * Access to a particular port can be requested by appending a colon and a
 * single digit to the name (eg. {@code .company.com:7000}). A range of port
 * numbers can also be specified, by appending a pattern of the form
 * LOW-HIGH where LOW and HIGH are valid port numbers. If
 * either LOW or HIGH is omitted it is equivalent to entering the
 * lowest or highest possible value respectively. For example:
 *
 *

 * {@code SocketPermission("www.company.com:7000-", "connect,accept")}
 *

 *
 * represents the permission to connect to and accept connections from
 * {@code www.company.com} on ports in the range {@code 7000} to {@code 65535}.
 */
public final class SocketPermission extends Permission implements Serializable {

	private static final long serialVersionUID = -7204263841984476862L;

	// Bit masks for each of the possible actions
	static final int SP_CONNECT = 1;

	static final int SP_LISTEN = 2;

	static final int SP_ACCEPT = 4;

	static final int SP_RESOLVE = 8;

	// list of actions permitted for socket permission in order, indexed by mask
	// value
	@SuppressWarnings("nls")
	private static final String[] actionNames = { "", "connect", "listen", "",
			"accept", "", "", "", "resolve" };

	// If a wildcard is present store the information
	private transient boolean isPartialWild;

	private transient boolean isWild;

	// The highest port number
	private static final int HIGHEST_PORT = 65535;

	// The lowest port number
	private static final int LOWEST_PORT = 0;

	transient String hostName; // Host name as returned by InetAddress

	transient String ipString; // IP address as returned by InetAddress

	transient boolean resolved; // IP address has been resolved

	// the port range;
	transient int portMin = LOWEST_PORT;

	transient int portMax = HIGHEST_PORT;

	private String actions; // List of all actions allowed by this permission

	transient int actionsMask = SP_RESOLVE;

	/**
	 * Constructs a new {@code SocketPermission} instance. The hostname can be a
	 * DNS name, an individual hostname, an IP address or the empty string which
	 * implies {@code localhost}. The port or port range is optional.
	 *

	 * The action list is a comma-separated list which can consists of the
	 * possible operations {@code "connect"}, {@code "listen"}, {@code "accept"}
	 * , and {@code "resolve"}. They are case-insensitive and can be put
	 * together in any order. {@code "resolve"} is implied per default.
	 *
	 * @param host
	 *            the hostname this permission is valid for.
	 * @param action
	 *            the action string of this permission.
	 */
	public SocketPermission(String host, String action) {
		super(host.isEmpty() ? "localhost" : host);
		hostName = getHostString(host);
		if (action == null) {
			throw new NullPointerException();
		}
		if (action.isEmpty()) {
			throw new IllegalArgumentException();
		}

		setActions(action);
		actions = toCanonicalActionString(action);
		// Use host since we are only checking for port presence
		parsePort(host, hostName);
	}

	/**
	 * Compares the argument {@code o} to this instance and returns {@code true}
	 * if they represent the same permission using a class specific comparison.
	 *
	 * @param other
	 *            the object to compare with this {@code SocketPermission}
	 *            instance.
	 * @return {@code true} if they represent the same permission, {@code false}
	 *         otherwise.
	 * @see #hashCode
	 */
	@Override
	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (other == null || this.getClass() != other.getClass()) {
			return false;
		}
		SocketPermission sp = (SocketPermission) other;
		if (!hostName.equalsIgnoreCase(sp.hostName)) {
			if (getIPString(true) == null
					|| !ipString.equalsIgnoreCase(sp.getIPString(true))) {
				return false;
			}
		}
		if (this.actionsMask != SP_RESOLVE) {
			if (this.portMin != sp.portMin) {
				return false;
			}
			if (this.portMax != sp.portMax) {
				return false;
			}
		}
		return this.actionsMask == sp.actionsMask;
	}

	/**
	 * Returns the hash value for this {@code SocketPermission} instance. Any
	 * two objects which returns {@code true} when passed to {@code equals()}
	 * must return the same value as a result of this method.
	 *
	 * @return the hashcode value for this instance.
	 * @see #equals
	 */
	@Override
	public int hashCode() {
		return hostName.hashCode() ^ actionsMask ^ portMin ^ portMax;
	}

	/**
	 * Gets a comma-separated list of all actions allowed by this permission. If
	 * more than one action is returned they follow this order: {@code connect},
	 * {@code listen}, {@code accept}, {@code resolve}.
	 *
	 * @return the comma-separated action list.
	 */
	@Override
	public String getActions() {
		return actions;
	}

	/**
	 * Stores the actions for this permission as a bit field.
	 *
	 * @param actions
	 *            java.lang.String the action list
	 */
	private void setActions(String actions) throws IllegalArgumentException {
		if (actions.isEmpty()) {
			return;
		}
		boolean parsing = true;
		String action;
		StringBuilder sb = new StringBuilder();
		int pos = 0, length = actions.length();
		while (parsing) {
			char c;
			sb.setLength(0);
			while (pos < length && (c = actions.charAt(pos++)) != ',') {
				sb.append(c);
			}
			if (pos == length) {
				parsing = false;
			}
			action = sb.toString().trim().toLowerCase();
			if (action.equals(actionNames[SP_CONNECT])) {
				actionsMask |= SP_CONNECT;
			} else if (action.equals(actionNames[SP_LISTEN])) {
				actionsMask |= SP_LISTEN;
			} else if (action.equals(actionNames[SP_ACCEPT])) {
				actionsMask |= SP_ACCEPT;
			} else if (action.equals(actionNames[SP_RESOLVE])) {
				// do nothing
			} else {
				throw new IllegalArgumentException("Invalid action: " + action);
			}
		}
	}

	/**
	 * Checks whether this {@code SocketPermission} instance allows all actions
	 * which are allowed by the given permission object {@code p}. All argument
	 * permission actions, hosts and ports must be implied by this permission
	 * instance in order to return {@code true}. This permission may imply
	 * additional actions not present in the argument permission.
	 *
	 * @param p
	 *            the socket permission which has to be implied by this
	 *            instance.
	 * @return {@code true} if this permission instance implies all permissions
	 *         represented by {@code p}, {@code false} otherwise.
	 */
	@Override
	public boolean implies(Permission p) {
		SocketPermission sp;
		try {
			sp = (SocketPermission) p;
		} catch (ClassCastException e) {
			return false;
		}

		// tests if the action list of p is the subset of the one of the
		// receiver
		if (sp == null || (actionsMask & sp.actionsMask) != sp.actionsMask) {
			return false;
		}

		// only check the port range if the action string of the current object
		// is not "resolve"
		if (!p.getActions().equals("resolve")) {
			if ((sp.portMin < this.portMin) || (sp.portMax > this.portMax)) {
				return false;
			}
		}

		// Verify the host is valid
		return checkHost(sp);
	}

	/**
	 * Creates a new {@code PermissionCollection} to store
	 * {@code SocketPermission} objects.
	 *
	 * @return the new permission collection.
	 */
	@Override
	public PermissionCollection newPermissionCollection() {
		return new SocketPermissionCollection();
	}

	/**
	 * Parse the port, including the minPort, maxPort
	 *
	 * @param hostPort
	 *            the host[:port] one
	 * @param host
	 *            the host name we just get
	 * @throws IllegalArgumentException
	 *             If the port is not a positive number or minPort is not less
	 *             than or equal maxPort
	 */
	private void parsePort(String hostPort, String host)
			throws IllegalArgumentException {
		String port = hostPort.substring(host.length());
		String emptyString = "";

		if (emptyString.equals(port)) {
			// Not specified
			portMin = 80;
			portMax = 80;
			return;
		}

		if (":*".equals(port)) {
			// The port range should be 0-65535
			portMin = 0;
			portMax = 65535;
			return;
		}

		// Omit ':'
		port = port.substring(1);
		int negIdx = port.indexOf('-');
		String strPortMin = emptyString;
		String strPortMax = emptyString;
		if (-1 == negIdx) {
			// No neg mark, only one number
			strPortMin = port;
			strPortMax = port;
		} else {
			strPortMin = port.substring(0, negIdx);
			strPortMax = port.substring(negIdx + 1);
			if (emptyString.equals(strPortMin)) {
				strPortMin = "0";
			}
			if (emptyString.equals(strPortMax)) {
				strPortMax = "65535";
			}
		}
		try {
			portMin = Integer.valueOf(strPortMin).intValue();
			portMax = Integer.valueOf(strPortMax).intValue();

			if (portMin > portMax) {
				throw new IllegalArgumentException(
						"MinPort is greater than MaxPort: " + port);
			}
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Invalid port number: " + port);
		}
	}

	/**
	 * Creates a canonical action list.
	 *
	 * @param action
	 *            java.lang.String
	 *
	 * @return java.lang.String
	 */
	private String toCanonicalActionString(String action) {
		if (action == null || action.isEmpty() || actionsMask == SP_RESOLVE) {
			return actionNames[SP_RESOLVE]; // If none specified return the
		}
		// implied action resolve
		StringBuilder sb = new StringBuilder();
		if ((actionsMask & SP_CONNECT) == SP_CONNECT) {
			sb.append(',');
			sb.append(actionNames[SP_CONNECT]);
		}
		if ((actionsMask & SP_LISTEN) == SP_LISTEN) {
			sb.append(',');
			sb.append(actionNames[SP_LISTEN]);
		}
		if ((actionsMask & SP_ACCEPT) == SP_ACCEPT) {
			sb.append(',');
			sb.append(actionNames[SP_ACCEPT]);
		}
		sb.append(',');
		sb.append(actionNames[SP_RESOLVE]);// Resolve is always implied
		// Don't copy the first ','.
		return actions = sb.substring(1, sb.length());
	}

	private String getIPString(boolean isCheck) {
		if (!resolved) {
			try {
				ipString = InetAddress.getHostNameInternal(hostName, isCheck);
			} catch (UnknownHostException e) {
				// ignore
			}
			resolved = true;
		}
		return ipString;
	}

	/**
	 * Get the host part from the host[:port] one. The host should be
	 *
	 *

	 *      host = (hostname | IPv4address | IPv6reference | IPv6 in full uncompressed form)
	 *

	 *
	 * The wildcard "*" may be included once in a DNS name host specification.
	 * If it is included, it must be in the leftmost position
	 *
	 * @param host
	 *            the {@code host[:port]} string.
	 * @return the host name.
	 * @throws IllegalArgumentException
	 *             if the host is invalid.
	 */
	private String getHostString(String host) throws IllegalArgumentException {
		host = host.trim();
		int idx = -1;
		idx = host.indexOf(':');
		isPartialWild = (host.length() > 0 && host.charAt(0) == '*');
		if (isPartialWild) {
			resolved = true;
			isWild = (host.length() == 1);
			if (isWild) {
				return host;
			}
			if (idx > -1) {
				host = host.substring(0, idx);
			}
			return host.toLowerCase();
		}

		int lastIdx = host.lastIndexOf(':');

		if (idx == lastIdx) {
			if (-1 != idx) {
				// only one colon, should be port
				host = host.substring(0, idx);
			}
			return host.toLowerCase();
		}
		// maybe ipv6
		boolean isFirstBracket = (host.charAt(0) == '[');
		if (!isFirstBracket) {
			// No bracket, should be in full form
			int colonNum = 0;
			for (int i = 0; i < host.length(); ++i) {
				if (host.charAt(i) == ':') {
					colonNum++;
				}
			}
			// Get rid of the colon before port
			if (8 == colonNum) {
				host = host.substring(0, lastIdx);
			}
			if (isIP6AddressInFullForm(host)) {
				return host.toLowerCase();
			}
			throw new IllegalArgumentException("Invalid port number: " + host);
		}
		// forward bracket found
		int bbracketIdx = host.indexOf(']');
		if (-1 == bbracketIdx) {
			// no back bracket found, wrong
			throw new IllegalArgumentException("Invalid port number: " + host);
		}
		host = host.substring(0, bbracketIdx + 1);
		if (isValidIP6Address(host)) {
			return host.toLowerCase();
		}
		throw new IllegalArgumentException("Invalid port number: " + host);
	}

	private static boolean isValidHexChar(char c) {
		return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
				|| (c >= 'a' && c <= 'f');
	}

	private static boolean isValidIP4Word(String word) {
		char c;
		if (word.length() < 1 || word.length() > 3) {
			return false;
		}
		for (int i = 0; i < word.length(); i++) {
			c = word.charAt(i);
			if (!(c >= '0' && c <= '9')) {
				return false;
			}
		}
		if (Integer.parseInt(word) > 255) {
			return false;
		}
		return true;
	}

	private static boolean isIP6AddressInFullForm(String ipAddress) {
		if (isValidIP6Address(ipAddress)) {
			int doubleColonIndex = ipAddress.indexOf("::");
			if (doubleColonIndex >= 0) {
				// Simplified form which contains ::
				return false;
			}
			return true;
		}
		return false;
	}

	private static boolean isValidIP6Address(String ipAddress) {
		int length = ipAddress.length();
		boolean doubleColon = false;
		int numberOfColons = 0;
		int numberOfPeriods = 0;
		int numberOfPercent = 0;
		String word = "";
		char c = 0;
		char prevChar = 0;
		int offset = 0; // offset for [] IP addresses

		if (length < 2) {
			return false;
		}

		for (int i = 0; i < length; i++) {
			prevChar = c;
			c = ipAddress.charAt(i);
			switch (c) {

			// case for an open bracket [x:x:x:...x]
			case '[':
				if (i != 0) {
					return false; // must be first character
				}
				if (ipAddress.charAt(length - 1) != ']') {
					return false; // must have a close ]
				}
				offset = 1;
				if (length < 4) {
					return false;
				}
				break;

			// case for a closed bracket at end of IP [x:x:x:...x]
			case ']':
				if (i != length - 1) {
					return false; // must be last character
				}
				if (ipAddress.charAt(0) != '[') {
					return false; // must have a open [
				}
				break;

			// case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d
			case '.':
				numberOfPeriods++;
				if (numberOfPeriods > 3) {
					return false;
				}
				if (!isValidIP4Word(word)) {
					return false;
				}
				if (numberOfColons != 6 && !doubleColon) {
					return false;
				}
				// a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an
				// IPv4 ending, otherwise 7 :'s is bad
				if (numberOfColons == 7 && ipAddress.charAt(0 + offset) != ':'
						&& ipAddress.charAt(1 + offset) != ':') {
					return false;
				}
				word = "";
				break;

			case ':':
				numberOfColons++;
				if (numberOfColons > 7) {
					return false;
				}
				if (numberOfPeriods > 0) {
					return false;
				}
				if (prevChar == ':') {
					if (doubleColon) {
						return false;
					}
					doubleColon = true;
				}
				word = "";
				break;
			case '%':
				if (numberOfColons == 0) {
					return false;
				}
				numberOfPercent++;

				// validate that the stuff after the % is valid
				if ((i + 1) >= length) {
					// in this case the percent is there but no number is
					// available
					return false;
				}
				try {
					Integer.parseInt(ipAddress.substring(i + 1));
				} catch (NumberFormatException e) {
					// right now we just support an integer after the % so if
					// this is not
					// what is there then return
					return false;
				}
				break;

			default:
				if (numberOfPercent == 0) {
					if (word.length() > 3) {
						return false;
					}
					if (!isValidHexChar(c)) {
						return false;
					}
				}
				word += c;
			}
		}

		// Check if we have an IPv4 ending
		if (numberOfPeriods > 0) {
			if (numberOfPeriods != 3 || !isValidIP4Word(word)) {
				return false;
			}
		} else {
			// If we're at then end and we haven't had 7 colons then there is a
			// problem unless we encountered a doubleColon
			if (numberOfColons != 7 && !doubleColon) {
				return false;
			}

			// If we have an empty word at the end, it means we ended in either
			// a : or a .
			// If we did not end in :: then this is invalid
			if (numberOfPercent == 0) {
				if (word == "" && ipAddress.charAt(length - 1 - offset) == ':'
						&& ipAddress.charAt(length - 2 - offset) != ':') {
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Determines whether or not this permission could refer to the same host as
	 * sp.
	 */
	boolean checkHost(SocketPermission sp) {
		if (isPartialWild) {
			if (isWild) {
				return true; // Match on any host
			}
			int length = hostName.length() - 1;
			return sp.hostName.regionMatches(sp.hostName.length() - length,
					hostName, 1, length);
		}
		// The ipString may not be the same, some hosts resolve to
		// multiple ips
		return (getIPString(false) != null && ipString.equals(sp
				.getIPString(false))) || hostName.equals(sp.hostName);
	}

	private void writeObject(ObjectOutputStream stream) throws IOException {
		stream.defaultWriteObject();
	}

	private void readObject(ObjectInputStream stream) throws IOException,
			ClassNotFoundException {
		stream.defaultReadObject();
		// Initialize locals
		isPartialWild = false;
		isWild = false;
		portMin = LOWEST_PORT;
		portMax = HIGHEST_PORT;
		actionsMask = SP_RESOLVE;
		hostName = getHostString(getName());
		parsePort(getName(), hostName);
		setActions(actions);
	}
}


text:
package org.mifos.framework.util.helpers;

public interface ExceptionConstants {
    String CFGFILENOTFOUND = "exceptions.hibernate.systemexception.cfgfilenotfound";
    String HIBERNATEPROPNOTFOUND = "exceptions.hibernate.systemexception.hibernatepropnotfound";
    String CONFIGPATHNOTFOUND = "exceptions.hibernate.systemexception.configpathnotfound";
    String SYSTEMEXCEPTION = "exception.framework.SystemException";
    String CONCURRENCYEXCEPTION = "exception.framework.ConcurrencyException";
    String DOUBLESUBMITEXCEPTION = "exception.framework.DoubleSubmitException";
    String SERVICEEXCEPTION = "exception.framework.ServiceException";
    String ILLEGALMONEYOPERATION = "The desired operation on money class is not possible because the two money objects are of different currencies.";
    String FRAMEWORKRUNTIMEEXCEPTION = "exception.framework.FrameworkRuntimeException";
    String CONSTANTSNOTLOADEDEXCEPTION = "exception.framework.ConstantsNotLoadedException";
    String STARTUP_EXCEPTION = "exception.framework.StartUpException";
    String ENUMSNOTLOADEDEXCEPTION = "exception.framework.EnumsNotLoadedException";
    String PAGEEXPIREDEXCEPTION = "exception.framework.PageExpiredException";
    String PERMISSIONFAILUREEXCEPTION = "exception.framework.permission";
    String CURRENCY_MUST_NOT_BE_NULL ="Currency must not be null";
    String AMMOUNT_MUST_NOT_BE_NULL = "Amount must not be null";
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<prerequisites>
		<maven>3.0</maven>
	</prerequisites>

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hashvoid.crossbinder</groupId>
	<artifactId>com.hashvoid.crossbinder-parent</artifactId>
	<version>0.4-SNAPSHOT</version>
	<name>Crossbinder Parent</name>
	<description>Parent project for all submodules under Crossbinder</description>
	<packaging>pom</packaging>

	<scm>
		<url>https://github.com/hashvoid/crossbinder.git</url>
		<connection>scm:git:https://github.com/hashvoid/crossbinder.git</connection>
	</scm>

	<modules>
		<module>crossbinder-hod</module>
		<module>crossbinder-extern</module>
		<module>crossbinder-commons-config</module>
		<module>crossbinder-jackson</module>
		<module>crossbinder-servlet</module>
		<module>crossbinder-dropwizard</module>
	</modules>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.4</version>
				<executions>
					<execution>
						<id>javadoc</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
						</execution>
				</executions>
				<configuration>
					<aggregate>false</aggregate>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>3.0.1</version>
				<configuration>
					<attach>false</attach>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.3</version>
				<configuration>
					<useReleaseProfile>false</useReleaseProfile>
					<releaseProfiles>release</releaseProfiles>
					<autoVersionSubmodules>true</autoVersionSubmodules>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<distributionManagement>
		<repository>
			<id>randondiesel-release</id>
			<url>http://randondiesel.com/artifactory/release</url>
		</repository>
		<snapshotRepository>
			<id>randondiesel-snapshot</id>
			<url>http://randondiesel.com/artifactory/snapshot</url>
		</snapshotRepository>
	</distributionManagement>

</project>