text:
/**
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
.img-with-shadow img, img.with-shadow {
	-moz-box-shadow: 3px 3px 4px #333;
	-webkit-box-shadow: 3px 3px 4px #333;
	box-shadow: 3px 3px 4px #333;
}

img.no-shadow {
	-moz-box-shadow: none;
	-webkit-box-shadow: none;
	box-shadow: none;
}

/** placement break **/
.block.wide {
	width: 100%;
}

img {
	display:block;
}
.block.wide img {float:none; }
.block.wide img.right {
	margin-left:auto;
}

.block.wide img.center {
	margin:0 auto;
}

img.right {float:right;
	margin:0 0 0 10px;
}
img.left {
	float:left;
	margin:0 10px 10px 0;
}

/* Use @frame to create frames on figures */
.figborder {
	border-style: solid;
	padding-left: 3px;
	border-width: 2px;
	padding-right: 3px;
	margin-top: 1em;
	border-color: Silver;
}

.figsides {
	border-left: 2px solid;
	padding-left: 3px;
	border-right: 2px solid;
	padding-right: 3px;
	margin-top: 1em;
	border-color: Silver;
}

.figtop {
	border-top: 2px solid;
	margin-top: 1em;
	border-color: Silver;
}

.figbottom {
	border-bottom: 2px solid;
	border-color: Silver;
}

.figtopbot {
	border-top: 2px solid;
	border-bottom: 2px solid;
	margin-top: 1em;
	border-color: Silver;
}

img + p {
	margin-top: 3em;
}

/* Default of italics to set apart figure captions */
.figcap {
	font-style: italic;
}

.figdesc {
	font-style: normal;
}

span.figcap {
	display: block;
	text-align: center;
	width: 100%;
	font-weight: bold;
	margin: 0.8em 0 2em 0;
}

.d4p-ui-cycle img {
	display:block;
}


text:
<?php

/**
* RecursiveFile
*/
class RecursiveFileFilterIterator extends FilterIterator
{
    protected $ext = ['jpg', 'gif'];

    function __construct($path)
    {
        parent::__construct(
            new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path)));
    }

    public function accept()
    {
        $item = $this->getInnerIterator();
        if ($item->isFile() && in_array(pathinfo($time->getFilename()), PATHINFO_EXTENSION), $this->ext) {
            return ture;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_Factory
{
    class Blacksmith
    {
        public Weapon buildWeapon(string weaponType) {
            if (weaponType == "dagger") {
                Dagger newDagger = new Dagger();
                return newDagger;
            }
            else if (weaponType == "sword") {
                Sword newSword = new Sword();
                return newSword;
            }
            else if (weaponType == "lance") {
                Lance newLance = new Lance();
                return newLance;
            }

            return null;
        }
    }
}


text:
require_relative 'user'

class Customer < User
  include TypeCast

  type_cast :expires_at, DateTime
  type_cast :created_at, :updated_at, Time
  type_cast :orders_count, :suggestions_count, :to_i
  type_cast :aov, :to_f
  type_cast :dynamic_created_at, Time
end


text:
package org.apache.lucene.queryparser.flexible.standard.builders;

import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.apache.lucene.queryparser.flexible.core.builders.QueryTreeBuilder;
import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode;
import org.apache.lucene.search.Query;

/**
 * This interface should be implemented by every class that wants to build
 * {@link Query} objects from {@link QueryNode} objects.
 *
 * @see QueryBuilder
 * @see QueryTreeBuilder
 */
public interface StandardQueryBuilder extends QueryBuilder {

  @Override
  public Query build(QueryNode queryNode) throws QueryNodeException;

}


text:
'use strict'

/* global notie  */

import { notieAlert$ } from './settingsPage'

function showNotie(alertType, alertMessage, duration) {
  var classToAdd = alertType === 3 ? 'notie-alert-error' : 'notie-alert-success'
  notieAlert$.removeClass('notie-alert-success notie-alert-error')
  notieAlert$.addClass(classToAdd)
  notie.alert(alertType, alertMessage, duration)
}

export { showNotie }


text:
<?php if ( ! defined('BASEPATH')) exit('Direct access forbidden.');

class Image
{
	private $sourceImage;
	private $newImagePath;
	private $newImageType;
	private $quality		= 60;
	private $aspectRatio	= TRUE;

	private $errorString;
	private $errorStatus	= FALSE;
	private $errorCode		= 0;
	private $result;

	private $gdImage;
	private $width;
	private $minWidth;
	private $height;
	private $minHeight;
	private $sourceWidth;
	private $sourceHeight;
	private $sourceType;
	private $newWidth;
	private $newHeight;

	public function __construct($settings = array())
	{
		if(!extension_loaded('GD'))
		{
			$this->errorStatus		= TRUE;
			throw new Exception(Corelanguage::IMAGE_GD_NOT_FOUND);
		}

		if(isset($settings['sourceImage']))
		{
			$this->sourceImage		= $settings['sourceImage'];
			if(!file_exists($this->sourceImage))
			{
				$this->errorStatus		= TRUE;
				throw new Exception(Corelanguage::IMAGE_SOURCE_FILE_NOT_FOUNT);
			}
		}

		if(isset($settings['newImagePath'])){$this->newImagePath=$settings['newImagePath'];}
		if(isset($settings['aspectRatio'])){$this->aspectRatio=$settings['aspectRatio'];}
		if(isset($settings['quality'])){$this->quality=$settings['quality'];}
		if(isset($settings['imageType'])){$this->newImageType=$settings['imageType'];}

		$this->result		= new stdClass();
	}

	public function reConfig($settings = array())
	{
		if(isset($settings['sourceImage']))
		{
			$this->sourceImage		= $settings['sourceImage'];
			if(!file_exists($this->sourceImage))
			{
				$this->errorStatus		= TRUE;
				throw new Exception(Corelanguage::IMAGE_SOURCE_FILE_NOT_FOUNT);
			}
		}

		if(isset($settings['newImagePath'])){$this->newImagePath=$settings['newImagePath'];}else{unset($this->newImagePath);}
		if(isset($settings['aspectRatio'])){$this->aspectRatio=$settings['aspectRatio'];}else{$this->aspectRatio=TRUE;}
		if(isset($settings['quality'])){$this->quality=$settings['quality'];}else{$this->quality=60;}
		if(isset($settings['imageType'])){$this->newImageType=$settings['imageType'];}

		$this->result		= new stdClass();
	}

	public function error()
	{
		$response			= new stdClass();
		$response->error	= $this->errorStatus;
		$response->message	= $this->errorString;
		$response->errCode	= $this->errorCode;
		return $response;
	}

	public function resize($newWidth, $newHeight, $minWidth = 0, $minHeight = 0)
	{
		if(!isset($this->sourceImage))
		{
			throw new Exception(Corelanguage::IMAGE_SOURCE_FILE_NOT_FOUNT);
		}else{

			$this->width		= $newWidth;
			$this->height		= $newHeight;
			$this->minWidth		= $minWidth;
			$this->minHeight	= $minHeight;
			$sourceInfo			= getimagesize($this->sourceImage);
			$this->sourceWidth	= $sourceInfo[0];
			$this->sourceHeight	= $sourceInfo[1];
			$this->sourceType	= $sourceInfo['mime'];
			$this->gdImage		= $this->createTemporaryImage();
			$resizedImage		= $this->createEmptyImage();

			if($this->gdImage && $resizedImage)
			{
				if($this->sourceType == 'image/png')
				{
					imagealphablending($this->gdImage, TRUE);
					imagealphablending($resizedImage, FALSE);
					imagesavealpha($resizedImage, TRUE);
				}

				$resizeStatus	= @imagecopyresampled($resizedImage, $this->gdImage, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->sourceWidth, $this->sourceHeight);
				if(!$resizeStatus)
				{
					$this->errorStatus	= TRUE;
					$this->errorString	= Corelanguage::IMAGE_NOT_RESIZEING;
					$this->errorCode	= 102;
				}else{
					$this->saveImage($resizedImage);
				}
			}
		}
	}

	public function cropImage($width, $height)
	{
		if(!isset($this->sourceImage))
		{
			throw new Exception(Corelanguage::IMAGE_SOURCE_FILE_NOT_FOUNT);
		}else{

			$this->width		= $width;
			$this->height		= $height;
			$this->minWidth		= 0;
			$this->minHeight	= 0;
			$this->aspectRatio	= false;
			$sourceInfo			= getimagesize($this->sourceImage);
			$this->sourceWidth	= $sourceInfo[0];
			$this->sourceHeight	= $sourceInfo[1];
			$this->sourceType	= $sourceInfo['mime'];
			$this->gdImage		= $this->createTemporaryImage();
			//$croppedImage		= $this->createEmptyImage();

			if($this->gdImage)
			{
				$destX				= floor(($this->sourceWidth - $this->width) / 2);
				$destY				= floor(($this->sourceHeight - $this->height) / 2);
				$croppedImageData	= array('x' => $destX , 'y' => $destY, 'width' => $this->width, 'height'=> $this->height);
				$croppedImage		= imagecrop($this->gdImage, $croppedImageData);

				if($this->sourceType == 'image/png')
				{
					imagealphablending($this->gdImage, TRUE);
					imagealphablending($croppedImage, FALSE);
					imagesavealpha($croppedImage, TRUE);
				}

				/*$resizeStatus	= @imagecopyresampled($croppedImage, $this->gdImage, 0, 0, $destX, $destY, $this->newWidth, $this->newHeight, $this->sourceWidth, $this->sourceHeight);
				if(!$resizeStatus)
				{
					$this->errorStatus	= TRUE;
					$this->errorString	= Corelanguage::IMAGE_NOT_RESIZEING;
					$this->errorCode	= 102;
				}else{
					$this->saveImage($croppedImage);
				}*/
				$this->saveImage($croppedImage);
			}
		}
	}

	public function getLastDimensions()
	{
		$response			= new stdClass();
		$response->width	= round($this->newWidth);
		$response->height	= round($this->newHeight);

		return $response;
	}

	private function createTemporaryImage()
	{
		switch($this->sourceType)
		{
		default:
			$this->errorStatus	= TRUE;
			$this->errorString	= Corelanguage::IMAGE_TYPE_NOT_SUPPORTED;
			$this->errorCode	= 100;
			return FALSE;
		break;
		case 'image/jpeg':
			return @imagecreatefromjpeg($this->sourceImage);
		break;
		case 'image/pjpeg':
			return @imagecreatefromjpeg($this->sourceImage);
		break;
		case 'image/gif':
			return @imagecreatefromgif($this->sourceImage);
		break;
		case 'image/png':
			return @imagecreatefrompng($this->sourceImage);
		break;
		}
	}

	private function createEmptyImage()
	{
		if($this->aspectRatio)
		{
			$ratio		= $this->sourceWidth / $this->sourceHeight;

			if(($this->minWidth > 0) || ($this->minHeight > 0))
			{
				$newWidth			= $this->width;
				$aspectWidth		= $ratio * $this->height;
				$newHeight			= $this->height;
				$aspectHeight		= $this->width / $ratio;

				$targetWidth		= $newWidth;
				$targetHeight		= $aspectHeight;
				$resizeCalculated	= false;

				if(($targetHeight < $this->minHeight) && ($this->minHeight > 0) && !$resizeCalculated)
				{
					$targetWidth	= $aspectWidth;
					$targetHeight	= $newHeight;
				}

				$this->newWidth		= $targetWidth;
				$this->newHeight	= $targetHeight;
			}else{
				$newWidth	= $this->width;
				$newHeight	= $newWidth / $ratio;

				$this->newWidth		= $newWidth;
				$this->newHeight	= $newHeight;
			}
		}else{
			$this->newWidth		= $this->width;
			$this->newHeight	= $this->height;
		}

		return imagecreatetruecolor($this->newWidth, $this->newHeight);
	}

	private function saveImage($image)
	{
		if(!empty($this->newImagePath))
		{
			$fileName	= $this->newImagePath;
		}else{
			$fileName	= $this->sourceImage;
			@chmod($fileName, 0775);
		}

		$imageType	= ($this->newImageType)?$this->newImageType:$this->sourceType;

		switch($imageType)
		{
		default:
			$this->errorStatus	= TRUE;
			$this->errorString	= Corelanguage::IMAGE_TYPE_NOT_SUPPORTED;
			$this->errorCode	= 100;
		break;
		case 'image/jpeg':
			$imageStatus	= @imagejpeg($image, $fileName, $this->quality);
		break;
		case 'image/gif':
			$imageStatus	= @imagegif($image, $fileName);
		break;
		case 'image/png':
			$tmpQuality		= ($this->quality > 9)?9:$this->quality;
			imagealphablending($image, FALSE);
			imagesavealpha($image, TRUE);
			$imageStatus	= @imagepng($image, $fileName, $tmpQuality);
		break;
		}

		if(!$this->errorStatus && !$imageStatus)
		{
			$this->errorStatus	= TRUE;
			$this->errorString	= Corelanguage::IMAGE_SAVE_ERROR;
			$this->errorCode	= 103;
		}else{
			@chmod($fileName, 0644);
		}
	}
}


text:
#if !defined(BOOST_SPIRIT_WRAP_ACTION_APR_19_2008_0103PM)
#define BOOST_SPIRIT_WRAP_ACTION_APR_19_2008_0103PM

#include <boost/spirit/home/support/detail/values.hpp>
#include <boost/spirit/home/phoenix/core/actor.hpp>
#include <boost/spirit/home/phoenix/core/argument.hpp>
#include <boost/spirit/home/phoenix/bind.hpp>
#include <boost/spirit/home/phoenix/scope.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace lex { namespace detail
{
    template <typename FunctionType, typename Attribute, typename Context>
    struct wrap_action
    {
        // plain functions with 4 arguments and function objects are not
        // touched at all
        template <typename F>
        static FunctionType call(F const& f)
        {
            return f;
        }

        // wrap phoenix actor, make sure first argument is a fusion sequence
        struct phoenix_action
        {
            template <typename F, typename T1, typename T2, typename T3, typename T4>
            struct result { typedef void type; };

            template <typename Eval>
            void
            operator()(phoenix::actor<Eval> const& f, Attribute const& attr,
                std::size_t id, bool& pass, Context& ctx) const
            {
                f (spirit::detail::pass_value<Attribute const>::call(attr),
                    id, pass, ctx);
            }
        };

        template <typename Eval>
        static FunctionType call(phoenix::actor<Eval> const& f)
        {
            using phoenix::arg_names::_1;
            using phoenix::arg_names::_2;
            using phoenix::arg_names::_3;
            using phoenix::arg_names::_4;
            return phoenix::bind(phoenix_action(), phoenix::lambda[f],
                _1, _2, _3, _4);
        }

        // semantic actions with 3 arguments
        template <typename F>
        static void arg3_action(F* f, Attribute const& attr,
            std::size_t id, bool& pass, Context&)
        {
            f(attr, id, pass);
        }

        template <typename A0, typename A1, typename A2>
        static FunctionType call(void(*f)(A0, A1, A2))
        {
            void (*pf)(void(*)(A0, A1, A2), Attribute const&, std::size_t,
                bool&, Context&) = &wrap_action::arg3_action;

            using phoenix::arg_names::_1;
            using phoenix::arg_names::_2;
            using phoenix::arg_names::_3;
            return phoenix::bind(pf, f, _1, _2, _3);
        }

        // semantic actions with 2 arguments
        template <typename F>
        static void arg2_action(F* f, Attribute const& attr,
            std::size_t id, bool&, Context&)
        {
            f(attr, id);
        }

        template <typename A0, typename A1>
        static FunctionType call(void(*f)(A0, A1))
        {
            void (*pf)(void(*)(A0, A1), Attribute const&, std::size_t,
                bool&, Context&) = &wrap_action::arg2_action;

            using phoenix::arg_names::_1;
            using phoenix::arg_names::_2;
            return phoenix::bind(pf, f, _1, _2);
        }

        // semantic actions with 1 argument
        template <typename F>
        static void arg1_action(F* f, Attribute const& attr,
            std::size_t, bool&, Context&)
        {
            f(attr);
        }

        template <typename A0>
        static FunctionType call(void(*f)(A0))
        {
            void (*pf)(void(*)(A0), Attribute const&, std::size_t,
                bool&, Context&) = &arg1_action;

            using phoenix::arg_names::_1;
            return phoenix::bind(pf, f, _1);
        }

        // semantic actions with 0 argument
        template <typename F>
        static void arg0_action(F* f, Attribute const&,
            std::size_t, bool&, Context&)
        {
            f();
        }

        static FunctionType call(void(*f)())
        {
            void (*pf)(void(*)(), Attribute const&, std::size_t,
                bool&, Context&) = &arg0_action;

            using phoenix::arg_names::_1;
            return phoenix::bind(pf, f, _1);
        }
    };

    // specialization allowing to skip wrapping for lexer types not supporting
    // semantic actions
    template <typename Attribute, typename Context>
    struct wrap_action<unused_type, Attribute, Context>
    {
        // plain functors are not touched at all
        template <typename F>
        static F const& call(F const& f)
        {
            return f;
        }
    };

}}}}

