text:
require 'chef/json_compat'
require 'chef/log'

module FB
  # Various utility grab-bag.
  class Helpers
    NW_CHANGES_ALLOWED = '/run/chef/chef_nw_changes_allowed'.freeze
    NW_CHANGES_NEEDED = '/run/chef/chef_pending_nw_changes_needed'.freeze

    # attempt_lazy() should be used when attempting to write a lazy block to
    # an api attribute.
    #
    # Usage:
    #   attempt_lazy { my_var }
    #
    # Arguments:
    #   block: A block to be used by the DelayedEvaluator or evaluated
    #
    # Notes:
    # - For clients running a version of chef less than 17.0.42
    #   DelayedEvaluators will not be automatically called when they are
    #   read from the node object. To prevent breaking older clients, the
    #   passed in block will be evaluated immediately and a value will
    #   be returned instead of a DelayedEvaluator.
    def self.attempt_lazy(&block)
      if Chef::Version.new(Chef::VERSION) < Chef::Version.new('17.0.42')
        Chef::Log.warn(
          'fb_helpers.attempt_lazy: Lazy attributes are not supported on ' +
          'chef versions before 17.0.42. Evaluating block immediately ' +
          'and returning value rather than a DelayedEvaluator',
        )
        block.call
      else
        Chef::DelayedEvaluator.new { block.call }
      end
    end

    # evaluate_lazy_hash() should be used to evaluate an object that contains
    # DelayedEvaluators that will not be assigned to an attribute and hence be
    # evaluated
    #
    # Usage:
    #   evaluate_lazy_enumerable { my_enumerable }
    #
    # Arguments:
    #   my_enumerable: An enumerable that contains elements that should be evaluated
    #
    def self.evaluate_lazy_enumerable(my_enumerable)
      if my_enumerable.respond_to?(:each_pair)
        my_enumerable.each_pair do |key, value|
          if value.respond_to?(:each)
            evaluate_lazy_enumerable(value)
          elsif value.is_a?(::Chef::DelayedEvaluator)
            my_enumerable[key] = value.call
          end
        end
      elsif my_enumerable.respond_to?(:each)
        my_enumerable.each_with_index do |element, index|
          if element.respond_to?(:each)
            evaluate_lazy_enumerable(element)
          elsif element.is_a?(::Chef::DelayedEvaluator)
            my_enumerable[index] = element.call
          end
        end
      end
    end

    # commentify() takes a text string and converts it to a (possibly)
    # multi-line comment suitable for dropping into a config file.
    #
    # Usage:
    #   commentify(text, argHash)
    #
    # Arguments:
    #   text:    Required string. The string to convert to a comment
    #   arghash: An optional hash with the following (optional) keys:
    #   arghash['start']:     String to use for starting comment char(s)
    #                         Defaults to '#'
    #   arghash['finish']:    String used to close off entire
    #                         section of text, instead of leading each line
    #                         Defaults to empty string.
    #   arghash['width']:     Total line width (integer) of the config file.
    #                         Defaults to 80.
    #
    # Notes:
    # - 'text' arg will have all whitespace (including newlines) collapsed to a
    #   single space.
    # - If only 'start' is specified, string will be broken up into
    #   multiple lines, with each preceded by the start tag and padding
    # - If 'finish' is also specified, the entire string will be broken up
    #   similarly to above, except that only one leading and one trailing
    #   tag are used in total.
    # - Line width is the total width of the file you are inserting comments
    #   into, including the leading comment chars and padding
    # - Any words (tokens) longer than a full line are inserted at the start of
    #   their own line and printed contiguously in the config file. They will
    #   NOT be split up among multiple-lines.
    # - A minimum of one trailing space will be used as padding for each line
    def self.commentify(comment, arghash = {})
      defaults = { 'start' => '#', 'finish' => '', 'width' => 80 }
      arghash = defaults.merge(arghash)

      usage = %{
commentify(text, args)

commentify() takes one required string argument, followed by an optional hash.
If the has is specified, it takes one or more of the following keys:
'start', 'finish', 'width'
}

      # First arg must be a string that is not all whitespace
      if !comment.is_a?(String) || comment.match(/^\s*$/)
        fail usage
      end

      # Extract variable
      start = arghash['start']
      finish = arghash['finish']
      width = arghash['width']

      # Adjust the following variables to control padding:
      # - For comments with comment char at front of each line
      single_line_pad = 1
      # - Amount of padding at end of each line of all comments
      end_pad = 1

      # Contents of each line as we go
      curr_line = ''
      # Put comment in here to return
      final_comment = ''

      # >>> Start constructing the actual comment <<<
      # First thing to go into comment (always) is comment start tag
      curr_line = start

      # For multi-line comments, line-break right after initial start tag
      if finish == ''
        # For single-line comments, just pad and keep going w/ first line
        curr_line += ' ' * single_line_pad
        prefix = start + ' ' * single_line_pad
      else
        final_comment += "#{curr_line}\n"
        curr_line = ''
        prefix = ''
      end

      # Split on whitespace into an array
      words = comment.split(/\s+/)
      words.each do |word|
        # Determine how much writing space we have left
        space_avail = width - (curr_line.size + end_pad)
        # If the next word won't fit, handle a couple of special cases
        if word.length > space_avail
          # If we already have content on the line, then just line-break it
          if curr_line.empty?
            # If we get here, we are at start of line, and word is STILL
            # too long; force it in and violate the line-width.
            final_comment += "#{prefix}#{word}\n"
            curr_line = ''
          else
            final_comment += "#{curr_line.strip}\n"
            curr_line = "#{prefix}#{word} "
          end
        else
          # Space is available. Add word to line, adding start tag if needed
          if curr_line.empty?
            curr_line = prefix
          end
          curr_line += "#{word} "
        end
      end
      # No more words.
      # Add final line but only if the line already has content.
      unless curr_line.empty?
        final_comment += curr_line.strip
      end
      # Add closing comment if defined
      if finish != ''
        final_comment += "\n#{finish}"
      end
      final_comment
    end

    # filter_hash() takes two Hash objects and applies the second as a filter
    # on the first one.
    #
    # Usage:
    #   filter_hash(hash, filter)
    #
    # Arguments:
    #   hash: Required Hash. The Hash to be filtered
    #   filter: Required Hash. The filter to apply against hash
    #
    # Sample usage:
    # hash = {
    #   'foo' => 1,
    #   'bar' => 2,
    #   'baz' => {
    #     'cake' => 'asdf',
    #     'pie' => 42,
    #   },
    # }
    #
    # filter = ['foo', 'baz/cake']
    #
    # filter_hash(hash, filter) = {
    #   'foo' => 1,
    #   'baz' => {
    #     'cake' => 'asdf',
    #   },
    # }
    def self.filter_hash(hash, filter)
      self._filter_hash(hash, self._expand_filter(filter))
      # self._filter_hash_alt(hash, filter)
    end

    # helper method to convert AttributeAllowlist-style filters to something
    # usable by _filter_hash
    def self._expand_filter(array_filter)
      hash_filter = {}
      array_filter.each do |f|
        keys = f.split('/')
        h = nil
        keys.reverse_each do |k|
          h = { k => h }
        end
        self.merge_hash!(hash_filter, h)
      end
      hash_filter
    end

    # alternate implementation using AttributeAllowlist; does not work yet due
    # to https://github.com/chef/chef/issues/10276
    def self._filter_hash_alt(hash, filter)
      if FB::Version.new(Chef::VERSION) >= FB::Version.new('16.3')
        require 'chef/attribute_allowlist'
        Chef::AttributeAllowlist.filter(hash, filter)
      else
        require 'chef/whitelist'
        Chef::Whitelist.filter(hash, filter)
      end
    end

    # private method to implement filter_hash using recursion
    # note: we can't use Chef::AttributeAllowlist here because it doesn't
    # handle empty values properly at the moment
    def self._filter_hash(hash, filter, depth = 0)
      unless filter.is_a?(Hash)
        fail 'fb_helpers: the filter argument to filter_hash needs to be a ' +
          "Hash (actual: #{filter.class})"
      end

      filtered_hash = {}

      # We loop over the filter and pull out only allowed items from the hash
      # provided by the user. Since users might pass in something huge like
      # the entire saved node object, don't make the performance of this code
      # be defined by them.
      filter.each do |k, v|
        if hash.include?(k)
          if v.nil?
            filtered_hash[k] = hash[k]
          elsif v.is_a?(Hash)
            # we need to go deeper
            ret = self._filter_hash(hash[k], v, depth + 1)
            # if the filter returned nil, it means it had no matches, so
            # don't add it to the filtered_hash to avoid creating spurious
            # entries
            unless ret.nil?
              filtered_hash[k] = ret
            end
          else
            fail "fb_helpers: invalid filter passed to filter_hash: #{filter}"
          end
        else
          Chef::Log.debug(
            "fb_helpers: skipping key #{k} as it is missing from the hash",
          )
        end
      end

      # if we're recursing and get an empty hash here, it means we had no
      # matches; change it to nil so we can detect it appropriately in the
      # loop above
      if depth > 0 && filtered_hash == {}
        filtered_hash = nil
      end

      filtered_hash
    end

    # safe_dup() takes an object and duplicates it. This method always returns
    # a valid object, even if thing is not dup'able.
    #
    # This method is based on lib/chef/mixin/deep_merge.rb from
    # https://github.com/chef/chef at revision
    # 5c8383fedd13b07f13d64a58f7cc78664a235ced.
    #
    # Usage:
    #   safe_dup(thing)
    #
    # Arguments:
    #   thing: Required object. The object to duplicate.
    def self.safe_dup(thing)
      thing.dup
    rescue TypeError
      thing
    end

    # merge_hash() takes two hashes and returns the result of recursively
    # merging one onto the other. Only hashes are merged -- other objects,
    # including arrays, will be replaced. Leaf hashes are also merged by
    # default; this can be changed with overwrite_leaves, which will replace
    # them instead.
    #
    # This method is based on lib/chef/mixin/deep_merge.rb from
    # https://github.com/chef/chef at revision
    # 5c8383fedd13b07f13d64a58f7cc78664a235ced.
    #
    # Usage:
    #   merge_hash(merge_onto, merge_with, overwrite_leaves)
    #
    # Arguments:
    #   merge_onto: Required hash. The base hash that will be merged onto
    #   merge_with: Required hash. The hash that will be merged on merge_onto
    #   overwrite_leaves: Optional boolean. Whether to overwrite leaves or not
    def self.merge_hash(merge_onto, merge_with, overwrite_leaves = false)
      self.merge_hash!(safe_dup(merge_onto), safe_dup(merge_with),
                       overwrite_leaves)
    end

    # merge_hash!() takes two hashes and recursively merges one onto the
    # other, altering it in place, and returns the merged hash. See
    # merge_hash() for details on the merge semantics.
    #
    # This method is based on lib/chef/mixin/deep_merge.rb from
    # https://github.com/chef/chef at revision
    # 5c8383fedd13b07f13d64a58f7cc78664a235ced.
    #
    # Usage:
    #   merge_hash(merge_onto, merge_with, overwrite_leaves)
    #
    # Arguments:
    #   merge_onto: Required hash. The base hash that will be merged onto
    #   merge_with: Required hash. The hash that will be merged on merge_onto
    #   overwrite_leaves: Optional boolean. Whether to overwrite leaves or not
    def self.merge_hash!(merge_onto, merge_with, overwrite_leaves = false)
      # If there are two Hashes, recursively merge.
      if merge_onto.is_a?(Hash) && merge_with.is_a?(Hash)
        merge_with.each do |key, merge_with_value|
          is_leaf = false
          if overwrite_leaves && merge_with_value.is_a?(Hash)
            # if we're overwriting leaves, we need to know when we have one
            merge_with_value.each do |_k, v|
              if v.is_a?(Hash)
                is_leaf = true
                break
              end
            end
          end

          if merge_onto.key?(key)
            if is_leaf
              value = merge_onto[key]
              merge_with_value.each do |k, _v|
                value[k] = merge_with_value[k]
              end
            else
              value = self.merge_hash(merge_onto[key], merge_with_value,
                                      overwrite_leaves)
            end
          else
            value = merge_with_value
          end

          merge_onto[key] = value
        end
        merge_onto
      else
        # In all other cases, replace merge_onto with merge_with
        merge_with
      end
    end

    # parse_json() takes a JSON string and converts it to a Ruby object,
    # also enforcing that the top-level object matches what is expected.
    #
    # Usage:
    #   parse_json(json_string, top_level_class)
    #
    # Arguments:
    #   json_string: Required string. The JSON string to parse.
    #   top_level_class: Optional class, defaults to Hash.
    #   fallback: Optional boolean, defaults to false.
    def self.parse_json(json_string, top_level_class = Hash, fallback = false)
      unless [Array, Hash, String].include?(top_level_class)
        fail 'fb_helpers: top_level_class can only be Array, Hash or ' +
          "(actual: #{top_level_class})"
      end

      begin
        parsed_json = Chef::JSONCompat.parse(json_string)
      rescue Chef::Exceptions::JSON::ParseError => e
        m = 'fb_helpers: cannot parse string as JSON; returning an empty ' +
            "#{top_level_class} instead: #{e}"
        if fallback
          Chef::Log.error(m)
          return top_level_class.new
        else
          # rubocop:disable Style/SignalException
          fail m
          # rubocop:enable Style/SignalException
        end
      end

      unless parsed_json.is_a?(top_level_class)
        m = 'fb_helpers: parsed JSON does not match the expected ' +
            "#{top_level_class} (actual: #{parsed_json.class})"
        if fallback
          Chef::Log.error(m)
          return top_level_class.new
        else
          fail m
        end
      end

      parsed_json
    end

    # parse_json_file() takes a path string and converts its contents to a
    # Ruby object, also enforcing that the top-level object matches what is
    # expected.
    #
    # Usage:
    #   parse_json_file(path, top_level_class, fallback)
    #
    # Arguments:
    #   path: Required string. Path to the file to parse.
    #   top_level_class: Optional class, defaults to Hash.
    #   fallback: Optional boolean, defaults to false.
    def self.parse_json_file(path, top_level_class = Hash, fallback = false)
      Chef::Log.debug(
        "fb_helpers: parsing #{path} as JSON (expecting: #{top_level_class})",
      )

      begin
        content = File.read(path)
      rescue IOError, SystemCallError => e
        # SystemCallError is because of -ENOENT
        m = "fb_helpers: cannot read #{path}: #{e}"
        if fallback
          Chef::Log.error(m)
          return top_level_class.new
        else
          # rubocop:disable Style/SignalException
          fail m
          # rubocop:enable Style/SignalException
        end
      end

      self.parse_json(content, top_level_class, fallback)
    end

    # parse_timeshard_start() takes a time string and converts its contents to a
    # unix timestamp, to be used in computing timeshard information
    #
    # Usage:
    #   parse_timeshard_start(time)
    #
    # Arguments:
    #   time: A valid time string
    def self.parse_timeshard_start(time)
      # Validate the time string matches our prescribed format.
      begin
        st = Time.parse(time).tv_sec
      rescue ArgumentError
        errmsg = "fb_helpers: Invalid start_time arg '#{time}' for " +
                 'FB::Helpers.parse_timeshard_start'
        raise errmsg
      end
      st
    end

    # parse_timeshard_duration() takes a duration string and converts
    # its contents to a to an int to be used in computing timeshard information
    #
    # Usage:
    #   parse_timeshard_duration(duration)
    #
    # Arguments:
    #   duration: A valid duration string, in days or hours
    def self.parse_timeshard_duration(duration)
      # Multiply the number of days by 1440 min and 60 s to convert a day into
      # seconds.
      if duration.match('^[0-9]+[dD]$')
        duration = duration.to_i * 1440 * 60
      # Multiply the number of hours by 3600 s to convert hours into seconds.
      elsif duration.match('^[0-9]+[hH]$')
        duration = duration.to_i * 3600
      else
        errmsg = "fb_helpers: Invalid duration arg, '#{duration}' for " +
                 'FB::Helpers.parse_timeshard_duration'
        fail errmsg
      end
      duration
    end

    def self.linux?
      RUBY_PLATFORM.include?('linux')
    end

    def self.windows?
      RUBY_PLATFORM =~ /mswin|mingw32|windows/
    end

    # mountpoint? determines if a path string represents a mountpoint
    #
    # Usage:
    #   mountpoint?(path)
    #
    # Arguments:
    #   path: A string-compatible object that represents a path to test
    def self.mountpoint?(path)
      Pathname.new(path.to_s).mountpoint?
    end

    # date_of_last() takes a day of the week and finds the most recent
    # date this day fell on
    #
    # Usage:
    #   date_of_last(day)
    #
    # Arguments:
    #   day: A string representing a day of the week. Can be long-form
    #        (e.g. "Monday") or abbreviate (e.g. "Wed")
    def self.date_of_last(day)
      # Gets you the date of the last day passed
      date  = Date.parse(day)
      delta = date < Date.today ? 0 : 7
      (date - delta).to_s
    end

    # sysnative_path() determines the sysnative path on Windows
    def self.sysnative_path
      fail unless self.windows?

      if RUBY_PLATFORM.include?('64')
        "#{ENV['WINDIR']}\\system32\\"
      else
        "#{ENV['WINDIR']}\\sysnative\\"
      end
    end

    # warn_to_remove() is used in sharding operations to help
    # discover old sharding code
    def self.warn_to_remove(
      stack_depth, msg = 'fb_helpers: Past time shard duration! Please cleanup!'
    )
      stack = caller(stack_depth, 1)[0]
      parts = %r{^.*/cookbooks/([^/]*)/([^/]*)/(.*)\.rb:(\d+)}.match(stack)
      if parts
        where = "(#{parts[1]}::#{parts[3]} line #{parts[4]})"
      else
        where = stack
      end
      Chef::Log.warn("#{msg} #{where}")
    end

    # Normally preferred testing for existence of a user is via
    # node['etc']['passwd'], but if the user was added in the same chef run
    # then ohai won't have it.
    def self.user_exist?(user_name)
      Etc.getpwnam(user_name)
      true
    rescue ArgumentError
      false
    end

    # Normally preferred testing for existence of a group is via
    # node['etc']['group'], but if the group was added in the same chef run
    # then ohai won't have it.
    def self.group_exist?(group_name)
      Etc.getgrnam(group_name)
      true
    rescue ArgumentError
      false
    end

    def self._request_nw_changes_permission(run_context, new_resource)
      run_context.node.default['fb_helpers']['_nw_perm_requested'] = true
      notification = Chef::Resource::Notification.new(
        'fb_helpers_request_nw_changes[manage]',
        :request_nw_changes,
        new_resource,
      )
      notification.fix_resource_reference(run_context.resource_collection)
      run_context.root_run_context.add_delayed_action(notification)
    end
  end

  # Helper class to compare software versions.
  # Sample usage:
  #   Version.new('1.3') < Version.new('1.21')
  #   => true
  #   Version.new('4.5') < Version.new('4.5')
  #   => false
  #   Version.new('3.3.10') > Version.new('3.4')
  #   => false
  #   Version.new('10.2') >= Version.new('10.2')
  #   => true
  #   Version.new('1.2.36') == Version.new('1.2.36')
  #   => true
  #   Version.new('3.3.4') <= Version.new('3.3.02')
  #   => false

  # Our version comparison class
  class Version < Array
    # This is intentional.
    # rubocop:disable Lint/MissingSuper
    def initialize(s)
      @string_form = s
      if s.nil?
        @arr = []
        return
      end
      @arr = s.split(/[._-]/).map(&:to_i)
    end
    # rubocop:enable Lint/MissingSuper

    def to_s
      @string_form
    end

    def to_a
      @arr
    end

    def compare(other, exact = true)
      other ||= new
      unless other.is_a?(FB::Version)
        other = FB::Version.new(other)
      end
      if exact
        @arr <=> other.to_a
      else
        len = [@arr.length, other.to_a.length].min
        @arr[0, len] <=> other[0, len]
      end
    end

    alias_method '<=>', :compare

    def <=(other)
      compare(other) <= 0
    end

    def >=(other)
      compare(other) >= 0
    end

    def <(other)
      compare(other).negative?
    end

    def >(other)
      compare(other).positive?
    end

    def ==(other)
      compare(other).zero?
    end

    def [](*args)
      @arr[*args]
    end

    def ===(other)
      # Useful to use in case statements
      compare(other, false).zero?
    end

    # Oh, come on rubocop...
    def inspect
      @string_form
    end
  end