#endif


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="description" content="">
      <meta name="author" content="">
      <title>Heroic Features - Start Bootstrap Template</title>

      <link href="./dist/css/bootstrap.css" rel="stylesheet">
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
         rel="stylesheet">

registro

paso 4/4 datos establecimiento comercial

          <form action="">

                 Crear contraseña
                 <input type="password" class="form-control">

                 Confirmar contraseña
                 <input type="password" class="form-control">

                 <button type="submit" class="btn btn-default btn-lg  sign-in-btn-go btn-block">Finalizar</button>

            </form>


text:
from __future__ import absolute_import

from st2client.models.reactor import Rule
from st2client.commands import resource
from st2client.formatters import table

class RuleBranch(resource.ResourceBranch):
    def __init__(self, description, app, subparsers, parent_parser=None):
        super(RuleBranch, self).__init__(
            Rule,
            description,
            app,
            subparsers,
            parent_parser=parent_parser,
            commands={
                "list": RuleListCommand,
                "get": RuleGetCommand,
                "update": RuleUpdateCommand,
                "delete": RuleDeleteCommand,
            },
        )

        self.commands["enable"] = RuleEnableCommand(
            self.resource, self.app, self.subparsers
        )
        self.commands["disable"] = RuleDisableCommand(
            self.resource, self.app, self.subparsers
        )

class RuleListCommand(resource.ResourceTableCommand):
    display_attributes = ["ref", "pack", "description", "enabled"]
    display_attributes_iftt = ["ref", "trigger.ref", "action.ref", "enabled"]

    def __init__(self, resource, *args, **kwargs):

        self.default_limit = 50

        super(RuleListCommand, self).__init__(
            resource,
            "list",
            "Get the list of the %s most recent %s."
            % (self.default_limit, resource.get_plural_display_name().lower()),
            *args,
            **kwargs,
        )

        self.resource_name = resource.get_plural_display_name().lower()
        self.group = self.parser.add_argument_group()
        self.parser.add_argument(
            "-n",
            "--last",
            type=int,
            dest="last",
            default=self.default_limit,
            help=(
                "List N most recent %s. Use -n -1 to fetch the full result \
                                       set."
                % self.resource_name
            ),
        )
        self.parser.add_argument(
            "--iftt",
            action="store_true",
            help="Show trigger and action in display list.",
        )
        self.parser.add_argument(
            "-p",
            "--pack",
            type=str,
            help=("Only return resources belonging to the" " provided pack"),
        )
        self.group.add_argument(
            "-c", "--action", help="Action reference to filter the list."
        )
        self.group.add_argument(
            "-g", "--trigger", help="Trigger type reference to filter the list."
        )
        self.enabled_filter_group = self.parser.add_mutually_exclusive_group()
        self.enabled_filter_group.add_argument(
            "--enabled", action="store_true", help="Show rules that are enabled."
        )
        self.enabled_filter_group.add_argument(
            "--disabled", action="store_true", help="Show rules that are disabled."
        )

    @resource.add_auth_token_to_kwargs_from_cli
    def run(self, args, **kwargs):
        # Filtering options
        if args.pack:
            kwargs["pack"] = args.pack
        if args.action:
            kwargs["action"] = args.action
        if args.trigger:
            kwargs["trigger"] = args.trigger
        if args.enabled:
            kwargs["enabled"] = True
        if args.disabled:
            kwargs["enabled"] = False
        if args.iftt:
            # switch attr to display the trigger and action
            args.attr = self.display_attributes_iftt

        include_attributes = self._get_include_attributes(args=args)
        if include_attributes:
            include_attributes = ",".join(include_attributes)
            kwargs["params"] = {"include_attributes": include_attributes}

        return self.manager.query_with_count(limit=args.last, **kwargs)

    def run_and_print(self, args, **kwargs):
        instances, count = self.run(args, **kwargs)
        if args.json or args.yaml:
            self.print_output(
                instances,
                table.MultiColumnTable,
                attributes=args.attr,
                widths=args.width,
                json=args.json,
                yaml=args.yaml,
            )
        else:
            self.print_output(
                instances,
                table.MultiColumnTable,
                attributes=args.attr,
                widths=args.width,
            )

            if args.last and count and count > args.last:
                table.SingleRowTable.note_box(self.resource_name, args.last)

class RuleGetCommand(resource.ContentPackResourceGetCommand):
    display_attributes = ["all"]
    attribute_display_order = [
        "id",
        "uid",
        "ref",
        "pack",
        "name",
        "description",
        "enabled",
    ]

class RuleUpdateCommand(resource.ContentPackResourceUpdateCommand):
    pass

class RuleEnableCommand(resource.ContentPackResourceEnableCommand):
    display_attributes = ["all"]
    attribute_display_order = [
        "id",
        "ref",
        "pack",
        "name",
        "enabled",
        "description",
        "enabled",
    ]

class RuleDisableCommand(resource.ContentPackResourceDisableCommand):
    display_attributes = ["all"]
    attribute_display_order = [
        "id",
        "ref",
        "pack",
        "name",
        "enabled",
        "description",
        "enabled",
    ]

class RuleDeleteCommand(resource.ContentPackResourceDeleteCommand):
    pass


text:
package org.cp.semaphores.fractal.beans;

import com.google.common.base.Objects;

/**
 * {@code FractalConstant} is an immutable {@link org.cp.semaphores.fractal.beans.FractalBean}
 *
 * @author kornicameister
 * @version 0.0.1
 * @since 0.0.1
 */
public class FractalConstant
        extends AbstractFractalBean {

    public FractalConstant(final String var) {
        super(var);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                      .addValue(symbol)
                      .toString();
    }
}


text:
package org.apereo.portal.portlets.portletadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.WindowState;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBElement;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.pluto.container.PortletContainerException;
import org.apache.pluto.container.driver.PortalDriverContainerServices;
import org.apache.pluto.container.driver.PortletRegistryService;
import org.apache.pluto.container.om.portlet.DisplayName;
import org.apache.pluto.container.om.portlet.PortletApplicationDefinition;
import org.apache.pluto.container.om.portlet.PortletDefinition;
import org.apache.pluto.container.om.portlet.Supports;
import org.apereo.portal.EntityIdentifier;
import org.apereo.portal.api.portlet.DelegateState;
import org.apereo.portal.api.portlet.DelegationActionResponse;
import org.apereo.portal.api.portlet.PortletDelegationDispatcher;
import org.apereo.portal.api.portlet.PortletDelegationLocator;
import org.apereo.portal.groups.IEntityGroup;
import org.apereo.portal.groups.IGroupMember;
import org.apereo.portal.io.xml.portlet.IPortletPublishingService;
import org.apereo.portal.layout.dlm.remoting.IGroupListHelper;
import org.apereo.portal.layout.dlm.remoting.JsonEntityBean;
import org.apereo.portal.portlet.PortletUtils;
import org.apereo.portal.portlet.dao.jpa.PortletDefinitionImpl;
import org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl;
import org.apereo.portal.portlet.delegation.jsp.RenderPortletTag;
import org.apereo.portal.portlet.om.IPortletDefinition;
import org.apereo.portal.portlet.om.IPortletPreference;
import org.apereo.portal.portlet.om.IPortletType;
import org.apereo.portal.portlet.om.IPortletWindowId;
import org.apereo.portal.portlet.om.PortletCategory;
import org.apereo.portal.portlet.om.PortletLifecycleState;
import org.apereo.portal.portlet.registry.IPortletCategoryRegistry;
import org.apereo.portal.portlet.registry.IPortletDefinitionRegistry;
import org.apereo.portal.portlet.registry.IPortletTypeRegistry;
import org.apereo.portal.portlet.rendering.IPortletRenderer;
import org.apereo.portal.portletpublishing.xml.MultiValuedPreferenceInputType;
import org.apereo.portal.portletpublishing.xml.Parameter;
import org.apereo.portal.portletpublishing.xml.ParameterInputType;
import org.apereo.portal.portletpublishing.xml.PortletPublishingDefinition;
import org.apereo.portal.portletpublishing.xml.Preference;
import org.apereo.portal.portletpublishing.xml.PreferenceInputType;
import org.apereo.portal.portletpublishing.xml.SingleValuedPreferenceInputType;
import org.apereo.portal.portletpublishing.xml.Step;
import org.apereo.portal.portlets.Attribute;
import org.apereo.portal.portlets.BooleanAttribute;
import org.apereo.portal.portlets.StringListAttribute;
import org.apereo.portal.portlets.fragmentadmin.FragmentAdministrationHelper;
import org.apereo.portal.portlets.groupselector.EntityEnum;
import org.apereo.portal.portlets.portletadmin.xmlsupport.IChannelPublishingDefinitionDao;
import org.apereo.portal.security.AuthorizationPrincipalHelper;
import org.apereo.portal.security.IAuthorizationPrincipal;
import org.apereo.portal.security.IAuthorizationService;
import org.apereo.portal.security.IPermission;
import org.apereo.portal.security.IPermissionManager;
import org.apereo.portal.security.IPerson;
import org.apereo.portal.security.IUpdatingPermissionManager;
import org.apereo.portal.security.PermissionHelper;
import org.apereo.portal.services.GroupService;
import org.apereo.portal.url.IPortalUrlBuilder;
import org.apereo.portal.url.IPortalUrlProvider;
import org.apereo.portal.url.IPortletUrlBuilder;
import org.apereo.portal.url.UrlType;
import org.apereo.portal.utils.ComparableExtractingComparator;
import org.apereo.portal.utils.Tuple;
import org.apereo.portal.xml.PortletDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import org.springframework.webflow.context.ExternalContext;

/** Helper methods for the portlet administration workflow. */
@Service
public final class PortletAdministrationHelper implements ServletContextAware {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET = "fragment-admin";

    /**
     * Enumeration of the portlet-related permissions that may be managed in the Portlet Manager.
     *
     * @since 5.0
     */
    /* package-private */ enum PortletPermissionsOnForm {
        SUBSCRIBE(IPermission.PORTAL_SUBSCRIBE, IPermission.PORTLET_SUBSCRIBER_ACTIVITY),
        BROWSE(IPermission.PORTAL_SUBSCRIBE, IPermission.PORTLET_BROWSE_ACTIVITY),
        CONFIGURE(IPermission.PORTAL_PUBLISH, IPermission.PORTLET_MODE_CONFIG);

        private final String owner;
        private final String activity;

        PortletPermissionsOnForm(String owner, String activity) {
            this.owner = owner;
            this.activity = activity;
        }

        public String getOwner() {
            return owner;
        }

        public String getActivity() {
            return activity;
        }
    };

    /*
     * Autowired beans listed alphabetically by type
     */
    @Autowired private FragmentAdministrationHelper fragmentAdminHelper;
    @Autowired private IAuthorizationService authorizationService;
    @Autowired private IChannelPublishingDefinitionDao portletPublishingDefinitionDao;
    @Autowired private IGroupListHelper groupListHelper;
    @Autowired private IPortalUrlProvider urlProvider;
    @Autowired private IPortletCategoryRegistry portletCategoryRegistry;
    @Autowired private IPortletDefinitionRegistry portletDefinitionRegistry;
    @Autowired private IPortletPublishingService portletPublishingService;
    @Autowired private IPortletTypeRegistry portletTypeRegistry;
    @Autowired private PortalDriverContainerServices portalDriverContainerServices;
    @Autowired private PortletDelegationLocator portletDelegationLocator;

    private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * Construct a new PortletDefinitionForm for the given IPortletDefinition id. If a
     * PortletDefinition matching this ID already exists, the form will be pre-populated with the
     * PortletDefinition's current configuration. If the PortletDefinition does not yet exist, a new
     * default form will be created.
     *
     * @param person user that is required to have related lifecycle permission
     * @param portletId identifier for the portlet definition
     * @return {@PortletDefinitionForm} with set values based on portlet definition or default
     *     category and principal if no definition is found
     */
    public PortletDefinitionForm createPortletDefinitionForm(IPerson person, String portletId) {

        IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(portletId);

        // create the new form
        final PortletDefinitionForm form;
        if (def != null) {
            // if this is a pre-existing portlet, set the category and permissions
            form = new PortletDefinitionForm(def);
            form.setId(def.getPortletDefinitionId().getStringId());

            // create a JsonEntityBean for each current category and add it
            // to our form bean's category list
            Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def);
            for (PortletCategory cat : categories) {
                form.addCategory(new JsonEntityBean(cat));
            }

            addPrincipalPermissionsToForm(def, form);
        } else {
            form = createNewPortletDefinitionForm();
        }

        /* TODO:  Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */
        // User must have SOME FORM of lifecycle permission over AT LEAST ONE
        // category in which this portlet resides;  lifecycle permissions are
        // hierarchical, so we'll test with the weakest.
        if (!hasLifecyclePermission(person, PortletLifecycleState.CREATED, form.getCategories())) {
            logger.warn(
                    "User '"
                            + person.getUserName()
                            + "' attempted to edit the following portlet without MANAGE permission:  "
                            + def);
            throw new SecurityException("Not Authorized");
        }