end


text:
package net.binarycreations.apod.app.background;

import android.os.AsyncTask;

import java.lang.ref.WeakReference;

/**
 *
 *
 * @author graham.
 */
final class AsyncTaskRunner<T> extends AsyncTask<Void, Void, T> {

    private WeakReference<BackgroundJob<T>> mJob;

    private WeakReference<Conclusion<T>> mConclusion;

    private Exception mJobError;

    AsyncTaskRunner(WeakReference<BackgroundJob<T>> backgroundJob, WeakReference<Conclusion<T>> conclusion) {
        mJob = backgroundJob;
        mConclusion = conclusion;
    }

    @Override
    protected T doInBackground(Void... params) {
        T result = null;

        BackgroundJob<T> toRun = mJob.get();
        if (toRun != null) {
            try {
                result = toRun.doInBackground();
            } catch (Exception e) {
                mJobError = e;
            }
        }

        return result;
    }

    @Override
    protected void onPostExecute(T result) {
        super.onPostExecute(result);

        Conclusion<T> toCallBack = mConclusion.get();
        if (toCallBack != null) {
            if (mJobError != null) {
                toCallBack.onError(mJobError);
            } else if (result != null) {
                toCallBack.onConclusion(result);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.script.mvel;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.Scorer;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.math.UnboxedMathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptEngineService;
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.lookup.SearchLookup;
import org.mvel2.MVEL;
import org.mvel2.ParserConfiguration;
import org.mvel2.ParserContext;
import org.mvel2.compiler.ExecutableStatement;
import org.mvel2.integration.impl.MapVariableResolverFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class MvelScriptEngineService extends AbstractComponent implements ScriptEngineService {

    private final ParserConfiguration parserConfiguration;

    @Inject
    public MvelScriptEngineService(Settings settings) {
        super(settings);

        parserConfiguration = new ParserConfiguration();
        parserConfiguration.addPackageImport("java.util");
        parserConfiguration.addPackageImport("gnu.trove");
        parserConfiguration.addPackageImport("org.joda");
        parserConfiguration.addImport("time", MVEL.getStaticMethod(System.class, "currentTimeMillis", new Class[0]));
        // unboxed version of Math, better performance since conversion from boxed to unboxed my mvel is not needed
        for (Method m : UnboxedMathUtils.class.getMethods()) {
            if ((m.getModifiers() & Modifier.STATIC) > 0) {
                parserConfiguration.addImport(m.getName(), m);
            }
        }
    }

    @Override
    public void close() {
        // nothing to do here...
    }

    @Override
    public String[] types() {
        return new String[]{"mvel"};
    }

    @Override
    public String[] extensions() {
        return new String[]{"mvel"};
    }

    @Override
    public Object compile(String script) {
        return MVEL.compileExpression(script, new ParserContext(parserConfiguration));
    }

    @Override
    public Object execute(Object compiledScript, Map vars) {
        return MVEL.executeExpression(compiledScript, vars);
    }

    @Override
    public ExecutableScript executable(Object compiledScript, Map vars) {
        return new MvelExecutableScript(compiledScript, vars);
    }

    @Override
    public SearchScript search(Object compiledScript, SearchLookup lookup, @Nullable Map<String, Object> vars) {
        return new MvelSearchScript(compiledScript, lookup, vars);
    }

    @Override
    public Object unwrap(Object value) {
        return value;
    }

    public static class MvelExecutableScript implements ExecutableScript {

        private final ExecutableStatement script;

        private final MapVariableResolverFactory resolver;

        public MvelExecutableScript(Object script, Map vars) {
            this.script = (ExecutableStatement) script;
            if (vars != null) {
                this.resolver = new MapVariableResolverFactory(vars);
            } else {
                this.resolver = new MapVariableResolverFactory(new HashMap());
            }
        }

        @Override
        public void setNextVar(String name, Object value) {
            resolver.createVariable(name, value);
        }

        @Override
        public Object run() {
            return script.getValue(null, resolver);
        }

        @Override
        public Object unwrap(Object value) {
            return value;
        }
    }

    public static class MvelSearchScript implements SearchScript {

        private final ExecutableStatement script;

        private final SearchLookup lookup;

        private final MapVariableResolverFactory resolver;

        public MvelSearchScript(Object script, SearchLookup lookup, Map<String, Object> vars) {
            this.script = (ExecutableStatement) script;
            this.lookup = lookup;
            if (vars != null) {
                this.resolver = new MapVariableResolverFactory(vars);
            } else {
                this.resolver = new MapVariableResolverFactory(new HashMap());
            }
            for (Map.Entry<String, Object> entry : lookup.asMap().entrySet()) {
                resolver.createVariable(entry.getKey(), entry.getValue());
            }
        }

        @Override
        public void setScorer(Scorer scorer) {
            lookup.setScorer(scorer);
        }

        @Override
        public void setNextReader(AtomicReaderContext context) {
            lookup.setNextReader(context);
        }

        @Override
        public void setNextDocId(int doc) {
            lookup.setNextDocId(doc);
        }

        @Override
        public void setNextScore(float score) {
            resolver.createVariable("_score", score);
        }

        @Override
        public void setNextVar(String name, Object value) {
            resolver.createVariable(name, value);
        }

        @Override
        public void setNextSource(Map<String, Object> source) {
            lookup.source().setNextSource(source);
        }

        @Override
        public Object run() {
            return script.getValue(null, resolver);
        }

        @Override
        public float runAsFloat() {
            return ((Number) run()).floatValue();
        }

        @Override
        public long runAsLong() {
            return ((Number) run()).longValue();
        }

        @Override
        public double runAsDouble() {
            return ((Number) run()).doubleValue();
        }

        @Override
        public Object unwrap(Object value) {
            return value;
        }
    }
}


text:
package me.dpohvar.powernbt.nbt;

import org.bukkit.ChatColor;

import static me.dpohvar.powernbt.PowerNBT.plugin;
import static org.bukkit.ChatColor.*;

public enum NBTType {
    END((byte) 0, "end", "\u24EA", WHITE), // ⓪
    BYTE((byte) 1, "byte", "\u24B7", RED), // Ⓑ
    SHORT((byte) 2, "short", "\u24C8", YELLOW), // Ⓢ
    INT((byte) 3, "int", "\u24BE", BLUE), // Ⓘ
    LONG((byte) 4, "long", "\u24C1", AQUA), // Ⓛ
    FLOAT((byte) 5, "float", "\u24BB", DARK_PURPLE), // Ⓕ
    DOUBLE((byte) 6, "double", "\u24B9", LIGHT_PURPLE), // Ⓓ
    BYTEARRAY((byte) 7, "byte[]", ChatColor.BOLD + "\u24D1", DARK_RED), // ⓑ
    STRING((byte) 8, "string", "\u24C9", GREEN), // Ⓣ
    LIST((byte) 9, "list", "\u2630", DARK_GRAY), // ☰
    COMPOUND((byte) 10, "compound", "\u27B2", GRAY), // ➲
    INTARRAY((byte) 11, "int[] ", ChatColor.BOLD + "\u24D8", DARK_BLUE), // ⓘ
    ;
    public final String name;
    public final String prefix;
    public final byte type;
    public final ChatColor color;

    NBTType(byte type, String name, String prefix, ChatColor color) {
        this.type = type;
        this.name = name;
        this.prefix = prefix;
        this.color = color;
    }

    public static NBTType fromByte(byte b) {
        for (NBTType t : values()) if (t.type == b) return t;
        return END;
    }

    public static NBTType fromBase(NBTBase base) {
        if (base == null) return END;
        return fromByte(base.getTypeId());
    }

    public static NBTType fromString(String name) {
        if (name == null || name.isEmpty()) return END;
        String s = name.toLowerCase();
        for (NBTType t : values()) if (s.equalsIgnoreCase(t.name)) return t;
        for (NBTType t : values()) if (t.name.toLowerCase().startsWith(s)) return t;
        return END;
    }

    public NBTBase getDefault() {
        return NBTBase.getDefault(type);
    }

    public NBTBase parse(String s) {
        switch (this) {
            case STRING: {
                return new NBTTagString(s);
            }
            case BYTE: {
                Byte v = null;
                try {
                    v = Byte.parseByte(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (byte) Long.parseLong(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (byte) Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagByte(v);
            }
            case SHORT: {
                Short v = null;
                try {
                    v = Short.parseShort(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (short) Long.parseLong(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (short) Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagShort(v);
            }
            case INT: {
                Integer v = null;
                try {
                    v = Integer.parseInt(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (int) Long.parseLong(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (int) Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagInt(v);
            }
            case LONG: {
                Long v = null;
                try {
                    v = Long.parseLong(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (long) Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagLong(v);
            }
            case DOUBLE: {
                Double v = null;
                try {
                    if (s.equalsIgnoreCase("NaN")) v = Double.NaN;
                    else v = Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagDouble(v);
            }
            case FLOAT: {
                Float v = null;
                try {
                    if (s.equalsIgnoreCase("NaN")) v = Float.NaN;
                    else v = Float.parseFloat(s);
                } catch (Throwable ignored) {
                }
                if (v == null) try {
                    v = (float) (double) Double.parseDouble(s);
                } catch (Throwable ignored) {
                }
                if (v == null) throw new RuntimeException(plugin.translate("error_parse", s, this.name));
                return new NBTTagFloat(v);
            }
            case BYTEARRAY: {
                if (!s.matches("\\[((-?[0-9]+|#-?[0-9a-fA-F]+)(,(?!\\])|(?=\\])))*\\]")) {
                    throw new RuntimeException(plugin.translate("error_parse", s, INTARRAY.name));
                }
                String sp = s.substring(1, s.length() - 1);
                if (sp.isEmpty()) return new NBTTagByteArray();
                String[] ss = sp.split(",");
                byte[] v = new byte[ss.length];
                for (int i = 0; i < v.length; i++) {
                    Byte t = null;
                    String x = ss[i];
                    if (x.startsWith("#")) try {
                        t = (byte) Long.parseLong(x.substring(1), 16);
                    } catch (Throwable ignored) {
                    }
                    try {
                        t = Byte.parseByte(x);
                    } catch (Throwable ignored) {
                    }
                    if (t == null) try {
                        t = (byte) (long) Long.parseLong(x);
                    } catch (Throwable ignored) {
                    }
                    if (t == null) throw new RuntimeException(plugin.translate("error_parse", x, BYTE.name));
                    v[i] = t;
                }
                return new NBTTagByteArray(v);
            }
            case INTARRAY: {
                if (!s.matches("\\[((-?[0-9]+|#-?[0-9a-fA-F]+)(,(?!\\])|(?=\\])))*\\]")) {
                    throw new RuntimeException(plugin.translate("error_parse", s, INTARRAY.name));
                }
                String sp = s.substring(1, s.length() - 1);
                if (sp.isEmpty()) return new NBTTagIntArray();
                String[] ss = sp.split(",");
                int[] v = new int[ss.length];
                for (int i = 0; i < v.length; i++) {
                    Integer t = null;
                    String x = ss[i];
                    if (x.startsWith("#")) try {
                        t = (int) Long.parseLong(x.substring(1), 16);
                    } catch (Throwable ignored) {
                    }
                    try {
                        t = Integer.parseInt(x);
                    } catch (Throwable ignored) {
                    }
                    if (t == null) try {
                        t = (int) (long) Long.parseLong(x);
                    } catch (Throwable ignored) {
                    }
                    if (t == null) throw new RuntimeException(plugin.translate("error_parse", x, INT.name));
                    v[i] = t;
                }
                return new NBTTagIntArray(v);
            }
            default: {
                throw new RuntimeException(plugin.translate("error_parse", s, this.name));
            }
        }
    }
}


text:
package it.geosolutions.geoserver.rest.encoder;

import junit.framework.TestCase;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
 */
public class GSWorkspaceEncoderTest extends TestCase {

    /**
     * Default logger
     */
    protected final static Logger LOGGER = LoggerFactory.getLogger(GSWorkspaceEncoderTest.class);

    @Test
    public void testAll() {
        final GSWorkspaceEncoder wsenc = new GSWorkspaceEncoder("WS1");
        LOGGER.info(wsenc.toString());

        wsenc.setName("test_name");
        LOGGER.info(wsenc.toString());
        wsenc.setName("new_name");
        LOGGER.info(wsenc.toString());

    }
}


text:
package com.swfarm.biz.chain.web;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.bo.ShippingMethod;
import com.swfarm.biz.chain.dto.SearchShippingMethodsCriteria;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.dto.SearchAllocationProductVouchersCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.utils.DateUtils;
import com.swfarm.pub.utils.ImageUtils;

public class DownloadYwAllocationProductVouchersController extends AbstractController {

	private static final String[] titles = { "单号" };

	private static final double MAGIC_FACTOR = 1.112877583;

	private WarehouseService warehouseService;

	private ChainService chainService;

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception {
		SearchAllocationProductVouchersCriteria criteria = new SearchAllocationProductVouchersCriteria();

		String shippingChannel = "燕文物流";
		criteria.setShippingChannel(shippingChannel);
		Date startDate = DateUtils.stringToDate(req.getParameter("startDate"), "yyyy/MM/dd");
		Date endDate = DateUtils.stringToDate(req.getParameter("endDate"), "yyyy/MM/dd");

		criteria.setDeliverStartDate(startDate);
		criteria.setDeliverEndDate(endDate);

		List allocationProductVouchers = this.warehouseService.searchAllocationProductVouchers(criteria);

		HSSFWorkbook wb = new HSSFWorkbook();
		Map<String, CellStyle> styles = createStyles(wb);
		HSSFSheet sheet = wb.createSheet("客户订单");
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(false);
		sheet.setAutobreaks(true);
		printSetup.setFitHeight((short) 1);
		printSetup.setFitWidth((short) 1);
		HSSFRow headerRow = sheet.createRow(0);
		headerRow.setHeightInPoints(12.75f);
		for (int i = 0; i < titles.length; i++) {
			HSSFCell cell = headerRow.createCell(i);
			cell.setCellValue(titles[i]);
			cell.setCellStyle(styles.get("header"));
		}
		HSSFRow row = null;
		HSSFCell cell = null;
		for (int i = 0; i < 4; i++) {
			sheet.setColumnWidth(i, (int) (15 * 256 * MAGIC_FACTOR));
		}
		int rowCounter = 1;
		SearchShippingMethodsCriteria searchCriteria = new SearchShippingMethodsCriteria();
		searchCriteria.setShippingCompanyCode("yanwen");
		List shippingMethods = this.chainService.searchShippingMethods(searchCriteria);
		List sfmCodes = new ArrayList();
		for (Iterator iter = shippingMethods.iterator(); iter.hasNext();) {
			ShippingMethod shippingMethod = (ShippingMethod) iter.next();
			sfmCodes.add(shippingMethod.getCode());
			logger.warn("yanwen sfm code [" + shippingMethod.getCode() + "]");
		}
		if (CollectionUtils.isNotEmpty(allocationProductVouchers)) {
			for (Iterator iter = allocationProductVouchers.iterator(); iter.hasNext();) {
				AllocationProductVoucher apv = (AllocationProductVoucher) iter.next();

				String sfmCode = apv.getShippingForwarderMethod();

				if (!sfmCodes.contains(sfmCode)) {
					continue;
				}

				row = sheet.createRow(rowCounter);
				int cellCounter = 0;

				String no = apv.getRefShippingOrderNo();
				if (StringUtils.isEmpty(no)) {
					no = apv.getShippingOrderNo();
				}
				if (StringUtils.isEmpty(no)) {
					no = apv.getAllocationProductVoucherNo();
				}
				cell = row.createCell(cellCounter++);
				cell.setCellValue(no);
				cell.setCellStyle(styles.get("cell_normal"));

				rowCounter++;
			}
			res.setContentType("application/ms-excel");
			String fileName = shippingChannel + ".xls";
			res.setHeader("Content-Disposition",
					"attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
			OutputStream out = res.getOutputStream();
			wb.write(out);
			return null;
		} else {
			return new ModelAndView("redirect:/warehouse/search_allocationproductvoucherlists.shtml");
		}
	}

	private static Map<String, CellStyle> createStyles(HSSFWorkbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		DataFormat df = wb.createDataFormat();

		CellStyle style;
		Font headerFont = wb.createFont();
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setFont(headerFont);
		styles.put("header", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setFont(headerFont);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("header_date", style);

		Font font1 = wb.createFont();
		font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
		font1.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font1);
		styles.put("cell_b", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFont(font1);
		styles.put("cell_b_centered", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_b_date", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_g", style);

		Font font2 = wb.createFont();
		font2.setColor(IndexedColors.BLUE.getIndex());
		font2.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font2);
		styles.put("cell_bb", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_bg", style);

		Font font3 = wb.createFont();
		font3.setFontHeightInPoints((short) 10);
		font3.setColor(IndexedColors.DARK_BLUE.getIndex());
		font3.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font3);
		style.setWrapText(true);
		styles.put("cell_h", style);

		Font normalFont = wb.createFont();
		normalFont.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setWrapText(true);
		style.setFont(normalFont);
		styles.put("cell_normal", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setWrapText(true);
		styles.put("cell_normal_centered", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setWrapText(true);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_normal_date", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setIndention((short) 1);
		style.setWrapText(true);
		styles.put("cell_indented", style);

		style = createBorderedStyle(wb);
		style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		styles.put("cell_blue", style);

		return styles;
	}

	private static CellStyle createBorderedStyle(HSSFWorkbook wb) {
		CellStyle style = wb.createCellStyle();
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		return style;
	}

	private static byte[] getImage(String url) {
		return ImageUtils.generateImage(url);
	}

	private String filterIllegalCharacters(String originName) {
		if (StringUtils.isNotEmpty(originName)) {
			String[] illegalCharacters = new String[] { "&", "'" };
			for (int i = 0; i < illegalCharacters.length; i++) {
				String illegalCharacter = illegalCharacters[i];
				originName = originName.replaceAll(illegalCharacter, " ");
			}
		}
		return originName;
	}

}