        return form;
    }

    /*
     * Add to the form SUBSCRIBE, BROWSE, and CONFIGURE activity permissions, along with their principals,
     * assigned to the portlet.
     */
    private void addPrincipalPermissionsToForm(IPortletDefinition def, PortletDefinitionForm form) {
        final String portletTargetId = PermissionHelper.permissionTargetIdForPortletDefinition(def);

        final Set<JsonEntityBean> principalBeans = new HashSet<>();
        Map<String, IPermissionManager> permManagers = new HashMap<>();
        for (PortletPermissionsOnForm perm : PortletPermissionsOnForm.values()) {
            if (!permManagers.containsKey(perm.getOwner())) {
                permManagers.put(
                        perm.getOwner(),
                        authorizationService.newPermissionManager(perm.getOwner()));
            }
            final IPermissionManager pm = permManagers.get(perm.getOwner());
            /* Obtain the principals that have permission for the activity on this portlet */
            final IAuthorizationPrincipal[] principals =
                    pm.getAuthorizedPrincipals(perm.getActivity(), portletTargetId);

            for (IAuthorizationPrincipal principal : principals) {
                JsonEntityBean principalBean;

                // first assume this is a group
                final IEntityGroup group = GroupService.findGroup(principal.getKey());
                if (group != null) {
                    // principal is a group
                    principalBean = new JsonEntityBean(group, EntityEnum.GROUP);
                } else {
                    // not a group, so it must be a person
                    final IGroupMember member = authorizationService.getGroupMember(principal);
                    principalBean = new JsonEntityBean(member, EntityEnum.PERSON);
                    // set the name
                    final String name = groupListHelper.lookupEntityName(principalBean);
                    principalBean.setName(name);
                }

                principalBeans.add(principalBean);

                form.addPermission(principalBean.getTypeAndIdHash() + "_" + perm.getActivity());
            }
        }
        form.setPrincipals(principalBeans);
    }

    /*
     * Create a {@code PortletDefinitionForm} and pre-populate it with default categories and principal permissions.
     */
    private PortletDefinitionForm createNewPortletDefinitionForm() {
        final PortletDefinitionForm form = new PortletDefinitionForm();

        // pre-populate with top-level category
        final IEntityGroup portletCategoriesGroup =
                GroupService.getDistinguishedGroup(IPortletDefinition.DISTINGUISHED_GROUP);
        form.addCategory(
                new JsonEntityBean(
                        portletCategoriesGroup,
                        groupListHelper.getEntityType(portletCategoriesGroup)));

        // pre-populate with top-level group
        final IEntityGroup everyoneGroup =
                GroupService.getDistinguishedGroup(IPerson.DISTINGUISHED_GROUP);
        final JsonEntityBean everyoneBean =
                new JsonEntityBean(everyoneGroup, groupListHelper.getEntityType(everyoneGroup));
        form.setPrincipals(Collections.singleton(everyoneBean));
        form.initPermissionsForPrincipal(everyoneBean);

        return form;
    }

    /**
     * Persist a new or edited PortletDefinition from a form, replacing existing values.
     *
     * @param publisher {@code IPerson} that requires permission to save this definition
     * @param form form data to persist
     * @return new {@code PortletDefinitionForm} for this portlet ID
     */
    public PortletDefinitionForm savePortletRegistration(
            IPerson publisher, PortletDefinitionForm form) throws Exception {
        logger.trace("In savePortletRegistration() - for: {}", form.getPortletName());
        /* TODO:  Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */

        // User must have the selected lifecycle permission over AT LEAST ONE
        // category in which this portlet resides.  (This is the same check that
        // is made when the user enters the lifecycle-selection step in the wizard.)
        if (!hasLifecyclePermission(publisher, form.getLifecycleState(), form.getCategories())) {
            logger.warn(
                    "User '"
                            + publisher.getUserName()
                            + "' attempted to save the following portlet without the selected MANAGE permission:  "
                            + form);
            throw new SecurityException("Not Authorized");
        }

        if (!form.isNew()) {
            // User must have the previous lifecycle permission
            // in AT LEAST ONE previous category as well
            IPortletDefinition def =
                    this.portletDefinitionRegistry.getPortletDefinition(form.getId());
            Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def);
            SortedSet<JsonEntityBean> categoryBeans = new TreeSet<>();
            for (PortletCategory cat : categories) {
                categoryBeans.add(new JsonEntityBean(cat));
            }
            if (!hasLifecyclePermission(publisher, def.getLifecycleState(), categoryBeans)) {
                logger.warn(
                        "User '"
                                + publisher.getUserName()
                                + "' attempted to save the following portlet without the previous MANAGE permission:  "
                                + form);
                throw new SecurityException("Not Authorized");
            }
        }

        if (form.isNew()
                || portletDefinitionRegistry.getPortletDefinition(form.getId()).getType().getId()
                        != form.getTypeId()) {
            // User must have access to the selected CPD if s/he selected it in this interaction
            final int selectedTypeId = form.getTypeId();
            final PortletPublishingDefinition cpd =
                    portletPublishingDefinitionDao.getChannelPublishingDefinition(selectedTypeId);
            final Map<IPortletType, PortletPublishingDefinition> allowableCpds =
                    this.getAllowableChannelPublishingDefinitions(publisher);
            if (!allowableCpds.containsValue(cpd)) {
                logger.warn(
                        "User '"
                                + publisher.getUserName()
                                + "' attempted to administer the following portlet without the selected "
                                + IPermission.PORTLET_MANAGER_SELECT_PORTLET_TYPE
                                + " permission:  "
                                + form);
                throw new SecurityException("Not Authorized");
            }
        }

        // create the principal array from the form's principal list -- only principals with
        // permissions
        final Set<IGroupMember> subscribePrincipalSet = new HashSet<>(form.getPrincipals().size());
        final Set<IGroupMember> browsePrincipalSet = new HashSet<>(form.getPrincipals().size());
        final Set<IGroupMember> configurePrincipalSet = new HashSet<>(form.getPrincipals().size());
        for (JsonEntityBean bean : form.getPrincipals()) {
            final String subscribePerm =
                    bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_SUBSCRIBER_ACTIVITY;
            final String browsePerm =
                    bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_BROWSE_ACTIVITY;
            final String configurePerm =
                    bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_MODE_CONFIG;
            final EntityEnum entityEnum = bean.getEntityType();
            final IGroupMember principal =
                    entityEnum.isGroup()
                            ? (GroupService.findGroup(bean.getId()))
                            : (GroupService.getGroupMember(bean.getId(), entityEnum.getClazz()));
            if (form.getPermissions().contains(subscribePerm)) {
                logger.info(
                        "In savePortletRegistration() - Found a subscribePerm for principal: {}",
                        principal);
                subscribePrincipalSet.add(principal);
            }
            if (form.getPermissions().contains(browsePerm)) {
                logger.info(
                        "In savePortletRegistration() - Found a browsePerm for principal: {}",
                        principal);
                browsePrincipalSet.add(principal);
            }
            if (form.getPermissions().contains(configurePerm)) {
                logger.info(
                        "In savePortletRegistration() - Found a configurePerm for principal: {}",
                        principal);
                configurePrincipalSet.add(principal);
            }
        }

        // create the category list from the form's category bean list
        List<PortletCategory> categories = new ArrayList<>();
        for (JsonEntityBean category : form.getCategories()) {
            String id = category.getId();
            String iCatID = id.startsWith("cat") ? id.substring(3) : id;
            categories.add(portletCategoryRegistry.getPortletCategory(iCatID));
        }

        final IPortletType portletType = portletTypeRegistry.getPortletType(form.getTypeId());
        if (portletType == null) {
            throw new IllegalArgumentException("No IPortletType exists for ID " + form.getTypeId());
        }

        IPortletDefinition portletDef;
        if (form.getId() == null) {
            portletDef =
                    new PortletDefinitionImpl(
                            portletType,
                            form.getFname(),
                            form.getName(),
                            form.getTitle(),
                            form.getApplicationId(),
                            form.getPortletName(),
                            form.isFramework());
        } else {
            portletDef = portletDefinitionRegistry.getPortletDefinition(form.getId());
            portletDef.setType(portletType);
            portletDef.setFName(form.getFname());
            portletDef.setName(form.getName());
            portletDef.setTitle(form.getTitle());
            portletDef.getPortletDescriptorKey().setWebAppName(form.getApplicationId());
            portletDef.getPortletDescriptorKey().setPortletName(form.getPortletName());
            portletDef.getPortletDescriptorKey().setFrameworkPortlet(form.isFramework());
        }
        portletDef.setDescription(form.getDescription());
        portletDef.setTimeout(form.getTimeout());

        // Make parameters (NB:  these are different from preferences) in the
        // portletDef reflect the state of the form, in case any have changed.
        for (String key : form.getParameters().keySet()) {
            String value = form.getParameters().get(key).getValue();
            if (!StringUtils.isBlank(value)) {
                portletDef.addParameter(key, value);
            }
        }
        portletDef.addParameter(
                IPortletDefinition.EDITABLE_PARAM, Boolean.toString(form.isEditable()));
        portletDef.addParameter(
                IPortletDefinition.CONFIGURABLE_PARAM, Boolean.toString(form.isConfigurable()));
        portletDef.addParameter(
                IPortletDefinition.HAS_HELP_PARAM, Boolean.toString(form.isHasHelp()));
        portletDef.addParameter(
                IPortletDefinition.HAS_ABOUT_PARAM, Boolean.toString(form.isHasAbout()));

        // Now add portlet preferences
        List<IPortletPreference> preferenceList = new ArrayList<>();
        for (String key : form.getPortletPreferences().keySet()) {
            List<String> prefValues = form.getPortletPreferences().get(key).getValue();
            if (prefValues != null && prefValues.size() > 0) {
                String[] values = prefValues.toArray(new String[prefValues.size()]);
                BooleanAttribute readOnly = form.getPortletPreferenceReadOnly().get(key);
                preferenceList.add(new PortletPreferenceImpl(key, readOnly.getValue(), values));
            }
        }
        portletDef.setPortletPreferences(preferenceList);

        // Lastly update the PortletDefinition's lifecycle state & lifecycle-related metadata
        updateLifecycleState(form, portletDef, publisher);

        // The final parameter of IGroupMembers is used to set the initial SUBSCRIBE permission set
        portletPublishingService.savePortletDefinition(
                portletDef, publisher, categories, new ArrayList<>(subscribePrincipalSet));
        // updatePermissions(portletDef, subscribePrincipalSet,
        // IPermission.PORTLET_SUBSCRIBER_ACTIVITY);
        updatePermissions(
                portletDef,
                browsePrincipalSet,
                IPermission.PORTAL_SUBSCRIBE,
                IPermission.PORTLET_BROWSE_ACTIVITY);
        updatePermissions(
                portletDef,
                configurePrincipalSet,
                IPermission.PORTAL_PUBLISH,
                IPermission.PORTLET_MODE_CONFIG);
        return this.createPortletDefinitionForm(
                publisher, portletDef.getPortletDefinitionId().getStringId());
    }

    /*
     * Update permissions for a given owner, activity, and portlet definition combination. Adds new principals' permissions passed in and removes
     * principals' permissions if not in the list for the given activity.
     */
    private void updatePermissions(
            IPortletDefinition def,
            Set<IGroupMember> newPrincipals,
            String owner,
            String activity) {
        final String portletTargetId = PermissionHelper.permissionTargetIdForPortletDefinition(def);

        final IUpdatingPermissionManager pm =
                authorizationService.newUpdatingPermissionManager(owner);

        /* Create the new permissions array */
        final List<IPermission> newPermissions = new ArrayList<>();
        for (final IGroupMember newPrincipal : newPrincipals) {
            final IAuthorizationPrincipal authorizationPrincipal =
                    authorizationService.newPrincipal(newPrincipal);
            final IPermission permission = pm.newPermission(authorizationPrincipal);
            permission.setType(IPermission.PERMISSION_TYPE_GRANT);
            permission.setActivity(activity);
            permission.setTarget(portletTargetId);
            newPermissions.add(permission);
            logger.trace("In updatePermissions() - adding a new permission of: {}", permission);
        }

        /* Remove former permissions for this portlet / activity */
        final IPermission[] oldPermissions = pm.getPermissions(activity, portletTargetId);
        pm.removePermissions(oldPermissions);

        /* Add the new permissions */
        pm.addPermissions(newPermissions.toArray(new IPermission[newPermissions.size()]));
    }

    /**
     * Delete the portlet with the given portlet ID.
     *
     * @param person the person removing the portlet
     * @param form
     */
    public void removePortletRegistration(IPerson person, PortletDefinitionForm form) {

        /* TODO:  Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */
        // Arguably a check here is redundant since -- in the current
        // portlet-manager webflow -- you can't get to this point in the
        // conversation with out first obtaining a PortletDefinitionForm;  but
        // it makes sense to check permissions here as well since the route(s)
        // to reach this method could evolve in the future.

        // Let's enforce the policy that you may only delete a portlet thet's
        // currently in a lifecycle state you have permission to MANAGE.
        // (They're hierarchical.)
        if (!hasLifecyclePermission(person, form.getLifecycleState(), form.getCategories())) {
            logger.warn(
                    "User '"
                            + person.getUserName()
                            + "' attempted to remove portlet '"
                            + form.getFname()
                            + "' without the proper MANAGE permission");
            throw new SecurityException("Not Authorized");
        }

        IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(form.getId());
        /*
         * It's very important to remove portlets via the portletPublishingService
         * because that API cleans up details like category memberships and permissions.
         */
        portletPublishingService.removePortletDefinition(def, person);
    }

    /**
     * Check if the link to the Fragment admin portlet should display in the status message.
     *
     * <p>Checks that the portlet is new, that the portlet has been published and that the user has
     * necessary permissions to go to the fragment admin page.
     *
     * @param person the person publishing/editing the portlet
     * @param form the portlet being editted
     * @param portletId the id of the saved portlet
     * @return true If all three conditions are met
     */
    public boolean shouldDisplayLayoutLink(
            IPerson person, PortletDefinitionForm form, String portletId) {
        if (!form.isNew()) {
            return false;
        }

        // only include the "do layout" link for published portlets.
        if (form.getLifecycleState() != PortletLifecycleState.PUBLISHED) {
            return false;
        }

        // check that the user can edit at least 1 fragment.
        Map<String, String> layouts =
                fragmentAdminHelper.getAuthorizedDlmFragments(person.getUserName());
        if (layouts == null || layouts.isEmpty()) {
            return false;
        }

        // check that the user has subscribe priv.
        IAuthorizationPrincipal authPrincipal =
                authorizationService.newPrincipal(
                        person.getUserName(), EntityEnum.PERSON.getClazz());

        return authPrincipal.canSubscribe(portletId);
    }

    /**
     * Get the link to the fragment admin portlet.
     *
     * @param request the current http request.
     * @return the portlet link
     */
    public String getFragmentAdminURL(HttpServletRequest request) {
        IPortalUrlBuilder builder =
                urlProvider.getPortalUrlBuilderByPortletFName(
                        request, PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET, UrlType.RENDER);
        IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder();
        portletUrlBuilder.setPortletMode(PortletMode.VIEW);
        portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);

        return builder.getUrlString();
    }

    /**
     * Get a list of the key names of the currently-set arbitrary portlet preferences.
     *
     * @param form
     * @return
     */
    public Set<String> getArbitraryPortletPreferenceNames(PortletDefinitionForm form) {
        // set default values for all portlet parameters
        PortletPublishingDefinition cpd =
                this.portletPublishingDefinitionDao.getChannelPublishingDefinition(
                        form.getTypeId());
        Set<String> currentPrefs = new HashSet<>();
        currentPrefs.addAll(form.getPortletPreferences().keySet());
        for (Step step : cpd.getSteps()) {
            if (step.getPreferences() != null) {
                for (Preference pref : step.getPreferences()) {
                    currentPrefs.remove(pref.getName());
                }
            }
        }
        return currentPrefs;
    }

    /**
     * If the portlet is a portlet and if one of the supported portlet modes is {@link
     * IPortletRenderer#CONFIG}
     */
    public boolean supportsConfigMode(PortletDefinitionForm form) {
        final Tuple<String, String> portletDescriptorKeys = this.getPortletDescriptorKeys(form);
        if (portletDescriptorKeys == null) {
            logger.trace("Unable to determine supportsConfig - portletDescriptorKeys is null.");
            return false;
        }
        final String portletAppId = portletDescriptorKeys.first;
        final String portletName = portletDescriptorKeys.second;

        final PortletRegistryService portletRegistryService =
                this.portalDriverContainerServices.getPortletRegistryService();
        final PortletDefinition portletDescriptor;
        try {
            portletDescriptor = portletRegistryService.getPortlet(portletAppId, portletName);
        } catch (PortletContainerException e) {
            this.logger.warn(
                    "Unable to determine supportsConfig - Failed to load portlet descriptor for appId='"
                            + portletAppId
                            + "', portletName='"
                            + portletName
                            + "'",
                    e);
            return false;
        }

        if (portletDescriptor == null) {
            logger.trace("Unable to determine supportsConfig - portletDescriptor is null.");
            return false;
        }
        logger.trace(
                "Checking supportsConfig for portlet ID=[{}] and Name=[{}].",
                portletAppId,
                portletName);

        // Iterate over supported portlet modes, this ignores the content types for now
        final List<? extends Supports> supports = portletDescriptor.getSupports();
        for (final Supports support : supports) {
            logger.trace("Checking Supports instance:  {}", support.getMimeType());
            final List<String> portletModes = support.getPortletModes();
            for (final String portletMode : portletModes) {
                logger.trace("Checking portletMode {}.", portletMode);
                if (IPortletRenderer.CONFIG.equals(PortletUtils.getPortletMode(portletMode))) {
                    logger.trace("Returning supportsConfig is true.");
                    return true;
                }
            }
        }
        logger.trace("Returning supportsConfig is false.");
        return false;
    }

    private static final Pattern PARAM_PATTERN =
            Pattern.compile("^([^\\[]+)\\['([^\\']+)'\\]\\.value$");

    public void cleanOptions(PortletDefinitionForm form, PortletRequest request) {
        // Add permission parameters to permissions collection
        form.clearPermissions();
        for (PortletPermissionsOnForm perm : PortletPermissionsOnForm.values()) {
            addPermissionsFromRequestToForm(form, request, perm.getActivity());
        }

        // Names of valid preferences and parameters
        final Set<String> preferenceNames = new HashSet<>();
        final Set<String> parameterNames = new HashSet<>();

        // Read all of the submitted channel parameter and portlet preference names from the request
        for (final Enumeration<String> e = request.getParameterNames(); e.hasMoreElements(); ) {
            final String name = e.nextElement();
            final Matcher nameMatcher = PARAM_PATTERN.matcher(name);
            if (nameMatcher.matches()) {
                final String paramType = nameMatcher.group(1);
                final String paramName = nameMatcher.group(2);

                if ("portletPreferences".equals(paramType)) {
                    preferenceNames.add(paramName);
                } else if ("parameters".equals(paramType)) {
                    parameterNames.add(paramName);
                }
            }
        }

        // Add all of the parameter and preference names that have default values in the CPD into
        // the valid name sets
        final PortletPublishingDefinition cpd =
                this.portletPublishingDefinitionDao.getChannelPublishingDefinition(
                        form.getTypeId());
        for (final Step step : cpd.getSteps()) {
            final List<Parameter> parameters = step.getParameters();
            if (parameters != null) {
                for (final Parameter parameter : parameters) {
                    final JAXBElement<? extends ParameterInputType> parameterInput =
                            parameter.getParameterInput();
                    if (parameterInput != null) {
                        final ParameterInputType parameterInputType = parameterInput.getValue();
                        if (parameterInputType != null && parameterInputType.getDefault() != null) {
                            parameterNames.add(parameter.getName());
                        }
                    }
                }
            }

            final List<Preference> preferences = step.getPreferences();
            if (preferences != null) {
                for (final Preference preference : preferences) {
                    final JAXBElement<? extends PreferenceInputType> preferenceInput =
                            preference.getPreferenceInput();
                    final PreferenceInputType preferenceInputType = preferenceInput.getValue();
                    if (preferenceInputType instanceof MultiValuedPreferenceInputType) {
                        final MultiValuedPreferenceInputType multiValuedPreferenceInputType =
                                (MultiValuedPreferenceInputType) preferenceInputType;
                        final List<String> defaultValues =
                                multiValuedPreferenceInputType.getDefaults();
                        if (defaultValues != null && !defaultValues.isEmpty()) {
                            preferenceNames.add(preference.getName());
                        }
                    } else if (preferenceInputType instanceof SingleValuedPreferenceInputType) {
                        final SingleValuedPreferenceInputType SingleValuedPreferenceInputType =
                                (SingleValuedPreferenceInputType) preferenceInputType;
                        if (SingleValuedPreferenceInputType.getDefault() != null) {
                            preferenceNames.add(preference.getName());
                        }
                    }
                }
            }
        }

        // Remove portlet preferences from the form object that were not part of this request or
        // defined in the CPD
        // - do it only if portlet doesn't support configMode
        if (!this.supportsConfigMode(form)) {
            final Map<String, StringListAttribute> portletPreferences =
                    form.getPortletPreferences();
            final Map<String, BooleanAttribute> portletPreferencesOverrides =
                    form.getPortletPreferenceReadOnly();

            for (final Iterator<Entry<String, StringListAttribute>> portletPreferenceEntryItr =
                            portletPreferences.entrySet().iterator();
                    portletPreferenceEntryItr.hasNext(); ) {
                final Map.Entry<String, StringListAttribute> portletPreferenceEntry =
                        portletPreferenceEntryItr.next();
                final String key = portletPreferenceEntry.getKey();
                final StringListAttribute valueAttr = portletPreferenceEntry.getValue();
                if (!preferenceNames.contains(key) || valueAttr == null) {
                    portletPreferenceEntryItr.remove();
                    portletPreferencesOverrides.remove(key);
                } else {
                    final List<String> values = valueAttr.getValue();
                    for (final Iterator<String> iter = values.iterator(); iter.hasNext(); ) {
                        String value = iter.next();
                        if (value == null) {
                            iter.remove();
                        }
                    }
                    if (values.size() == 0) {
                        portletPreferenceEntryItr.remove();
                        portletPreferencesOverrides.remove(key);
                    }
                }
            }
        }

        final Map<String, Attribute> parameters = form.getParameters();

        for (final Iterator<Entry<String, Attribute>> parameterEntryItr =
                        parameters.entrySet().iterator();
                parameterEntryItr.hasNext(); ) {
            final Entry<String, Attribute> parameterEntry = parameterEntryItr.next();
            final String key = parameterEntry.getKey();
            final Attribute value = parameterEntry.getValue();

            if (!parameterNames.contains(key)
                    || value == null
                    || StringUtils.isBlank(value.getValue())) {
                parameterEntryItr.remove();
            }
        }
    }

    private void addPermissionsFromRequestToForm(
            PortletDefinitionForm form, PortletRequest request, String activity) {
        final String ending = "_" + activity;
        for (final String name : request.getParameterMap().keySet()) {
            if (name.endsWith(ending)) {
                logger.info(
                        "In addPermissionsFromRequestToForm() - Adding permission request: {}",
                        name);
                form.addPermission(name);
            } else {
                logger.info(
                        "In addPermissionsFromRequestToForm() - For permissions, ignoring request parameter: {}",
                        name);
            }
        }
    }

    /**
     * Retreive the list of portlet application contexts currently available in this portlet
     * container.
     *
     * @return list of portlet context
     */
    public List<PortletApplicationDefinition> getPortletApplications() {
        final PortletRegistryService portletRegistryService =
                portalDriverContainerServices.getPortletRegistryService();
        final List<PortletApplicationDefinition> contexts = new ArrayList<>();

        for (final Iterator<String> iter =
                        portletRegistryService.getRegisteredPortletApplicationNames();
                iter.hasNext(); ) {
            final String applicationName = iter.next();
            final PortletApplicationDefinition applicationDefninition;
            try {
                applicationDefninition =
                        portletRegistryService.getPortletApplication(applicationName);
            } catch (PortletContainerException e) {
                throw new RuntimeException(
                        "Failed to load PortletApplicationDefinition for '"
                                + applicationName
                                + "'");
            }

            final List<? extends PortletDefinition> portlets = applicationDefninition.getPortlets();
            portlets.sort(
                    new ComparableExtractingComparator<PortletDefinition, String>(
                            String.CASE_INSENSITIVE_ORDER) {
                        @Override
                        protected String getComparable(PortletDefinition o) {
                            final List<? extends DisplayName> displayNames = o.getDisplayNames();
                            if (displayNames != null && displayNames.size() > 0) {
                                return displayNames.get(0).getDisplayName();
                            }

                            return o.getPortletName();
                        }
                    });

            contexts.add(applicationDefninition);
        }

        contexts.sort(
                new ComparableExtractingComparator<PortletApplicationDefinition, String>(
                        String.CASE_INSENSITIVE_ORDER) {
                    @Override
                    protected String getComparable(PortletApplicationDefinition o) {
                        final String portletContextName = o.getName();
                        if (portletContextName != null) {
                            return portletContextName;
                        }

                        final String applicationName = o.getContextPath();
                        if ("/".equals(applicationName)) {
                            return "ROOT";
                        }

                        if (applicationName.startsWith("/")) {
                            return applicationName.substring(1);
                        }

                        return applicationName;
                    }
                });
        return contexts;
    }

    /**
     * Get a portlet descriptor matching the current portlet definition form. If the current form
     * does not represent a portlet, the application or portlet name fields are blank, or the
     * portlet description cannot be retrieved, the method will return <code>null</code>.
     *
     * @param form
     * @return
     */
    public PortletDefinition getPortletDescriptor(PortletDefinitionForm form) {
        final Tuple<String, String> portletDescriptorKeys = this.getPortletDescriptorKeys(form);
        if (portletDescriptorKeys == null) {
            return null;
        }
        final String portletAppId = portletDescriptorKeys.first;
        final String portletName = portletDescriptorKeys.second;

        final PortletRegistryService portletRegistryService =
                portalDriverContainerServices.getPortletRegistryService();
        try {
            return portletRegistryService.getPortlet(portletAppId, portletName);
        } catch (PortletContainerException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Pre-populate a new {@link PortletDefinitionForm} with information from the {@link
     * PortletDefinition}.
     *
     * @param form
     */
    public void loadDefaultsFromPortletDefinitionIfNew(PortletDefinitionForm form) {

        if (!form.isNew()) {
            // Get out;  we only prepopulate new portlets
            return;
        }

        // appName/portletName must be set at this point
        Validate.notBlank(form.getApplicationId(), "ApplicationId not set");
        Validate.notBlank(form.getPortletName(), "PortletName not set");

        final PortletRegistryService portletRegistryService =
                portalDriverContainerServices.getPortletRegistryService();
        final PortletDefinition portletDef;
        try {
            portletDef =
                    portletRegistryService.getPortlet(
                            form.getApplicationId(), form.getPortletName());
        } catch (PortletContainerException e) {
            this.logger.warn(
                    "Failed to load portlet descriptor for appId='"
                            + form.getApplicationId()
                            + "', portletName='"
                            + form.getPortletName()
                            + "'",
                    e);
            return;
        }

        form.setTitle(portletDef.getPortletName());
        form.setName(portletDef.getPortletName());
        for (Supports supports : portletDef.getSupports()) {
            for (String mode : supports.getPortletModes()) {
                if ("edit".equalsIgnoreCase(mode)) {
                    form.setEditable(true);
                } else if ("help".equalsIgnoreCase(mode)) {
                    form.setHasHelp(true);
                } else if ("config".equalsIgnoreCase(mode)) {
                    form.setConfigurable(true);
                }
            }
        }
    }

    public PortletLifecycleState[] getLifecycleStates() {
        return PortletLifecycleState.values();
    }

    public Set<PortletLifecycleState> getAllowedLifecycleStates(
            IPerson person, SortedSet<JsonEntityBean> categories) {
        Set<PortletLifecycleState> states = new TreeSet<PortletLifecycleState>();
        if (hasLifecyclePermission(person, PortletLifecycleState.MAINTENANCE, categories)) {
            states.add(PortletLifecycleState.CREATED);
            states.add(PortletLifecycleState.APPROVED);
            states.add(PortletLifecycleState.EXPIRED);
            states.add(PortletLifecycleState.PUBLISHED);
            states.add(PortletLifecycleState.MAINTENANCE);
        } else if (hasLifecyclePermission(person, PortletLifecycleState.EXPIRED, categories)) {
            states.add(PortletLifecycleState.CREATED);
            states.add(PortletLifecycleState.APPROVED);
            states.add(PortletLifecycleState.EXPIRED);
            states.add(PortletLifecycleState.PUBLISHED);
        } else if (hasLifecyclePermission(person, PortletLifecycleState.PUBLISHED, categories)) {
            states.add(PortletLifecycleState.CREATED);
            states.add(PortletLifecycleState.APPROVED);
            states.add(PortletLifecycleState.PUBLISHED);
        } else if (hasLifecyclePermission(person, PortletLifecycleState.APPROVED, categories)) {
            states.add(PortletLifecycleState.CREATED);
            states.add(PortletLifecycleState.APPROVED);
        } else if (hasLifecyclePermission(person, PortletLifecycleState.CREATED, categories)) {
            states.add(PortletLifecycleState.CREATED);
        }
        return states;
    }

    public boolean hasLifecyclePermission(
            IPerson person, PortletLifecycleState state, SortedSet<JsonEntityBean> categories) {
        EntityIdentifier ei = person.getEntityIdentifier();
        IAuthorizationPrincipal ap = authorizationService.newPrincipal(ei.getKey(), ei.getType());

        final String activity;
        switch (state) {
            case APPROVED:
                {
                    activity = IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY;
                    break;
                }
            case CREATED:
                {
                    activity = IPermission.PORTLET_MANAGER_CREATED_ACTIVITY;
                    break;
                }
            case PUBLISHED:
                {
                    activity = IPermission.PORTLET_MANAGER_ACTIVITY;
                    break;
                }
            case EXPIRED:
                {
                    activity = IPermission.PORTLET_MANAGER_EXPIRED_ACTIVITY;
                    break;
                }
            case MAINTENANCE:
                {
                    activity = IPermission.PORTLET_MANAGER_MAINTENANCE_ACTIVITY;
                    break;
                }
            default:
                {
                    throw new IllegalArgumentException("");
                }
        }
        if (ap.hasPermission(
                IPermission.PORTAL_PUBLISH, activity, IPermission.ALL_PORTLETS_TARGET)) {
            logger.debug(
                    "Found permission for category ALL_PORTLETS and lifecycle state "
                            + state.toString());
            return true;
        }

        for (JsonEntityBean category : categories) {
            if (ap.canManage(state, category.getId())) {
                logger.debug(
                        "Found permission for category "
                                + category.getName()
                                + " and lifecycle state "
                                + state.toString());
                return true;
            }
        }
        logger.debug("No permission for lifecycle state " + state.toString());
        return false;
    }

    public IPortletWindowId getDelegateWindowId(ExternalContext externalContext, String fname) {
        final PortletRequest nativeRequest = (PortletRequest) externalContext.getNativeRequest();
        final PortletSession portletSession = nativeRequest.getPortletSession();
        return (IPortletWindowId)
                portletSession.getAttribute(RenderPortletTag.DEFAULT_SESSION_KEY_PREFIX + fname);
    }

    public boolean configModeAction(ExternalContext externalContext, String fname)
            throws IOException {

        final ActionRequest actionRequest = (ActionRequest) externalContext.getNativeRequest();
        final ActionResponse actionResponse = (ActionResponse) externalContext.getNativeResponse();

        final IPortletWindowId portletWindowId = this.getDelegateWindowId(externalContext, fname);
        if (portletWindowId == null) {
            throw new IllegalStateException(
                    "Cannot execute configModeAciton without a delegate window ID in the session for key: "
                            + RenderPortletTag.DEFAULT_SESSION_KEY_PREFIX
                            + fname);
        }

        final PortletDelegationDispatcher requestDispatcher =
                this.portletDelegationLocator.getRequestDispatcher(actionRequest, portletWindowId);

        final DelegationActionResponse delegationResponse =
                requestDispatcher.doAction(actionRequest, actionResponse);

        final String redirectLocation = delegationResponse.getRedirectLocation();
        final DelegateState delegateState = delegationResponse.getDelegateState();
        if (redirectLocation != null
                || (delegationResponse.getPortletMode() != null
                        && !IPortletRenderer.CONFIG.equals(delegationResponse.getPortletMode()))
                || !IPortletRenderer.CONFIG.equals(delegateState.getPortletMode())) {

            // The portlet sent a redirect OR changed it's mode away from CONFIG, assume it is done
            return true;
        }

        return false;
    }

    /**
     * updates the editPortlet form with the portletType of the first (and only) portletDefinition
     * passed in through the Map of portlet definitions.
     *
     * @param portletDefinitions
     * @param form
     * @return PortletPublishingDefinition of the first portlet definition in the list, null if the
     *     list is empty or has more than one element.
     */
    public PortletPublishingDefinition updateFormForSinglePortletType(
            Map<IPortletType, PortletPublishingDefinition> portletDefinitions,
            PortletDefinitionForm form) {
        if (portletDefinitions.size() != 1) {
            return null;
        }
        IPortletType portletType = portletDefinitions.keySet().iterator().next();
        form.setTypeId(portletType.getId());
        PortletPublishingDefinition cpd =
                portletPublishingDefinitionDao.getChannelPublishingDefinition(portletType.getId());
        form.setChannelPublishingDefinition(cpd);

        return cpd;
    }

    public boolean offerPortletSelection(PortletDefinitionForm form) {
        final IPortletType portletType = this.portletTypeRegistry.getPortletType(form.getTypeId());
        final PortletPublishingDefinition portletPublishingDefinition =
                this.portletPublishingDefinitionDao.getChannelPublishingDefinition(
                        portletType.getId());
        final PortletDescriptor portletDescriptor =
                portletPublishingDefinition.getPortletDescriptor();
        if (portletDescriptor == null) {
            return true;
        }

        final Boolean isFramework = portletDescriptor.isIsFramework();
        if (isFramework != null && isFramework) {
            form.setFramework(true);
        } else {
            final String webAppName = portletDescriptor.getWebAppName();
            form.setApplicationId(webAppName);
        }

        final String portletName = portletDescriptor.getPortletName();
        form.setPortletName(portletName);

        return false;
    }

    public Map<IPortletType, PortletPublishingDefinition> getAllowableChannelPublishingDefinitions(
            IPerson user) {

        Map<IPortletType, PortletPublishingDefinition> rslt;

        final Map<IPortletType, PortletPublishingDefinition> rawMap =
                portletPublishingDefinitionDao.getChannelPublishingDefinitions();
        final IAuthorizationPrincipal principal =
                AuthorizationPrincipalHelper.principalFromUser(user);
        if (principal.hasPermission(
                IPermission.PORTAL_PUBLISH,
                IPermission.PORTLET_MANAGER_SELECT_PORTLET_TYPE,
                IPermission.ALL_PORTLET_TYPES)) {
            // Send the whole collection back...
            rslt = rawMap;
        } else {
            // Filter the collection by permissions...
            rslt = new HashMap<>();
            for (Map.Entry<IPortletType, PortletPublishingDefinition> y : rawMap.entrySet()) {
                if (principal.hasPermission(
                        IPermission.PORTAL_PUBLISH,
                        IPermission.PORTLET_MANAGER_SELECT_PORTLET_TYPE,
                        y.getKey().getName())) {
                    rslt.put(y.getKey(), y.getValue());
                }
            }
        }

        return rslt;
    }

    protected Tuple<String, String> getPortletDescriptorKeys(PortletDefinitionForm form) {
        if (form.getPortletName() == null
                || (form.getApplicationId() == null && !form.isFramework())) {
            return null;
        }

        final String portletAppId;
        if (form.isFramework()) {
            portletAppId = this.servletContext.getContextPath();
        } else {
            portletAppId = form.getApplicationId();
        }

        final String portletName = form.getPortletName();

        return new Tuple<>(portletAppId, portletName);
    }

    private void updateLifecycleState(
            PortletDefinitionForm form, IPortletDefinition portletDef, IPerson publisher) {

        final PortletLifecycleState selectedLifecycleState = form.getLifecycleState();

        /*
         * Step One:  update the current lifecycle state, even if it isn't changing.
         *
         * NOTE 1:  forcing an update (even to the same state) will have the effect of
         * clearing the publish/expire date if set previously (but not set in this submit).
         *
         * NOTE 2:  permissions for this step have already been checked in savePortletRegistration.
         */
        portletDef.updateLifecycleState(selectedLifecycleState, publisher);

        /*
         * Step Two:  depending on which state was selected, we may have extra work to do.
         */
        switch (selectedLifecycleState) {
            case APPROVED:
                // Check for an auto-publish date...
                if (form.getPublishDate() != null
                        && hasLifecyclePermission(
                                publisher, PortletLifecycleState.PUBLISHED, form.getCategories())) {
                    // We are also the 'publisher' if we scheduled the portlet for (future)
                    // publication...
                    portletDef.updateLifecycleState(
                            PortletLifecycleState.PUBLISHED, publisher, form.getPublishDateTime());
                }
                break;
            case PUBLISHED:
                // Check for an expiration date...
                if (form.getExpirationDate() != null
                        && hasLifecyclePermission(
                                publisher, PortletLifecycleState.EXPIRED, form.getCategories())) {
                    // We are also the 'expirer' if we scheduled the portlet for (future)
                    // expiration...
                    portletDef.updateLifecycleState(
                            PortletLifecycleState.EXPIRED, publisher, form.getExpirationDateTime());
                }
                break;
            default:
                // No extra work
                break;
        }
    }
}


text:
package org.maeno.example.service;

import org.maeno.example.domain.Project;
import org.maeno.example.repository.ProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    public List<Project> selectProject() {
        return projectMapper.list();
    }

    public List<Project> selectProject(ArrayList<Project> projectList) {
        final List<Integer> ids = getIds(projectList);
        return projectMapper.selectProjectByChecked(ids);
    }

    private List<Integer> getIds(ArrayList<Project> projectList) {
        final List<Integer> ids = new ArrayList<>();
        projectList.stream()
                .filter(project -> project.getChecked())
                .forEach(project -> ids.add(project.getId()));
        return ids;
    }

    public boolean deleteProject(ArrayList<Project> projectList) {
        final List<Integer> ids = getIds(projectList);
        return projectMapper.deleteProjectById(ids);
    }
}


text:
package io.fabric8.updatebot.test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Helper assertions for dealing with JSON or YAML markup
 */
public class MarkupAssertions {
    public static String assertTextValue(JsonNode tree, String... paths) {
        JsonNode node = assertPath(tree, paths);
        String pathText = Arrays.asList(paths).toString();

        assertThat(node).describedAs("Could not find value for path " + pathText).isNotNull();
        assertThat(node.isTextual()).describedAs("Value of path " + pathText + " is not textual but is " + node).isTrue();

        return node.asText();
    }

    public static ObjectNode assertSetValue(JsonNode tree, String value, String... paths) {
        assertThat(paths.length).describedAs("Should have at least one path expression!").isGreaterThan(0);

        int objectPathLength = paths.length - 1;
        ObjectNode objectNode;
        if (paths.length > 1) {
            String[] objectPath = new String[objectPathLength];
            System.arraycopy(paths, 0, objectPath, 0, objectPathLength);
            objectNode = assertObjectPath(tree, objectPath);
        } else {
            objectNode = assertObjectNode(tree);
        }
        objectNode.put(paths[objectPathLength], value);
        return objectNode;
    }

    public static ObjectNode assertObjectNode(JsonNode node) {
        assertThat(node).describedAs("ObjectNode expected").isInstanceOf(ObjectNode.class);
        return (ObjectNode) node;
    }

    public static ObjectNode assertObjectPath(JsonNode tree, String... paths) {
        JsonNode node = assertPath(tree, paths);
        return assertObjectNode(node);
    }

    public static JsonNode assertPath(JsonNode tree, String... paths) {
        JsonNode node = tree;
        for (String path : paths) {
            assertThat(node.isObject()).
                    describedAs("cannot access property " + path + " as the node is not an object " + node).
                    isTrue();

            JsonNode value = node.get(path);
            assertThat(value).
                    describedAs("property " + path + " should exist on " + node).
                    isNotNull();
            node = value;
        }
        return node;
    }
}


text:
<?php if (@$status == "baru") { ?>Input <?php } else { ?> Edit <?php } ?> AnggotaKoperasi ITS

File exel (*.xls):

                    <?php echo form_open_multipart('adminwebsite/do_upload'); ?>
                    <input type="file" id="file_upload" name="userfile" size="20" />
                    <button class="btn btn-danger" style="float:right;"  type="submit">Upload Excel Anggota Koperasi</button>
                    <?php echo form_close(); ?>

<a href="<?php echo base_url(); ?>dokumentasi\sampleDataExcelUtkDiUpload\anggota.xls"> DOWNLOAD CONTOH FILE EXCEL DISINI

CATATAN -->  PASTIKAN anda menyimpan backup data terlebih dahulu sebelum upload file Excel, karena data akan terhapus dan diisi dengan data baru ketika anda klik tombol upload

CATATAN -->  default password anggota = nomor anggota koperasi


text:
<!doctype html>

		<title>Contact Us | Films for the Forest</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
		<link href="../../css/bootstrap.min.css" rel="stylesheet" media="screen">
		<link href="../../css/style.css" rel="stylesheet">

				    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
				      Toggle navigation

				    </button>
				    Home

				        About

About Films for the Forest

About Rainforest Partnership

Judges

Advisors

Contact

				        Sponsors

Our Sponsors

Become a Sponsor

Past Winners

Submit Your Films

Donate

Contact Rainforest Partnership

					505 Willow St. Austin, TX 78701

					PO Box 49268 Austin, TX 78765

					(512) 420 0101

					films@rainforestpartnership.org

					© Rainforest Partnership 2014 | Made with  in Austin


text:
module HotelsPro
  class Request
    attr_accessor :api_method, :params

    def initialize(api_method, params={})
      @api_method = api_method.camelize(:lower)
      @params = params
    end

    def query
      params = @params.dup
      params["method"] = api_method
      params["apiKey"] = HotelsPro.configuration.api_key

      Query.new(params).to_s
    end

    def uri
      "#{HotelsPro.configuration.api_url}#{query}"
    end

    def perform
      HotelsPro.log("Request URL: #{uri}")

      raw_response = stubbed_response || real_response
      HotelsPro.log("Response: #{raw_response}")

      Response.new(raw_response)
    end

    def stubbed_response
      response = HotelsPro::Stubs.match(self)
      if !response && HotelsPro.configuration.only_stubs
        raise HotelsPro::UnstubbedRequest.new("Unstubbed request to URL: #{uri}")
      end
      response
    end

    def real_response
      Typhoeus::Request.get(uri).body
    end
  end
end


text:
Links
*****

- http://lucene.apache.org/
- http://lucenebook.com/
- .NET_
- `Search Engine Watch`_

Issues
======

- http://issues.apache.org/jira/browse/LUCENE

Alternatives
============

Also see *Competitors* (below)...

- `MG4J (Managing Gigabytes for Java) is a free full-text search engine for large document collections written in Java`_.
- http://sphinxsearch.com/

  - `Sphinx search introduction`_
  - http://xapian.org/

Articles
========

- `Delve inside the Lucene indexing mechanism`_ including
  *Improving the indexing performance*.

Competitors
===========

Also see *Alternatives* (above)...

- `IBM OmniFind Yahoo! Edition`_
- `IBM OmniFind Enterprise Edition`_

Did you mean
============

- org.apache.lucene.search.didyoumean_
- `Did You Mean: Lucene`_?
- `Spelling Checker using Lucene`_

Faceted
=======

- `Faceted Metadata Search and Browse`_

History
=======

- `The Lucene Search Engine, Doug Cutting, 16 June, 2000`_
- `Lucene - Doug Cutting, November 24, 2004`_

Index Accessor
==============

- :doc:`lucene-index-accessor`

Monitor
=======

- `LucidGaze for Lucene`_
  Monitor and improve your Lucene search performance.

StopWords
=========

- `Stopword List`_
- `Key to Effective Searches, Dealing with Stopwords`_
- `To Stopword or Not to Stopword?`_

Snowball
========

- `RE: [Snowball-discuss] Stop word lists`_

Text Extractor
==============

- `Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries`_.
- `Aperture, Extract full-text and metadata from many common file formats`_
  `Getting started (Appears to use Java 1.5)`_
- `OpenXML4j is a complete Java framework supporting Open Package Convention`_,
- Office Open XML (WordProcessingML, SpreadsheetML, PresentationML and shared
  specs like DrawingML).

html
----

- `Parsing HTML with java`_:

  - `HTMLEditorKit`_
  - `JTidy`_
  - `HTML Parser`_
  - `HTML Cleaner`_ For Maven instructions: `Maven repository notes`_.

Microsoft
---------

- `wv is a library which allows access to Microsoft Word files`_.
- `catdoc is program which reads one or more Microsoft word files and outputs text`_
- `catdoc, xls2csv and catppt`_
- `Antiword is a free MS Word reader for Linux`_
- `Using Java to Crack Office 2007`_

OpenOffice
----------

- `JOOConverter automates conversions between office document formats using OpenOffice.org`_
- `file2xliff4j is a set of Java classes to convert HTML, Word, Excel, OpenOffice.org Text, PowerPoint, RTF and MIF documents to XLIFF File Format`_.

pdf
---

- http://www.jpedal.org/

Projects
========

- `The Compass Framework`_ is a first class open source Java framework, enabling the power of
  Search Engine semantics to your application stack decoratively.
- `Enhydra Snapper - Fulltext Indexing and Search`_
- `Hibernate Search brings the power of full text search engines to the persistence domain model`_
  and Hibernate experience, through transparent configuration
  (Hibernate Annotations) and a common API.
  Might be here now... http://www.hibernate.org/410.html
- `Hibernate Annotations`_ includes a package of annotations that allows you to mark any
  domain model object as indexable and have Hibernate maintain a Lucene index of any
  instances persisted via Hibernate.
- `Kowari is an Open Source`_, massively scalable, transaction-safe, purpose-built database
  for the storage, retrieval and analysis of metadata.
- DBSight_ is a highly customisable full-text search platform for any relational
  database.
- `NetSearch - the Enterprise Search Solution from Ardentia`_
- Solr_ is an open source enterprise search server based on the Lucene Java search
  library, with XML/HTTP APIs, caching, replication, and a web administration
  interface.
- `LIUS is an indexing Java framework based on the Jakarta Lucene project`_.
  The LIUS framework indexes : MsWord, MsExcel, MsPowerPoint, RTF, PDF, XML, HTML,
  TXT, OpenOffice suite, ZIP files, MP3, VCard, Latex and JavaBeans.
- `Tika, a generic document parsing framework`_

Sample
======

- sample-lucene-did-you-mean_
- sample-lucene-count-unique-terms_

Upgrade
=======

- `Lucene 2.4 in 60 seconds`_

Word List
=========

- `Kevin's Word List Page`_

.. _.NET: http://sourceforge.net/projects/dotlucene/
.. _`Search Engine Watch`: http://searchenginewatch.com/
.. _`MG4J (Managing Gigabytes for Java) is a free full-text search engine for large document collections written in Java`: http://mg4j.dsi.unimi.it/
.. _`Sphinx search introduction`: http://komunitasweb.com/2009/03/sphinx-search-introduction/
.. _`Delve inside the Lucene indexing mechanism`: http://www-128.ibm.com/developerworks/library/wa-lucene/
.. _`IBM OmniFind Yahoo! Edition`: http://omnifind.ibm.yahoo.net/
.. _`IBM OmniFind Enterprise Edition`: http://www-306.ibm.com/software/data/enterprise-search/omnifind-enterprise/
.. _org.apache.lucene.search.didyoumean: http://ginandtonique.org/~kalle/javadocs/didyoumean/org/apache/lucene/search/didyoumean/package-summary.html
.. _`Did You Mean: Lucene`: http://today.java.net/pub/a/today/2005/08/09/didyoumean.html
.. _`Spelling Checker using Lucene`: http://sujitpal.blogspot.com/2007/12/spelling-checker-with-lucene.html
.. _`Faceted Metadata Search and Browse`: http://www.searchtools.com/info/faceted-metadata.html
.. _`The Lucene Search Engine, Doug Cutting, 16 June, 2000`: http://lucene.sourceforge.net/talks/inktomi/
.. _`Lucene - Doug Cutting, November 24, 2004`: http://lucene.sourceforge.net/talks/pisa/
.. _`LucidGaze for Lucene`: http://www.lucidimagination.com/Downloads/LucidGaze-for-Lucene
.. _`Stopword List`: http://www.unine.ch/info/clef/
.. _`Key to Effective Searches, Dealing with Stopwords`: http://www.informit.com/articles/article.asp?p=412909&seqNum=9&rl=1
.. _`To Stopword or Not to Stopword?`: http://www.ultraseek.com/articles/archives/2005/09/to_stopword_or.html
.. _`RE: [Snowball-discuss] Stop word lists`: http://www.snowball.tartarus.org/archives/snowball-discuss/0320.html
.. _`Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries`: http://lucene.apache.org/tika/
.. _`Aperture, Extract full-text and metadata from many common file formats`: http://aperture.sourceforge.net/
.. _`Getting started (Appears to use Java 1.5)`: ../aperture/getting-started.html
.. _`OpenXML4j is a complete Java framework supporting Open Package Convention`: http://sourceforge.net/projects/openxml4j/
.. _`Parsing HTML with java`: http://jtoee.blogspot.com/2007/11/parsing-html-with-htmleditorkitparserca.html
.. _`HTMLEditorKit`: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/html/HTMLEditorKit.html
.. _`JTidy`: http://jtidy.sourceforge.net/
.. _`HTML Parser`: http://htmlparser.sourceforge.net/
.. _`HTML Cleaner`: http://htmlcleaner.sourceforge.net/
.. _`Maven repository notes`: ../../info/computers/slinky/maven-repository.html
.. _`wv is a library which allows access to Microsoft Word files`: http://wvware.sourceforge.net/
.. _`catdoc is program which reads one or more Microsoft word files and outputs text`: http://www.45.free.net/~vitus/software/catdoc/
.. _`catdoc, xls2csv and catppt`: http://www.wagner.pp.ru/~vitus/software/catdoc/
.. _`Antiword is a free MS Word reader for Linux`: http://www.winfield.demon.nl/
.. _`Using Java to Crack Office 2007`: http://www.infoq.com/articles/cracking-office-2007-with-java
.. _`JOOConverter automates conversions between office document formats using OpenOffice.org`: http://sourceforge.net/projects/joott/
.. _`file2xliff4j is a set of Java classes to convert HTML, Word, Excel, OpenOffice.org Text, PowerPoint, RTF and MIF documents to XLIFF File Format`: http://file2xliff4j.sourceforge.net/
.. _`The Compass Framework`: http://www.compassframework.org
.. _`Enhydra Snapper - Fulltext Indexing and Search`: http://www.enhydra.org/apps/snapper/index.html
.. _`Hibernate Search brings the power of full text search engines to the persistence domain model`: http://search.hibernate.org/
.. _`Hibernate Annotations`: http://www.hibernate.org/hib_docs/annotations/reference/en/html/lucene.html
.. _`Kowari is an Open Source`: http://www.kowari.org/
.. _DBSight: http://www.dbsight.net/
.. _`NetSearch - the Enterprise Search Solution from Ardentia`: http://www.ardentia.com/
.. _Solr: http://lucene.apache.org/solr/
.. _`LIUS is an indexing Java framework based on the Jakarta Lucene project`: http://sourceforge.net/projects/lius/
.. _`Tika, a generic document parsing framework`: http://code.google.com/p/tika/
.. _sample-lucene-did-you-mean: http://toybox/hg/sample/file/tip/java/sample-lucene-did-you-mean
.. _sample-lucene-count-unique-terms: http://toybox/hg/sample/file/tip/java/sample-lucene-count-unique-terms
.. _`Lucene 2.4 in 60 seconds`: http://lingpipe-blog.com/2009/02/18/lucene-24-in-60-seconds/
.. _`Kevin's Word List Page`: http://wordlist.sourceforge.net/


text:
package tests.javax_servlet.ServletResponseWrapper;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import common.util.StaticLog;
import java.util.Enumeration;

/**
 *	Negative Test for ServletResponse.reset() method.
 */

public class ServletResponseWrapperReset_1TestServlet extends GenericServlet {

    StaticLog sl = new StaticLog();

    public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        sl.resetLog();

        response.setBufferSize( 11 );
        out.println( "in ServletResponseWrapperReset_1Test servlet
" );
        response.flushBuffer();

        try {
            response.reset();
            out.println( "ServletResponseWrapperReset_1Test test FAILED
" );
        } catch ( IllegalStateException e ) {
            out.println( "ServletResponseWrapperReset_1Test test PASSED
" );
        }

        Enumeration e = sl.readFromLog();

        while ( e.hasMoreElements() ) {
            String tmp = ( String ) e.nextElement();
            out.println( tmp );
        }
    }
}


text:
package org.pm4j.core.pm;

import java.util.List;

import org.pm4j.core.exception.PmRuntimeException;

/**
 * A PM for a tab set.
 *
 * @author olaf boede
 */
public interface PmTabSet extends PmObject {

  /**
   * This method gets called whenever the user or internal UI logic attempts
   * to switch from one opened tab to another one.
   *
   * @param toTab
   *          The tab to switch to.
   * @return true if the PM logic implementation allows the tab switch.

   *         false if the PM logic implementation prevents the tab switch.
   */
  boolean switchToTabPm(PmTab toTab);

  /**
   * @return The currently active tab.
   */
  PmTab getCurrentTabPm();

  /**
   * @return The set of tabs.
   */
  List<PmTab> getTabPms();

  /**
   * Provides the index position of the given {@link PmTab}.
   *
   * @param tabPm a {@link PmTab} that belongs to this tab set.
   * @return the tab index position. Starts with zero.
   * @throws PmRuntimeException if the given tab is not part of the tab set.
   */
  int getTabIndex(PmTab pmTab);

}